Finding Top Performers
Rank and retrieve top-N records without pulling millions of unnecessary rows.
Why this matters
Top 5 lists drive decisions, like who to reward or call first. The database can build them quickly.
Let the Database Sort
Let the database do the sorting. It is faster than sorting a huge list on your own computer.
In real life: Let the database do the sorting. It is fast, and you only send the few rows you need.
Use DESC and a Tie-Breaker
ORDER BY total_spend DESC puts the biggest first. Add a second sort, like customer_name ASC, so ties always come out in the same order.
In real life: If two pupils both score 90, who is first? A second rule, like name from A to Z, answers that. Without it, the order might change every time you run the query.
Use LIMIT for a Short List
LIMIT 5 stops the database from sending thousands of extra rows. That keeps dashboards fast.
In real life: A "top 5" slide shows 5 rows, not 5,000. LIMIT keeps the result small, so the dashboard loads fast.
Your practice task
Generate an executive report of the 5 highest-spending VIP customers based on completed sales. Calculate total revenue per customer named total_spend, arrange from greatest to least spending (with customer_name ASC as tie-breaker), and return only the top 5.
How to do it
- Total what each customer spent on completed orders.
- Sort from highest to lowest. Decide what breaks a tie.
- Keep only the top 5.
- Press Run proof and read the checklist.
Practice it for free in the app. You get instant checks that show what you got right and what to fix. A lesson takes about two minutes and you can try as many times as you like.
Quick reference: Top-N Leaderboard Query
Standard pattern for customer VIP segmentation and top salesperson dashboards.
SELECT customer_name, SUM(amount) AS total_spend FROM orders GROUP BY customer_name ORDER BY total_spend DESC, customer_name ASC LIMIT 5;
More lessons in this course
- Crash-Proof DivisionPrevent query crashes and broken dashboards by guarding against division by zero and preserving decimal precision.
- SQL Window Function Running Total ExampleCompute running day-by-day totals without complex self-joins using SQL Window Functions.
- SQL CTE Example: Find Above-Average CustomersBreak a hard question into named steps with WITH, then compare each group to the overall average.