sorting with ORDER BY
ASC, DESC, NULLS FIRST, and why a table has no order until you ask for one.
- address
- everything.basics.order_by
- part
- part 2, one table
- chapter
- chapter 4 of 12
- reading time
- 8 min
a table has no order. rows come back in whatever order the plan happens to produce them, and ORDER BY is the only thing that promises one. it sorts by its keys left to right, ascending unless you say DESC, and in postgres NULLs sort as if they were bigger than everything.
rows that tie on every key come back in any order. so keep adding keys until nothing ties.
the picture
you know how SELECT * FROM courses seems to come back in the order the rows went in? that's not a feature, it's a coincidence. postgres read the table front to back and handed rows over as it found them. change the plan, update a row, and the coincidence ends (LIMIT, OFFSET and FETCH FIRST catches it in the act).
ORDER BY is how you say what you actually want. think of sorting a pile of exam papers: by department first, then within a department by credits. papers that match on both stay in whatever order they were in the pile, because you never told anyone how to break that tie.
- 1SELECT code, dept, credits, title
- 2FROM courses
- 3ORDER BY dept;
| code | dept1 | credits | title | |
|---|---|---|---|---|
| tie of 5 rows | CS101 | CS | 4 | Intro to Programming |
| CS201 | CS | 4 | Data Structures | |
| CS301 | CS | 4 | Databases | |
| CS350 | CS | 4 | Operating Systems | |
| CS401 | CS | 4 | Database Internals | |
| CS499 | GEN | 6 | Senior Thesis | |
| HIST101 | HIST | 3 | History of Computing | |
| tie of 3 rows | MATH201 | MATH | 3 | Discrete Math |
| MATH301 | MATH | 3 | Linear Algebra | |
| MATH101 | MATH | 4 | Calculus I | |
| tie of 2 rows | PHYS101 | PHYS | 4 | Mechanics |
| PHYS201 | PHYS | 4 | Electromagnetism |
10 of 12 rows sit in 3 ties: equal on dept. inside a bracket, postgres may return them in any order, and the same query can do it differently tomorrow.
look at MATH under ORDER BY dept. postgres returned MATH201, MATH301, MATH101: not alphabetical, not insertion order, just the order its sort left them in. that's allowed, because all three have the same dept. you asked for nothing more.
one key at a time
ORDER BY takes a list. the first key decides, the second only breaks ties in the first, the third only breaks ties in the second, and so on. each key gets its own direction, and DESC belongs to the one key right before it:
SELECT code, dept, credits
FROM courses
ORDER BY credits DESC, code;| codetext | depttext | creditsint2 |
|---|---|---|
| CS499 | GEN | 6 |
| CS101 | CS | 4 |
| CS201 | CS | 4 |
| CS301 | CS | 4 |
| CS350 | CS | 4 |
| CS401 | CS | 4 |
| MATH101 | MATH | 4 |
| PHYS101 | PHYS | 4 |
| PHYS201 | PHYS | 4 |
| HIST101 | HIST | 3 |
| MATH201 | MATH | 3 |
| MATH301 | MATH | 3 |
credits high to low, and within the same credits, code A to Z (ASC is the default, so it can go unsaid). the senior thesis has 6 credits, so it leads.
a sort key doesn't have to be a column you select, or a column at all. any expression works, computed per row just for sorting:
SELECT code, title
FROM courses
ORDER BY length(title) DESC, code
LIMIT 3;| codetext | titletext |
|---|---|
| CS101 | Intro to Programming |
| HIST101 | History of Computing |
| CS401 | Database Internals |
ORDER BY can also name a SELECT alias or position (ORDER BY 2), because it runs after SELECT. the logical order has the fine print on that, including why the alias has to stand alone.
ties
a tie means "any order is correct". and postgres takes that literally: the order of tied rows depends on how it sorted, and it doesn't always sort the same way.
- 1SELECT code, dept, title
- 2FROM courses
- 3ORDER BY dept;
| codetext | depttext | titletext |
|---|---|---|
| CS101 | CS | Intro to Programming |
| CS201 | CS | Data Structures |
| CS301 | CS | Databases |
| CS350 | CS | Operating Systems |
| CS401 | CS | Database Internals |
| CS499 | GEN | Senior Thesis |
| HIST101 | HIST | History of Computing |
| MATH201 | MATH | Discrete Math |
| MATH301 | MATH | Linear Algebra |
| MATH101 | MATH | Calculus I |
| PHYS101 | PHYS | Mechanics |
| PHYS201 | PHYS | Electromagnetism |
the five CS courses tie on dept. sorted whole, they come back in code order, by luck.
ORDER BY dept, with and without a LIMIT. the five CS courses tie, and they come out in a different order: with LIMIT 3, postgres switches to a sort that only keeps the best 3 rows, and ties fall where they fall.the plans say why. the whole table gets a quicksort, the LIMIT version a top-N heapsort that never holds more than 3 rows:
EXPLAIN (ANALYZE, COSTS OFF, BUFFERS OFF, TIMING OFF, SUMMARY OFF)
SELECT code, dept FROM courses ORDER BY dept;
EXPLAIN (ANALYZE, COSTS OFF, BUFFERS OFF, TIMING OFF, SUMMARY OFF)
SELECT code, dept FROM courses ORDER BY dept LIMIT 3;two algorithms, two answers, both correct. a bigger table, a parallel sort or an index can each change it again. this is why every multi-row query in this book ends with a total order: keys that tell every row apart, usually by ending with the primary key (ORDER BY dept, code). it costs nothing, and the answer stops depending on luck. sorting has the algorithms.
where the NULLs go
SELECT name, category
FROM products
ORDER BY category DESC, id
LIMIT 3;SELECT name, category
FROM products
ORDER BY category DESC, id
LIMIT 3;| nametext | categorytext |
|---|---|
| wooden train | null |
| large lantern | null |
| smart stapler | null |
NULLS FIRST and NULLS LAST override that, per key. here's every combination on the one course with no instructor:
- 1SELECT code, instructor_id, title
- 2FROM courses
- 3ORDER BY instructor_id ASC, code;
| codetext | instructor_idint4 | titletext |
|---|---|---|
| CS101 | 1 | Intro to Programming |
| CS301 | 1 | Databases |
| CS201 | 2 | Data Structures |
| CS350 | 2 | Operating Systems |
| CS401 | 3 | Database Internals |
| MATH101 | 4 | Calculus I |
| MATH301 | 4 | Linear Algebra |
| MATH201 | 5 | Discrete Math |
| PHYS101 | 6 | Mechanics |
| PHYS201 | 6 | Electromagnetism |
| HIST101 | 7 | History of Computing |
| CS499 | null | Senior Thesis |
ascending, with no NULLS clause: NULL counts as bigger than every value, so the course with no instructor comes last.
the standard leaves the default up to each database, and they disagree. postgres treats NULL as the biggest value. mysql and sqlite treat it as the smallest, so NULLs come first when you sort ascending (mysql, sqlite). if it matters, write NULLS FIRST or NULLS LAST and stop depending on the default. NULL and three-valued logic explains why NULLs get sorted together at all, when NULL = NULL isn't even true.
text sorts by bytes here
the postgres in this page uses the C collation: text sorts by the bytes of its characters. every capital letter comes before every lower-case one, and accented letters come after all of them:
SELECT x
FROM (VALUES ('apple'), ('Banana'), ('cherry'), ('Zoë'), ('zoe')) AS t (x)
ORDER BY x;| xtext |
|---|
| Banana |
| Zoë |
| apple |
| cherry |
| zoe |
Banana and Zoë before apple. a real server can sort the way a dictionary does, with a language's collation. here's the same list on a postgres 18.6 server, sorted with ICU's english rules (this one can't run in the browser):
SELECT x
FROM (VALUES ('apple'), ('Banana'), ('cherry'), ('Zoë'), ('zoe')) AS t (x)
ORDER BY x COLLATE "en-US-x-icu";| xtext |
|---|
| apple |
| Banana |
| cherry |
| zoe |
| Zoë |
checked on a real postgres 18.6 server. the browser engine can't run this one.
case and accents only break ties there, after the letters themselves. if you need case not to matter here, sort by lower(x) and keep x as a tie-breaker. why postgres lets each database, column or query pick its own collation is in text, varchar and collations.
keylines
- a table has no order. ORDER BY is the only promise you get.
- keys are applied left to right; each one only breaks the ties of the ones before it.
- DESC belongs to one key. ASC is the default.
- ties come back in any order, even between two runs of similar queries. end with a unique key.
- postgres sorts NULL as the biggest value. NULLS FIRST and NULLS LAST say it out loud.