Ravindra BagaleCourses & study guides Track your progress

5. ORDER BY, DISTINCT and Top-N Results

5.1 How to Sort Rows with ORDER BY ASC and DESC

Why. Unsorted results hide the biggest and newest rows.

What. ORDER BY sorts the result. ASC = low to high (default). DESC = high to low.

How. SELECT … ORDER BY amount_inr DESC;

Steps

  1. Sort amounts DESC.
  2. Sort dates ASC.
  3. Remember ORDER BY comes after WHERE.

Examples

Example 1 · dataset: raja_coffee

SELECT order_id, amount_inr
FROM orders
ORDER BY amount_inr DESC
LIMIT 5;

Output

order_idamount_inr
10161780.0
10131680.0
10071080.0
10041050.0
1010930.0

Meaning. Five highest amounts.

Ravindra Bagale's Tip

ORDER BY alone does not limit rows — pair with LIMIT for Top-N.