Ravindra BagaleCourses & study guides Track your progress

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

  1. Sort by city ASC.
  2. Add second key amount DESC.
  3. 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

cityamount_inr
Goa890.0
Goa360.0
Goa350.0
Kolhapur900.0
Kolhapur890.0
Kolhapur620.0
Mumbai930.0
Mumbai840.0
Mumbai720.0
Nashik1080.0
Nashik890.0
Nashik350.0

Meaning. Cities alphabetical; inside each city, big amounts first.

Ravindra Bagale's Tip

You can mix ASC and DESC per column.