Sorting and limiting
Hook
“Who’s the leading rusher” is a sort plus a limit. So is “five worst defenses” and “top 10 receiving games this year.” Once you have the sort right, the answer is the top row.
Concept
ORDER BY runs after WHERE. Two things to know:
- Direction.
ASCis the default (ascending).DESCflips it. You almost always wantDESCfor leaderboards. - Tie-breakers. When the sort column ties, the database is free to return rows in any order — unless you add a second sort key. Always tie-break with something stable (a week, a name, an id).
SELECT player_display_name, week, rushing_yardsFROM weekly_statsWHERE recent_team = 'DET' AND season = 2024ORDER BY rushing_yards DESC, week ASCLIMIT 10;LIMIT caps the row count after sorting. LIMIT 1 is the “leader” shortcut.
Lions example
The five biggest Lions receiving games of 2024:
SELECT player_display_name, week, opponent_team, receiving_yards, receiving_tdsFROM weekly_statsWHERE recent_team = 'DET' AND season = 2024 AND season_type = 'REG'ORDER BY receiving_yards DESCLIMIT 5;Add , receiving_tds DESC as a tie-breaker if two players hit the same yardage —
the player with more TDs comes first.
Try it
Find the three lowest-scoring Lions games of 2024 — the games where they
themselves scored the fewest points. You’ll need the schedules table this time.
Hint: the Lions can be the home_team or the away_team. You can use a CASE
expression, or just write two queries and UNION them later (that’s Level 2
territory — for now, just filter to one side and run the query twice).
Common mistakes
- Forgetting
DESC. SQL sorts ascending by default, so without it your “leader” query returns the least. NULLsort order surprises. Postgres putsNULLlast onASCand first onDESC. AddNULLS LASTto keep nulls out of your top-N.LIMITwithoutORDER BY. You get some 10 rows, not the top 10. Always pair them.- Sorting by a column you didn’t select. That’s legal in standard SQL, but it’s worth selecting the column anyway — otherwise you can’t see why the ordering came out the way it did.
Quick check
- What does
ORDER BY rushing_yards DESC NULLS LASTdo? - If you remove
LIMIT 5, what changes about the result? - How would you write “fifth-leading rusher” instead of “leading rusher”?
(Hint:
OFFSET.)