Filtering and Sorting · Lesson 14 of 64

SQL ORDER BY

What you will learn

  • How ORDER BY sorts the result, with ASC and DESC
  • How to sort by several columns and by an expression
  • Where NULL appears in a sorted result
  • Why the order of a result is not guaranteed without ORDER BY

This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). Edit any query and press Run. Reset data puts the original rows back.

1. Sort ascending and descending

ORDER BY goes near the end of the query. The default is ascending (smallest first, A to Z, oldest date first). Add DESC for descending:

SELECT name, price FROM products ORDER BY price LIMIT 5;
SELECT name, price FROM products ORDER BY price DESC LIMIT 5;
name          price
------------  -----
Day backpack    4.5
Footrest       4.95
Glass jar       5.4
Steel pan       6.6
Wall planner    6.6
(5 rows)

name          price
------------  -----
Water bottle   86.9
Tea kettle     79.0
Highlighters   79.0
Foam roller    79.0
Drawing kit    53.9
(5 rows)
SELECT account_id, balance_cents FROM accounts ORDER BY balance_cents LIMIT 5;
SELECT account_id, balance_cents FROM accounts ORDER BY balance_cents DESC LIMIT 5;
account_id  balance_cents
----------  -------------
       330           1300
        23           2700
       405           4300
       331           4800
       370           5300
(5 rows)

account_id  balance_cents
----------  -------------
       398         502080
       243         432800
       165         428004
       238         401600
       295         379900
(5 rows)
SELECT code, title, credits FROM courses ORDER BY title LIMIT 5;
SELECT code, title, credits FROM courses ORDER BY title DESC LIMIT 5;
code    title             credits
------  ----------------  -------
SCI301  Biology                 3
SCI201  Chemistry               4
HUM301  Civics                  2
CS101   Computing Basics        3
CS301   Databases               4
(5 rows)

code     title            credits
-------  ---------------  -------
LANG101  Writing Skills         3
HUM101   World History          3
MATH301  Statistics             4
LANG201  Second Language        3
LANG102  Reading Circle         2
(5 rows)

Text sorts alphabetically, dates sort in time order (lesson 1.7), numbers sort by value.

2. Several columns

When several rows have the same value in the first column, the second column breaks the tie. List the columns in order of importance, each with its own ASC or DESC:

SELECT country, last_name, first_name FROM customers
ORDER BY country, last_name DESC, first_name LIMIT 8;
country     last_name  first_name
----------  ---------  ----------
Bangladesh  Zhang      Farid
Bangladesh  Wang       Dana
Bangladesh  Torres     Tara
Bangladesh  Sato       Sven
Bangladesh  Rossi      Yusuf
Bangladesh  Park       Rina
Bangladesh  Nguyen     Jin
Bangladesh  Meyer      Aisha
(8 rows)
SELECT account_type, status, account_id FROM accounts
ORDER BY account_type, status DESC, account_id LIMIT 8;
account_type  status  account_id
------------  ------  ----------
checking      open             1
checking      open             5
checking      open             6
checking      open            11
checking      open            12
checking      open            13
checking      open            14
checking      open            15
(8 rows)
SELECT enrolled_year, last_name, first_name FROM students
ORDER BY enrolled_year DESC, last_name, first_name LIMIT 8;
enrolled_year  last_name  first_name
-------------  ---------  ----------
         2026  Abdi       Farid
         2026  Abdi       Leo
         2026  Abdi       Mei
         2026  Abdi       Olga
         2026  Abdi       Tara
         2026  Alvarez    Bela
         2026  Alvarez    Eva
         2026  Banerjee   Lara
(8 rows)

Rows are sorted by the first column; only where it is equal does the second matter, and so on.

3. Sort by an expression or an alias

You can sort by a calculation, or by the alias you gave it (lesson 1.4):

SELECT name, price, cost, ROUND(price - cost, 2) AS margin FROM products ORDER BY margin DESC LIMIT 5;
name          price   cost  margin
------------  -----  -----  ------
Foam roller    79.0  44.79   34.21
Tea kettle     79.0  52.69   26.31
Highlighters   79.0  55.25   23.75
Water bottle   86.9  63.47   23.43
Drawing kit    53.9  33.24   20.66
(5 rows)
SELECT account_id, balance_cents, ROUND(balance_cents / 100.0, 2) AS units FROM accounts ORDER BY units DESC LIMIT 5;
account_id  balance_cents    units
----------  -------------  -------
       398         502080   5020.8
       243         432800   4328.0
       165         428004  4280.04
       238         401600   4016.0
       295         379900   3799.0
(5 rows)
SELECT title, max_points, ROUND(max_points * 0.4, 1) AS pass_mark FROM assignments ORDER BY pass_mark DESC, title LIMIT 5;
title    max_points  pass_mark
-------  ----------  ---------
Midterm         100       40.0
Midterm         100       40.0
Midterm         100       40.0
Midterm         100       40.0
Midterm         100       40.0
(5 rows)

You can also sort by something you do not show, such as ORDER BY LENGTH(name).

4. Where does NULL go?

In SQLite, a NULL is treated as smaller than any value: it comes first when ascending and last when descending:

SELECT customer_id, phone FROM customers ORDER BY phone LIMIT 3;
SELECT customer_id, phone FROM customers ORDER BY phone DESC LIMIT 3;
customer_id  phone
-----------  -----
          2  NULL
         16  NULL
         21  NULL
(3 rows)

customer_id  phone
-----------  ------------
        103  +99 82437717
        363  +99 82167427
        196  +99 66496959
(3 rows)
SELECT log_id, note FROM audit_log ORDER BY note LIMIT 3;
SELECT log_id, note FROM audit_log ORDER BY note DESC LIMIT 3;
log_id  note
------  ----
     1  NULL
     2  NULL
     6  NULL
(3 rows)

log_id  note
------  --------------
     4  status changed
     5  status changed
    15  status changed
(3 rows)
SELECT student_id, guardian_name FROM students ORDER BY guardian_name LIMIT 3;
SELECT student_id, guardian_name FROM students ORDER BY guardian_name DESC LIMIT 3;
student_id  guardian_name
----------  -------------
         7  NULL
         9  NULL
        19  NULL
(3 rows)

student_id  guardian_name
----------  -------------
        63  Zoe Singh
        93  Zoe Eze
       283  Zoe Cohen
(3 rows)

You can choose where they go with NULLS FIRST or NULLS LAST after ASC or DESC (available in SQLite 3.30 and later):

SELECT customer_id, phone FROM customers ORDER BY phone NULLS LAST LIMIT 3;
customer_id  phone
-----------  ------------
         88  +20 22980601
        194  +20 24964281
        353  +20 30491206
(3 rows)
SELECT log_id, note FROM audit_log ORDER BY note NULLS LAST LIMIT 3;
log_id  note
------  ---------------
    12  address changed
    14  address changed
    25  address changed
(3 rows)
SELECT student_id, guardian_name FROM students ORDER BY guardian_name NULLS LAST LIMIT 3;
student_id  guardian_name
----------  -------------
       142  Aisha Cohen
       248  Aisha Garcia
        75  Aisha Lee
(3 rows)

In other databases. The default differs. PostgreSQL's documentation says NULL sorts as if larger than any other value: last when ascending and first when descending, the opposite of SQLite. MySQL's documentation says NULL comes first when ascending and last when descending, like SQLite. This is from the official documentation and was not run here. If your report depends on it, write NULLS FIRST or NULLS LAST (where supported) instead of relying on the default.

5. Without ORDER BY there is no order

A query without ORDER BY returns rows in whatever order the database finds convenient. It often looks sorted (for example by key) but this is not a promise, and it can change when the data or the database changes. If the order matters, always write ORDER BY. If rows can tie, add a unique column (such as the id) at the end so the order is the same every time:

SELECT 'b' AS letter, 2 AS n UNION ALL SELECT 'a', 2 UNION ALL SELECT 'c', 1
ORDER BY n, letter;
letter  n
------  -
c       1
a       2
b       2
(3 rows)
SELECT 'b' AS letter, 2 AS n UNION ALL SELECT 'a', 2 UNION ALL SELECT 'c', 1
ORDER BY n, letter;
letter  n
------  -
c       1
a       2
b       2
(3 rows)
SELECT 'b' AS letter, 2 AS n UNION ALL SELECT 'a', 2 UNION ALL SELECT 'c', 1
ORDER BY n, letter;
letter  n
------  -
c       1
a       2
b       2
(3 rows)

Worked example: a top list with ties

"Show the five most expensive products." Ties are possible, so:

  1. sort by the value, largest first: ORDER BY price DESC;
  2. add a second sort column for ties, such as product_id;
  3. keep only five rows (LIMIT 5, lesson 2.7).

SELECT name, price FROM products ORDER BY price DESC, product_id LIMIT 5 gives the same five rows in the same order every time. Without the tie-break, two equal prices could swap places between runs. The table is made up.

Common mistakes

  • Relying on the order without ORDER BY.
  • Forgetting DESC when you wanted "highest first".
  • No tie-break column, so the order of equal rows can change.
  • Assuming NULL sorts the same everywhere. It does not.
  • Writing ORDER BY before WHERE. The order is SELECT, FROM, WHERE, ORDER BY, LIMIT.

Key takeaways

  • ORDER BY sorts ascending by default; DESC reverses.
  • Several columns are tie-breakers from left to right; each has its own direction.
  • You can sort by a calculation or an alias.
  • In SQLite NULL comes first when ascending; other databases differ; NULLS FIRST/LAST chooses.
  • No ORDER BY means no promised order.

Practice

1. Write a query for the products from most to least expensive.

Show answer

SELECT name, price FROM products ORDER BY price DESC;

2. In ORDER BY a, b DESC, which column is sorted descending?

Show answer

Only b. a is ascending; each column has its own direction.

3. Why add the id as the last column of an ORDER BY?

Show answer

It breaks ties, so rows with equal values always come in the same order.

4. Where do NULLs come in SQLite with ORDER BY x ASC?

Show answer

First, before every real value.

5. Is the order of rows guaranteed if you write no ORDER BY?

Show answer

No. It may look sorted but it is not a promise.

6. Can you sort by a column that is not in the SELECT list?

Show answer

Yes. You can sort by any column or expression, shown or not.