Premier League Predictor: Django & MySQL — Chapter 9, Exercise 1 ==================================================== TASK Explain why survivors is computed as old_table[:-RELEGATION_COUNT] directly from compute_league_table's own result, rather than by querying the database a second time for "every team except the bottom three," and what real guarantee this relies on from compute_league_table. SOLUTION compute_league_table's own underlying raw SQL ends with a fixed, explicit ORDER BY: points DESC, goal_difference DESC, goals_for DESC. That means the list it returns isn't just "the 20 teams in some order" — it's guaranteed to already be sorted from first place down to last place, every single time it's called, because RawQuerySet has no order_by() of its own (Chapter 7) and the ordering is baked directly into the SQL text itself rather than left to chance. Given that guarantee, the last 3 entries in old_table ARE, by construction, the bottom three teams in the real table — no further lookup is needed to identify them. old_table[-RELEGATION_COUNT:] (the last 3 rows) is the relegated group, and old_table[:-RELEGATION_COUNT] (everything except the last 3) is exactly the survivors, in one plain Python slice against data already fetched and already in the right order. Querying the database a second time for "every team except the bottom three" would be strictly worse in two ways: it would need to somehow re-express the identical ORDER BY + LIMIT/OFFSET logic (or the identical bottom-three-id exclusion logic) a second time in a different query, risking the two queries silently drifting out of sync if one is ever edited without the other; and it would cost a second real database round trip to recompute something the first query already computed in full. Slicing the already-fetched, already- sorted Python list is both simpler and cheaper, and it relies on exactly one guarantee: that compute_league_table's own result is correctly, fully ordered every time, which the explicit ORDER BY in LEAGUE_TABLE_SQL is what actually provides. WHY THIS WORKS AS AN ANSWER ---------------------------- It identifies the specific guarantee the slicing depends on (the query's own explicit ORDER BY, not an assumption), explains why that guarantee makes a second database query unnecessary, and names the real risk (query drift, extra round trips) a second, separately- written query would introduce that the slice avoids entirely.