skip to content

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.

ORDER BY =
query.sql
  1. 1SELECT code, dept, credits, title
  2. 2FROM courses
  3. 3ORDER BY dept;
the sorted rows, with ties bracketed
codedept1creditstitle
tie of 5 rowsCS101CS4Intro to Programming
CS201CS4Data Structures
CS301CS4Databases
CS350CS4Operating Systems
CS401CS4Database Internals
CS499GEN6Senior Thesis
HIST101HIST3History of Computing
tie of 3 rowsMATH201MATH3Discrete Math
MATH301MATH3Linear Algebra
MATH101MATH4Calculus I
tie of 2 rowsPHYS101PHYS4Mechanics
PHYS201PHYS4Electromagnetism

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.

a tie: equal on every sort key
real output, postgres 18.6 (PGlite 0.5.12) · order-by
add sort keys one at a time. hot brackets are ties: rows equal on every key so far, whose order is postgres's choice. by the third key nothing ties, and the order is fully decided.

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:

sqldb=school
SELECT code, dept, credits
FROM courses
ORDER BY credits DESC, code;
output, from postgres 18.6
SELECT 12
codetextdepttextcreditsint2
CS499GEN6
CS101CS4
CS201CS4
CS301CS4
CS350CS4
CS401CS4
MATH101MATH4
PHYS101PHYS4
PHYS201PHYS4
HIST101HIST3
MATH201MATH3
MATH301MATH3
(12 rows)

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:

sqldb=school
SELECT code, title
FROM courses
ORDER BY length(title) DESC, code
LIMIT 3;
output, from postgres 18.6
SELECT 3
codetexttitletext
CS101Intro to Programming
HIST101History of Computing
CS401Database Internals
(3 rows)

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.

LIMIT =
query.sql
  1. 1SELECT code, dept, title
  2. 2FROM courses
  3. 3ORDER BY dept;
the result for none
codetextdepttexttitletext
CS101CSIntro to Programming
CS201CSData Structures
CS301CSDatabases
CS350CSOperating Systems
CS401CSDatabase Internals
CS499GENSenior Thesis
HIST101HISTHistory of Computing
MATH201MATHDiscrete Math
MATH301MATHLinear Algebra
MATH101MATHCalculus I
PHYS101PHYSMechanics
PHYS201PHYSElectromagnetism
(12 rows)

the five CS courses tie on dept. sorted whole, they come back in code order, by luck.

real output, postgres 18.6 (PGlite 0.5.12) · order-by
the same 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:

sqldb=school
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;
output, from postgres 18.6
#1 · EXPLAIN
Sort (actual rows=12.00 loops=1) Sort Key: dept Sort Method: quicksort Memory: 17kB -> Seq Scan on courses (actual rows=12.00 loops=1)
#2 · EXPLAIN
Limit (actual rows=3.00 loops=1) -> Sort (actual rows=3.00 loops=1) Sort Key: dept Sort Method: top-N heapsort Memory: 17kB -> Seq Scan on courses (actual rows=12.00 loops=1)

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

predict the output
sql
SELECT name, category
FROM products
ORDER BY category DESC, id
LIMIT 3;
sqldb=shop
SELECT name, category
FROM products
ORDER BY category DESC, id
LIMIT 3;
output, from postgres 18.6
SELECT 3
nametextcategorytext
wooden trainnull
large lanternnull
smart staplernull
(3 rows)

NULLS FIRST and NULLS LAST override that, per key. here's every combination on the one course with no instructor:

direction =
nulls =
query.sql
  1. 1SELECT code, instructor_id, title
  2. 2FROM courses
  3. 3ORDER BY instructor_id ASC, code;
the result for ASC | default
codetextinstructor_idint4titletext
CS1011Intro to Programming
CS3011Databases
CS2012Data Structures
CS3502Operating Systems
CS4013Database Internals
MATH1014Calculus I
MATH3014Linear Algebra
MATH2015Discrete Math
PHYS1016Mechanics
PHYS2016Electromagnetism
HIST1017History of Computing
CS499nullSenior Thesis
(12 rows)

ascending, with no NULLS clause: NULL counts as bigger than every value, so the course with no instructor comes last.

real output, postgres 18.6 (PGlite 0.5.12) · order-by
flip the direction and the NULL placement. by default the senior thesis sits at the end going up and at the start going down. NULLS FIRST and NULLS LAST pin it wherever you say, whichever way the rest is sorted.

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:

sqlempty db
SELECT x
FROM (VALUES ('apple'), ('Banana'), ('cherry'), ('Zoë'), ('zoe')) AS t (x)
ORDER BY x;
output, from postgres 18.6
SELECT 5
xtext
Banana
Zoë
apple
cherry
zoe
(5 rows)

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):

sqlempty db
SELECT x
FROM (VALUES ('apple'), ('Banana'), ('cherry'), ('Zoë'), ('zoe')) AS t (x)
ORDER BY x COLLATE "en-US-x-icu";
output, from a real postgres 18.6 server
SELECT 5
xtext
apple
Banana
cherry
zoe
Zoë
(5 rows)

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.