ORDER BY
ORDER BY sorts the rows of a result. Without it, a table has no guaranteed order, so the database may return rows in whatever order is fastest, and that order can change. Every query in this course that returns several rows ends with ORDER BY for exactly this reason. This lesson covers sorting up and down, by several columns, by calculations, where NULL lands, and how text is sorted.
In One Minute
ORDER BY columnsorts ascending (smallest first); addDESCfor descending.- List several columns to break ties:
ORDER BY level, fee_usd DESC. - You can sort by a calculation or by a column alias.
- In PostgreSQL,
NULLsorts last going up and first going down;NULLS FIRSTandNULLS LASTchange that. - Text sorts by the database's collation; in the course database, capital letters come before lowercase ones.
The Basics
SELECT columns
FROM table_name
ORDER BY column1 [ASC | DESC], column2 [ASC | DESC], ...;| Part | Meaning |
|---|---|
ORDER BY | Comes last in the query, after WHERE |
ASC | Ascending: smallest first, A before Z, earliest date first. It's the default, so you rarely write it |
DESC | Descending: largest first, Z before A, latest date first |
Courses from cheapest to most expensive:
SELECT title, fee_usd
FROM courses
ORDER BY fee_usd; title | fee_usd
-------------------+---------
Git Basics | 250.00
SQL Basics | 400.00
Java Basics | 450.00
JavaScript Basics | 450.00
Java OOP | 500.00
Java Collections | 550.00
(6 rows)And most expensive first, with DESC:
SELECT title, fee_usd
FROM courses
ORDER BY fee_usd DESC; title | fee_usd
-------------------+---------
Java Collections | 550.00
Java OOP | 500.00
Java Basics | 450.00
JavaScript Basics | 450.00
SQL Basics | 400.00
Git Basics | 250.00
(6 rows)Sorting by Several Columns
Look closely at the last result: Java Basics and JavaScript Basics both cost $450.00. They tie, and with only fee_usd in the ORDER BY, the database may return them in either order. A second column breaks the tie, and only applies when the first column is equal:
SELECT title, fee_usd
FROM courses
ORDER BY fee_usd DESC, title; title | fee_usd
-------------------+---------
Java Collections | 550.00
Java OOP | 500.00
Java Basics | 450.00
JavaScript Basics | 450.00
SQL Basics | 400.00
Git Basics | 250.00
(6 rows)Each column has its own direction. Here courses are grouped by level (A to Z), and within each level the most expensive comes first:
SELECT title, level, fee_usd
FROM courses
ORDER BY level, fee_usd DESC, title; title | level | fee_usd
-------------------+--------------+---------
Java Basics | Beginner | 450.00
JavaScript Basics | Beginner | 450.00
SQL Basics | Beginner | 400.00
Git Basics | Beginner | 250.00
Java Collections | Intermediate | 550.00
Java OOP | Intermediate | 500.00
(6 rows)Sorting by a Calculation or an Alias
You can sort by any expression, or by the alias you gave a calculated column. Here payments are sorted by how many days late they were, latest first, using the alias days_late (subtracting dates gives days, as in Basic Data Types):
SELECT payment_id, due_on, paid_on, paid_on - due_on AS days_late
FROM payments
ORDER BY days_late DESC, payment_id; payment_id | due_on | paid_on | days_late
------------+------------+------------+-----------
7 | 2025-12-15 | 2025-12-19 | 4
3 | 2025-12-01 | 2025-12-03 | 2
5 | 2026-01-05 | 2026-01-05 | 0
6 | 2025-11-15 | 2025-11-14 | -1
2 | 2025-11-01 | 2025-10-30 | -2
1 | 2025-09-01 | 2025-08-28 | -4
4 | 2026-01-02 | 2025-12-29 | -4
(7 rows)Positive numbers are late payments, zero is paid on the due date, and negative numbers were paid early. Payments 1 and 4 tie at 4 days early, so payment_id breaks the tie.
An alias works in ORDER BY because sorting happens after the SELECT list is worked out. The same alias can't be used in that query's WHERE, which runs earlier: WHERE days_late > 0 fails with column "days_late" does not exist. Aliases explains why.
You may also see ORDER BY 2, which sorts by the second column of the SELECT list. It works, but it's an old style: add a column at the front and the query quietly sorts by something else. Name the column instead.
Where NULL Goes
NULL has no value to compare, so each database has a rule for where it sorts. PostgreSQL sorts NULL as if it were larger than every value: it comes last when you sort ascending and first when you sort descending. Advitha and Navika have no email:
SELECT first_name, email
FROM students
ORDER BY email, first_name; first_name | email
------------+--------------------------------
Srihitha | srihitha.anamaneni@example.com
Advitha | NULL
Navika | NULL
(3 rows)NULLS FIRST and NULLS LAST put the missing values exactly where you want them, whatever the direction. Here the payment with no recorded method comes first, so it stands out:
SELECT payment_id, method
FROM payments
ORDER BY method NULLS FIRST, payment_id; payment_id | method
------------+--------
5 | NULL
1 | card
2 | card
4 | card
6 | card
3 | check
7 | check
(7 rows)Databases choose different default positions for NULL when sorting: PostgreSQL and Oracle place it last in ascending order, while MySQL, SQL Server and SQLite place it first. This is a sorting rule, not an ordinary comparison: NULL still isn't greater or smaller than anything. NULLS FIRST and NULLS LAST are standard SQL and work in PostgreSQL, Oracle and SQLite, but not in MySQL or SQL Server. Tabs showing each database's version are coming to this course.
How Text Is Sorted
Text is sorted by the database's collation: its rules for ordering characters. The course database uses the simple C collation, which orders characters by their codes, so every capital letter comes before every lowercase letter:
SELECT word
FROM (VALUES ('apple'), ('Apple'), ('banana'), ('Zebra')) AS w(word)
ORDER BY word; word
--------
Apple
Zebra
apple
banana
(4 rows)(The VALUES list makes a small table of four words on the spot, so you can test sorting without changing any real table.) Zebra lands before apple because Z is a capital. Many databases use a language-aware collation instead, which would put the words in dictionary order, so the same query can sort differently elsewhere.
To sort ignoring capitals, sort by the lowercase version of the text:
SELECT word
FROM (VALUES ('apple'), ('Apple'), ('banana'), ('Zebra')) AS w(word)
ORDER BY lower(word), word; word
--------
Apple
apple
banana
Zebra
(4 rows)lower(word) converts each word to lowercase before sorting, which gives a case-insensitive order for these words; the second word breaks the tie between Apple and apple. The exact order of text can still depend on the collation, for example with accented letters or language-specific rules.
Sorting Distinct Rows
DISTINCT and ORDER BY do different jobs. DISTINCT decides which rows remain; ORDER BY decides how those rows are arranged. DISTINCT never sorts on its own, so when you want each technology once and in alphabetical order, you need both:
SELECT DISTINCT technology
FROM courses
ORDER BY technology; technology
------------
Git
Java
JavaScript
SQL
(4 rows)Common Mistakes
Relying on the order without ORDER BY. A table has no order. The rows may come back the same way a hundred times and then change after an update or a bigger table. If the order matters, say so.
Sorting by one column when it has ties. ORDER BY fee_usd DESC can return the two $450.00 courses either way round. Add a tie-breaker.
Putting ORDER BY before WHERE. In a basic query the order is SELECT, FROM, WHERE, then ORDER BY. The wrong order gives syntax error at or near "WHERE".
Expecting NULL in the same place in every database. PostgreSQL puts it last going up; MySQL and SQL Server put it first. Write NULLS FIRST or NULLS LAST where your database supports it.
Practice
Challenge: List every payment's payment_id, amount_usd and paid_on, with the largest amount first. When two payments have the same amount, show the earlier one first.
Show solution
SELECT payment_id, amount_usd, paid_on
FROM payments
ORDER BY amount_usd DESC, paid_on; payment_id | amount_usd | paid_on
------------+------------+------------
4 | 550.00 | 2025-12-29
1 | 450.00 | 2025-08-28
2 | 250.00 | 2025-10-30
3 | 250.00 | 2025-12-03
6 | 225.00 | 2025-11-14
7 | 225.00 | 2025-12-19
5 | 200.00 | 2026-01-05
(7 rows)Payments 2 and 3 are both $250.00, so paid_on decides: payment 2 (October 30) comes before payment 3 (December 3). Payments 6 and 7 tie at $225.00 the same way.
Key Takeaways
| You want to | Write |
|---|---|
| Smallest first | ORDER BY fee_usd |
| Largest first | ORDER BY fee_usd DESC |
| Break ties | ORDER BY fee_usd DESC, title |
| Sort by an alias | ORDER BY days_late DESC |
| Missing values first | ORDER BY method NULLS FIRST |
| Sort ignoring capitals | ORDER BY lower(word) |
Was this tutorial helpful?