Skip to main content

ORDER BY: Sorting Results

ORDER BY sorts the rows in the result set. Without it, the database is free to return rows in any order - and that order can change between runs.

Prior lesson

The sample dataset is defined in the Introduction to SQL lesson.

Syntax

SELECT columns
FROM table_name
ORDER BY column1 [ASC | DESC], column2 [ASC | DESC];
  • ASC - ascending order (A → Z, 0 → 9). This is the default.
  • DESC - descending order (Z → A, 9 → 0).

Examples

Example 1: Sort by a single column

SELECT
order_id,
total_amount,
order_date
FROM orders
ORDER BY total_amount DESC;

Result:

order_idtotal_amountorder_date
1999.002024-01-05
7999.002024-03-15
9999.002024-04-10
4796.002024-02-01
3349.002024-01-15
6349.002024-03-01
889.972024-04-01
259.982024-01-10
549.902024-02-10
1024.952024-05-01

Example 2: Sort by multiple columns

When the first sort column has ties, the second column breaks them.

SELECT
name,
country,
city
FROM customers
ORDER BY country ASC, name ASC;

Result:

namecountrycity
Carol WhiteAustraliaSydney
Dave BrownCanadaToronto
Bob SmithUKLondon
Alice JohnsonUSANew York
Eve DavisUSANew York

Countries are sorted A→Z first; within USA, names are sorted A→Z.

Example 3: Order by a column alias

Unlike WHERE, ORDER BY can reference column aliases defined in SELECT.

SELECT
order_id,
total_amount * 0.9 AS discounted_price
FROM orders
ORDER BY discounted_price DESC;

Common Mistake

Without ORDER BY, row order is non-deterministic

The database is not required to return rows in any particular order unless you ask. Relying on implicit ordering (e.g., "the database always returns them in insert order") will eventually burn you - especially on large tables or after a vacuum/reindex.

Always add ORDER BY when the order of results matters.

Practice

Write a query that returns all products sorted by category ascending, then by price descending within each category.

Show answer
SELECT
name,
category,
price
FROM products
ORDER BY category ASC, price DESC;

Expected result:

namecategoryprice
LaptopElectronics999.00
MouseElectronics29.99
DeskFurniture349.00
ChairFurniture199.00
NotebookStationery4.99
Donate to this project