5. ORDER BY, DISTINCT and Top-N Results
5.2 How to Sort by Two Columns (City Then Amount)
Why. Managers often want city groups, then amount inside each city.
What. ORDER BY city, amount_inr DESC sorts by city first, then amount.
How. List sort keys left to right — first key wins ties.
Steps
- Sort by city ASC.
- Add second key amount DESC.
- Scan one city block in the result.
Examples
Example 1 · dataset: raja_coffee
SELECT city, amount_inr
FROM orders
ORDER BY city ASC, amount_inr DESC
LIMIT 12;Output
| city | amount_inr |
|---|---|
| Goa | 890.0 |
| Goa | 360.0 |
| Goa | 350.0 |
| Kolhapur | 900.0 |
| Kolhapur | 890.0 |
| Kolhapur | 620.0 |
| Mumbai | 930.0 |
| Mumbai | 840.0 |
| Mumbai | 720.0 |
| Nashik | 1080.0 |
| Nashik | 890.0 |
| Nashik | 350.0 |
Meaning. Cities alphabetical; inside each city, big amounts first.
Ravindra Bagale's Tip
You can mix ASC and DESC per column.
Ravindra Bagale's Tip – मराठी
प्रत्येक कॉलमसाठी ASC/DESC वेगळे ठेवता येतात.
Ravindra Bagale's Tip – हिंदी
हर कॉलम के लिए ASC/DESC अलग रख सकते हैं।