5. ORDER BY, DISTINCT and Top-N Results
5.4 How to Get Top N Rows with ORDER BY and LIMIT
Why. Top-N is a classic interview ask.
What. ORDER BY … DESC LIMIT n gives the top n rows by that sort.
How. Always sort first, then LIMIT.
Steps
- Top 3 amounts.
- Top 5 latest dates (ORDER BY date DESC).
- Say the business meaning in one line.
Examples
Example 1 · dataset: raja_coffee
SELECT order_id, city, amount_inr
FROM orders
ORDER BY amount_inr DESC
LIMIT 3;Output
| order_id | city | amount_inr |
|---|---|---|
| 1016 | Pune | 1780.0 |
| 1013 | Pune | 1680.0 |
| 1007 | Nashik | 1080.0 |
Meaning. Top 3 coffee orders by INR amount.
Ravindra Bagale's Tip
Ties: LIMIT 3 may hide a 4th row with the same amount — know that for interviews.
Ravindra Bagale's Tip – मराठी
टाय: LIMIT 3 समान रकमेची 4 थी रो लपवू शकते — interview साठी लक्षात ठेवा.
Ravindra Bagale's Tip – हिंदी
टाई: LIMIT 3 समान राशि की 4वीं पंक्ति छिपा सकता है — इंटरव्यू के लिए याद रखें।