Sorting With ORDER BY: Multiple Keys, Expressions, NULLs and Custom Orders
How ORDER BY works and why rows have no order without it: ascending and descending keys, sorting by several columns, aliases and expressions, where NULLs go and how to move them, custom and data-dependent orders with CASE, natural sorting of codes, collations and ties.
kvi5hnuCode Sprout team member10 min readOn this page
A table is a set of rows, and sets have no order. Unless a query ends with ORDER BY, the database returns rows in whatever order is convenient for it: the order they happen to be stored in, the order an index produced, or the order a parallel scan finished. That order can change when the data changes, when statistics are updated, or when you upgrade the database. If the order matters, and for anything shown to a person it almost always does, say so with ORDER BY.
SELECT columns
FROM table_name
[WHERE condition]
ORDER BY sort_key [ASC | DESC] [NULLS FIRST | NULLS LAST], ...;
ORDER BY is the last clause of a SELECT apart from the row limit (article 4), so it can use everything the query has produced, including column aliases.
Ascending, descending and several keys
ASC (ascending, the default) sorts from low to high: smallest number, earliest date, and the alphabet from A. DESC sorts from high to low. Each key has its own direction.
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
-- Ascending is the default; DESC reverses one key
SELECT name, price FROM products ORDER BY price DESC;
-- Several keys: category first, then the most expensive within each category
SELECT category, name, price FROM products ORDER BY category, price DESC;
-- Sort by an alias, an expression, or a column you didn't select
SELECT name, price * stock AS stock_value FROM products ORDER BY stock_value DESC, name;
SELECT name FROM products ORDER BY weight_g / price DESC NULLS LAST, name;
name | price
-------------------+--------
Summit 4 tent | 489.00
Ridge 2 tent | 249.99
Trail 30 backpack | 89.95
Day 18 backpack | 54.00
Glow head torch | 34.50
Basecamp lantern | 27.00
Merino socks | 16.00
(7 rows)
category | name | price
----------+-------------------+--------
clothing | Merino socks | 16.00
lighting | Glow head torch | 34.50
lighting | Basecamp lantern | 27.00
packs | Trail 30 backpack | 89.95
packs | Day 18 backpack | 54.00
tents | Summit 4 tent | 489.00
tents | Ridge 2 tent | 249.99
(7 rows)
name | stock_value
-------------------+-------------
Ridge 2 tent | 2999.88
Trail 30 backpack | 1978.90
Summit 4 tent | 1467.00
Glow head torch | 1380.00
Merino socks | 1200.00
Basecamp lantern | 405.00
Day 18 backpack | 0.00
(7 rows)
name
-------------------
Trail 30 backpack
Day 18 backpack
Summit 4 tent
Ridge 2 tent
Merino socks
Glow head torch
Basecamp lantern
(7 rows)
With several keys, the database sorts by the first key, and uses the second key only to order rows that tie on the first. The third key orders rows that tie on the first two, and so on. In the second query, the categories are in alphabetical order, and inside each category the most expensive product comes first.

The third and fourth queries show that a sort key can be:
- an output alias, such as
stock_value; - an expression, such as
weight_g / price(grams per unit of price), even one that isn't in the select list; - a column that isn't selected. You can sort by
pricewithout showing it. The exception isSELECT DISTINCT, where you can only sort by output columns (article 4).
Sorting by position
You can also sort by the position of a column in the select list: ORDER BY 2 DESC sorts by the second column. It's handy at the console, but avoid it in saved queries. If someone later adds a column at the start of the select list, the query silently sorts by a different column.
Ties and stable results
If several rows have equal sort keys, their order relative to each other is undefined. It might look stable when you test it and change in production. That matters as soon as you show results in pages (article 10): with ties, a row can appear on two pages or on none.
The fix is to end the sort with a unique key, usually the primary key, as a tie-breaker. Most examples in this course end with , name or , product_id for that reason. Without the , name tie-breaker in the NULL-placement examples below, Day 18 backpack and Trail 30 backpack (both Kestrel) could come out in either order.
Where NULLs go
NULLs sort together at one end, but which end depends on the product:
| Product | NULLs in ascending order | NULLs in descending order | NULLS FIRST / NULLS LAST |
|---|---|---|---|
| PostgreSQL | last | first | yes |
| Oracle | last | first | yes |
| SQLite | first | last | yes (3.30+) |
| MySQL | first | last | no |
| SQL Server | first | last | no |
PostgreSQL and Oracle treat NULL as larger than every value; the others treat it as smaller.
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
\pset null '(null)'
-- PostgreSQL's default: NULLs last when ascending, first when descending
SELECT name, brand FROM products ORDER BY brand, name;
SELECT name, brand FROM products ORDER BY brand DESC, name;
-- Standard NULLS FIRST / NULLS LAST
SELECT name, brand FROM products ORDER BY brand NULLS FIRST, name;
-- The portable way (works in MySQL and SQL Server too): sort on "is it NULL?" first
SELECT name, brand
FROM products
ORDER BY CASE WHEN brand IS NULL THEN 0 ELSE 1 END, brand, name;
name | brand
-------------------+---------
Ridge 2 tent | Alpina
Summit 4 tent | Alpina
Day 18 backpack | Kestrel
Trail 30 backpack | Kestrel
Glow head torch | Lumen
Merino socks | Woolly
Basecamp lantern | (null)
(7 rows)
name | brand
-------------------+---------
Basecamp lantern | (null)
Merino socks | Woolly
Glow head torch | Lumen
Day 18 backpack | Kestrel
Trail 30 backpack | Kestrel
Ridge 2 tent | Alpina
Summit 4 tent | Alpina
(7 rows)
name | brand
-------------------+---------
Basecamp lantern | (null)
Ridge 2 tent | Alpina
Summit 4 tent | Alpina
Day 18 backpack | Kestrel
Trail 30 backpack | Kestrel
Glow head torch | Lumen
Merino socks | Woolly
(7 rows)
name | brand
-------------------+---------
Basecamp lantern | (null)
Ridge 2 tent | Alpina
Summit 4 tent | Alpina
Day 18 backpack | Kestrel
Trail 30 backpack | Kestrel
Glow head torch | Lumen
Merino socks | Woolly
(7 rows)
The lantern has no brand, so it went last in ascending order, first in descending order, and first with NULLS FIRST.
The last query shows the portable technique for products without NULLS FIRST/NULLS LAST. Sort first by a CASE expression that's 0 for NULL and 1 for everything else. Then sort by the column itself. To put NULLs last instead, swap the 0 and 1. This works in every product, including MySQL and SQL Server.
Custom orders with CASE
Sometimes the right order isn't alphabetical or numeric. You might want order statuses as pending, paid, shipped, delivered, or categories in the order the shop's menu shows them. A CASE expression (article 11) maps each value to a sort number:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
-- A custom order that isn't alphabetical
SELECT name, category
FROM products
ORDER BY CASE category
WHEN 'tents' THEN 1
WHEN 'packs' THEN 2
WHEN 'lighting' THEN 3
ELSE 4
END,
name;
-- A data-dependent key: tents by price, everything else by stock
SELECT name, category, price, stock
FROM products
ORDER BY category,
CASE WHEN category = 'tents' THEN price ELSE stock END;
name | category
-------------------+----------
Ridge 2 tent | tents
Summit 4 tent | tents
Day 18 backpack | packs
Trail 30 backpack | packs
Basecamp lantern | lighting
Glow head torch | lighting
Merino socks | clothing
(7 rows)
name | category | price | stock
-------------------+----------+--------+-------
Merino socks | clothing | 16.00 | 75
Basecamp lantern | lighting | 27.00 | 15
Glow head torch | lighting | 34.50 | 40
Day 18 backpack | packs | 54.00 | 0
Trail 30 backpack | packs | 89.95 | 22
Ridge 2 tent | tents | 249.99 | 12
Summit 4 tent | tents | 489.00 | 3
(7 rows)
- The first query puts the categories in a fixed business order, then sorts by name within each category. The
ELSE 4catches any category not in the list, so new categories still appear, at the end. - The second query uses a data-dependent key: the sort key changes with the row. Tents are ordered by price and everything else by stock. Each
THENbranch must produce the same type, or compatible types, because a sort key has a single type. Here,priceandstockare both numbers.
If a custom order is used in many queries, store it instead of repeating the CASE. A sort_order column in a categories table, used through a join, keeps the order in one place, and the business can change it without a code change.
Sorting text: collation, case and "natural" order
Text sorts according to the column's collation. This course's database uses the C collation, which compares character codes. That's fast and predictable, but it puts every uppercase letter before every lowercase letter, and it treats digits as characters:
CREATE TABLE bins (code VARCHAR(10) PRIMARY KEY);
INSERT INTO bins VALUES ('A10'), ('A2'), ('B1'), ('A1'), ('a3'), ('B12'), ('B3');
-- Text sorts character by character, and in the C collation uppercase comes first
SELECT code FROM bins ORDER BY code;
-- Case-insensitive order
SELECT code FROM bins ORDER BY lower(code), code;
-- "Natural" order: the letter part, then the digits as a number
SELECT code
FROM bins
ORDER BY upper(substring(code FROM 1 FOR 1)),
CAST(substring(code FROM 2) AS INTEGER),
code;
code
------
A1
A10
A2
B1
B12
B3
a3
(7 rows)
code
------
A1
A10
A2
a3
B1
B12
B3
(7 rows)
code
------
A1
A2
a3
A10
B1
B3
B12
(7 rows)
- Plain
ORDER BY codegivesA1, A10, A2, ..., a3.A10comes beforeA2because'1'sorts before'2', and the rest of the string is never looked at. Anda3comes last because lowercase letters come after all uppercase letters in theCcollation. ORDER BY lower(code), codeignores case. The second key,code, makes the order deterministic when two codes differ only in case.- The third query sorts naturally: by the letter, then by the digits converted to a number. This only works because every code is one letter followed by digits. For messier data, such as codes with a variable-length prefix, extract the parts with regular expressions (article 42), or store the parts in separate columns.
Language-aware collations, such as en_US, or ICU collations in PostgreSQL, sort letters case-insensitively and handle accents properly: é sorts next to e. Some ICU collations even sort numbers naturally (A2 before A10). You can choose a collation per query: ORDER BY name COLLATE "en-x-icu" in PostgreSQL, or ORDER BY name COLLATE Latin1_General_CI_AS in SQL Server. MySQL and SQL Server use case-insensitive collations by default, so in those products, ORDER BY code would already mix a3 in with the other A codes. Article 36 covers collations.
Sorting and performance
Sorting many rows costs time and memory. If the database has an index on the sort key, it can often read rows already in order and skip the sort, which is especially valuable with a row limit like "the 20 newest orders" (articles 10 and 55). Sorting by an expression, such as lower(name), can only use an index built on that same expression.
Don't sort in subqueries or views and expect the order to survive. An ORDER BY inside a derived table or a view has no guaranteed effect on the outer query's result (SQL Server even rejects it without TOP or OFFSET). Put ORDER BY in the outermost query, where the order is actually delivered.
What's current
NULLS FIRSTandNULLS LASTare supported by PostgreSQL, Oracle and SQLite (since 3.30). MySQL and SQL Server still don't support them, so use theCASEtechnique there.- PostgreSQL can use ICU collations, including variants that sort numbers naturally, such as
und-u-kn-true. PostgreSQL 17 also added abuiltincollation provider (with theC.UTF-8locale), which sorts quickly and doesn't depend on the operating system's libraries.
Common questions
Do rows come back in insertion order if I don't use ORDER BY?
Often they seem to, especially in a small, freshly loaded table, but nothing guarantees it. Updates, deletes, parallel query, indexes and maintenance can all change the order. Treat rows without ORDER BY as unordered.
Can ORDER BY use a column that isn't in the SELECT list?
Yes, unless the query uses DISTINCT, or combines results with UNION and similar operators (where only output columns can be used).
How do I sort in random order?
Use ORDER BY random() in PostgreSQL and SQLite, ORDER BY RAND() in MySQL, ORDER BY NEWID() in SQL Server, and ORDER BY DBMS_RANDOM.VALUE in Oracle. It's fine for small tables or tests, but it sorts every row, so it's slow on big tables. Article 10 shows cheaper ways to pick random rows.
Is sorting case-sensitive?
It depends on the collation. With the C collation or a binary collation, uppercase letters sort before lowercase letters. With case-insensitive collations (MySQL's and SQL Server's defaults), a and A sort together. Use ORDER BY lower(col) to get the same behaviour everywhere.
Why does '10' sort before '9'?
Because the values are text, compared character by character, and '1' sorts before '9'. Store numbers in numeric columns, or CAST them for sorting.
Can I sort by the result of a subquery?
Yes. Any expression can be a sort key, including a scalar subquery such as ORDER BY (SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.customer_id) DESC. Article 23 covers correlated subqueries.
Summary
- Without
ORDER BY, rows come back in no particular order. Always sort when the order matters. ASCis the default andDESCreverses a key. Each key has its own direction.- Later keys only break ties in earlier ones. End with a unique key so the order is fully determined.
- Sort keys can be columns, output aliases, expressions or unselected columns. Avoid sorting by column position in saved code.
- NULLs sort last in ascending order in PostgreSQL and Oracle, and first in MySQL, SQL Server and SQLite. Use
NULLS FIRST/NULLS LAST, or aCASEkey where they aren't supported. - Use
CASEfor custom business orders and data-dependent keys, or store the order in a table. - Text order depends on the collation. Character-by-character comparison makes
'A10'sort before'A2'unless you sort the numeric part as a number. - Only the outermost
ORDER BYdetermines the order of the result.
Practice questions
List products by category (alphabetically), and within each category, list the in-stock products before the out-of-stock ones, with the cheapest first.
Answer
SELECT category, name, stock, price
FROM products
ORDER BY category,
CASE WHEN stock > 0 THEN 0 ELSE 1 END,
price,
product_id;
The CASE key puts in-stock products (0) before out-of-stock ones (1) within each category. For packs, the in-stock Trail 30 backpack comes before the Day 18 backpack, even though it's more expensive. product_id is the final tie-breaker.
In MySQL, SELECT name, brand FROM products ORDER BY brand puts the lantern (NULL brand) first. How do you make it appear last, while the other brands stay in ascending order?
Answer
SELECT name, brand
FROM products
ORDER BY brand IS NULL, brand, name;
In MySQL, brand IS NULL is 0 for rows with a brand and 1 for the NULL row, so sorting on it first moves NULLs to the end. The portable spelling is ORDER BY CASE WHEN brand IS NULL THEN 1 ELSE 0 END, brand, name, which also works in SQL Server, where a condition can't be used directly as a value.
A web page shows 10 orders per page with ORDER BY placed_on DESC. Users report that some orders appear on two pages and others never appear. What's wrong?
Answer
Many orders share the same placed_on date, so the sort isn't fully determined. Rows with the same date can come out in a different order each time the query runs, so each page's slice is taken from a slightly different ordering. Add a unique tie-breaker: ORDER BY placed_on DESC, order_id DESC. Article 10 shows a better way to paginate as well.
Explain why ORDER BY code puts 'B12' before 'B3', and write a sort that puts 'B3' first for codes made of one letter and a number.
Answer
code is text, so it's compared character by character. After the equal Bs, '1' is compared with '3', and '1' sorts first, so 'B12' comes first. The rest of the string doesn't matter. To compare the number as a number:
ORDER BY substring(code FROM 1 FOR 1),
CAST(substring(code FROM 2) AS INTEGER)
Previous: NULL in SQL: Three-Valued Logic, IS NULL, COALESCE and NULLIF

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.