Skip to content
Module 03 of 1230 min readBeginner

ORDER BY, LIMIT, DISTINCT

Slice, sort, and de-duplicate result sets — the everyday verbs.

25%

Listen along

Read “ORDER BY, LIMIT, DISTINCT” aloud

Plays in your browser using on-device text-to-speech — nothing leaves the page.

Three small but indispensable verbs: ORDER BY (sort), LIMIT (cap rows), DISTINCT (remove duplicates). You'll use them in nearly every interactive query.

ORDER BY

sql
SELECT first_name, last_name, signed_up_at
FROM customers
ORDER BY signed_up_at DESC;

DESC = descending (newest first). ASC = ascending (default). You can sort by multiple columns:

sql
SELECT *
FROM orders
ORDER BY country ASC, total_amount DESC;

First sort by country (A-Z), then within each country sort by total_amount (high-to-low).

LIMIT

sql
SELECT * FROM orders
ORDER BY total_amount DESC
LIMIT 10;

Top 10 orders by amount. LIMIT is essential for exploration — never run a SELECT * on a million-row table without one.

Pagination

Use LIMIT 20 OFFSET 40 to skip 40 rows and return the next 20 — page 3 of a 20-per-page paginated view. (Postgres also accepts FETCH FIRST 20 ROWS, but LIMIT is portable.)

DISTINCT

sql
SELECT DISTINCT country FROM customers ORDER BY country;

Returns the unique list of countries. DISTINCT applies to the entire row in the SELECT — DISTINCT a, b returns unique (a, b) pairs, not unique a OR unique b.

Exercise

Find the 5 most recent customers from Kenya, ordered newest first.

Loading progress…
LeadAfrikPublic Economics Hub