Explain it simply
Explain it simply
A database table is not a neatly arranged bookshelf; it is more like a bag of index cards. Each SELECT may hand the cards back in a different order. ORDER BY says "sort them by this column before you give them to me".
ASC means smallest to largest (A to Z, oldest date to newest) and is the default. DESC reverses it. Leaderboards, "latest posts" and "cheapest first" all rely on ORDER BY.
Problem → Why → Solution
The problem: sorted in development, shuffled in production
A developer builds the customer list page without ORDER BY. On a tiny table on their laptop the rows come back in insertion order, so everything looks fine. In production rows get updated and deleted, the table grows, the query plan changes, and the order shifts between reloads: customers from page 1 reappear on page 2.
-- page 1
SELECT customer_name FROM customers LIMIT 20;
-- page 2: may repeat or skip rows, because nothing defines the order
SELECT customer_name FROM customers LIMIT 20 OFFSET 20;Why does the order change?
In standard SQL a table is a set of rows with no inherent order. Without ORDER BY, PostgreSQL may return rows in physical storage order, index order, parallel-worker order or hash order. An UPDATE writes a new row version that can live somewhere else, so not even insertion order survives. ORDER BY is the only promise you get.
Core concept: sort keys are compared in order
ORDER BY runs at the very end of a SELECT: WHERE filters first, and only the surviving rows are sorted. That is why ORDER BY may use an alias from the SELECT list (ORDER BY name), a column position (ORDER BY 2) or an expression (ORDER BY lower(name)). Positions silently change meaning when the column list changes, so keep them for quick ad-hoc queries.
With several columns, rows are sorted by the first one, and the second column only matters among rows that tie on the first, like a phone book sorted by family name and then by given name. ASC and DESC apply to each column separately: in ORDER BY country, signed_up DESC, country is still ascending and only signed_up is descending.
Among rows that tie on every sort key, PostgreSQL promises no order at all. With only ORDER BY signed_up DESC, two customers who signed up on the same day may swap places from run to run. Add a unique column such as the primary key as the final tie-breaker so pagination and automated tests stay stable over time.
PostgreSQL treats NULL as larger than every value: NULLs come last in ASC and first in DESC. Oracle behaves the same way, while MySQL and SQL Server treat NULL as the smallest value, so NULLs appear first in ascending order. In PostgreSQL you can state it explicitly with NULLS FIRST or NULLS LAST. Text columns are sorted by their collation, the rules for comparing characters, which the deeper section covers.
- WHERE filters the rows
- Sort by the first key
- On a tie, look at the next key
- All keys tie: order is undefined
Only a unique column as the last key makes the order fully deterministic.
General pattern
SELECT column_list
FROM table_name
WHERE condition
ORDER BY first_key [ASC | DESC] [NULLS FIRST | NULLS LAST],
second_key [ASC | DESC],
unique_key;ORDER BY comes after WHERE, and each key can carry its own ASC/DESC and NULLS FIRST/LAST. ASC is the default and may be omitted. A unique key at the end resolves every remaining tie.
Example: by country, then newest sign-ups first
Five customers were inserted in a deliberately jumbled order; Germany and Mexico have two customers each, and two pairs share a sign-up date. The first query sorts by country and then by name; the second shows the newest sign-ups first and settles equal dates with customer_id.
CREATE TABLE customers (
customer_id integer PRIMARY KEY,
customer_name text NOT NULL,
country text NOT NULL,
signed_up date NOT NULL
);
INSERT INTO customers VALUES
(1, 'Around the Horn', 'UK', '2024-03-02'),
(2, 'Antonio Moreno', 'Mexico', '2024-01-15'),
(3, 'Alfreds Futterkiste', 'Germany', '2024-02-20'),
(4, 'Ana Trujillo', 'Mexico', '2024-03-02'),
(5, 'Blauer See Delikatessen', 'Germany', '2024-01-15');-- By country, then by name inside each country
SELECT customer_name, country
FROM customers
ORDER BY country ASC, customer_name ASC;
-- Newest sign-ups first; equal dates broken by id
SELECT customer_id, customer_name, signed_up
FROM customers
ORDER BY signed_up DESC, customer_id;Code breakdown
- First key
ORDER BY country ASC, customer_name ASC;Rows are first grouped as Germany, Mexico, UK. Only between the two Germany customers does customer_name matter, which puts Alfreds before Blauer.
- DESC
ORDER BY signed_up DESC, customer_id;DESC applies to signed_up only; customer_id stays ascending by default. On 2024-03-02 ids 1 and 4 tie, so id 1 comes first.
- Tie-breaker
customer_idcustomer_id is the primary key, so it is unique and the second query's order is identical on every run. Without it, Antonio and Blauer (both 2024-01-15) could swap places.
customer_name | country
-------------------------+---------
Alfreds Futterkiste | Germany
Blauer See Delikatessen | Germany
Ana Trujillo | Mexico
Antonio Moreno | Mexico
Around the Horn | UK
(5 rows)
customer_id | customer_name | signed_up
-------------+-------------------------+------------
1 | Around the Horn | 2024-03-02
4 | Ana Trujillo | 2024-03-02
3 | Alfreds Futterkiste | 2024-02-20
2 | Antonio Moreno | 2024-01-15
5 | Blauer See Delikatessen | 2024-01-15
(5 rows)Where NULLs go
Suppose a player who never finished has points = NULL. ORDER BY points DESC puts that player at the top of the leaderboard, because PostgreSQL treats NULL as the largest value. Adding NULLS LAST moves them to the bottom.
-- 'hla' (points NULL) is listed first
SELECT player, points FROM scores ORDER BY points DESC;
-- 'hla' is listed last
SELECT player, points FROM scores ORDER BY points DESC NULLS LAST;Collation: who decides the order of text
When sorting text, PostgreSQL uses the column's collation. The "C" collation compares raw bytes, so every uppercase letter sorts before every lowercase one: Banana, apple, cherry. A linguistic collation such as ICU's "unicode" or en_US.UTF-8 on a Linux server sorts the way people read: apple, Banana, cherry. The default comes from the locale chosen when the database was created, so the same query can order text differently on two servers.
SELECT name FROM fruits ORDER BY name COLLATE "C"; -- Banana, apple, cherry
SELECT name FROM fruits ORDER BY name COLLATE "unicode"; -- apple, Banana, cherry
SELECT name FROM fruits ORDER BY lower(name); -- apple, Banana, cherryIs the "unicode" collation available?
The "unicode" collation exists only when PostgreSQL was built with ICU support; check with SELECT collname FROM pg_collation;. Sorting by lower(name) works everywhere, but it does not handle accents or language-specific rules.
In real projects
Where this shows up in real projects
A blog's home page shows its ten newest posts with ORDER BY published_at DESC, id DESC LIMIT 10. The id makes sure that two posts published in the same second never repeat or vanish between pages. Infinite scroll usually replaces OFFSET with keyset pagination, a WHERE that fetches rows older than the last (published_at, id) seen, and that technique also depends on a unique sort key.
On the performance side, sorting a large table can be expensive. With an index on (published_at, id), PostgreSQL can read rows in index order, skip the sort entirely and stop after ten rows. For text columns the index only helps if its collation matches the query's, so do not sprinkle COLLATE into queries without a reason.
Common mistakes
Common mistakes
1. Thinking DESC applies to every column
In ORDER BY points, finished_at DESC, points is still ascending, so the lowest scorer ends up on top. Write the direction after each column: ORDER BY points DESC, finished_at ASC.
2. Paginating without a unique tie-breaker
With ORDER BY created_at LIMIT 20 OFFSET 20, rows sharing a created_at that straddle the page boundary can show up on both pages or on neither. Always add a unique column: ORDER BY created_at, id.
3. Assuming every database places NULLs the same way
After porting an app from MySQL, ORDER BY due_date moves tasks without a due date from the top of the list to the bottom. When it matters, always write NULLS FIRST or NULLS LAST explicitly.
Best practices
Best practices
- Write ORDER BY on every query whose rows a user sees, that feeds an export file, or that uses LIMIT.
- End the list of sort keys with a unique column such as the primary key.
- When sorting a nullable column, spell out NULLS FIRST or NULLS LAST so the intent is visible.
- Keep positional keys like ORDER BY 2 for ad-hoc queries and name the columns in application code.
Mini challenge
Mini challenge: a game leaderboard
Produce a leaderboard from the scores table: highest points first, earlier finishers win ties, and players who did not finish (points NULL) go to the bottom.
- Show the player, points and finished_at columns
- Sort points descending and send NULLs to the end
- zaw and kyaw both have 950; zaw finished earlier and must come first
CREATE TABLE scores (
player text PRIMARY KEY,
points integer, -- NULL = did not finish
finished_at timestamp
);
INSERT INTO scores VALUES
('mya', 820, '2026-05-01 10:04'),
('kyaw', 950, '2026-05-01 10:09'),
('hla', NULL, NULL),
('zaw', 950, '2026-05-01 10:02'),
('thida', 700, '2026-05-01 10:01');
-- TODO: highest points first, but 'hla' (NULL) must not be on top
-- TODO: on equal points, the earlier finished_at wins
SELECT player, points, finished_at
FROM scores;Expected: zaw (950, 10:02), kyaw (950, 10:09), mya (820), thida (700), and hla (NULL) last.
Show hint
In PostgreSQL, DESC puts NULLs first. Add NULLS LAST after points DESC and use finished_at ASC as the second key.
Show solution
SELECT player, points, finished_at
FROM scores
ORDER BY points DESC NULLS LAST,
finished_at ASC;Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Never rely on row order without ORDER BY.
- Keys are compared in order, and ASC/DESC belongs to each column separately.
- A unique final tie-breaker keeps pagination stable.
- PostgreSQL puts NULLs last in ASC and first in DESC; control it with NULLS FIRST/LAST.
- Text order depends on collation: "C" is byte order, linguistic collations follow human reading order.
PostgreSQL SQL Tutorial — PostgreSQL Global Development Group