ORDER BY example
SELECT name,
stock
FROM products
ORDER BY stock ASC, name ASC
LIMIT 5;Speaker and Pro Laptop tie with zero stock. name ASC decides a reproducible order within that tie.
Check the result with small data
Two items cost the same and a third is more expensive.
WITH products(id, name, price) AS (
VALUES (1, 'Mouse', 20), (2, 'Keyboard', 20), (3, 'Display', 150)
)
SELECT name, price FROM products
ORDER BY price ASC, id ASC;| name | price |
|---|---|
| Mouse | 20 |
| Keyboard | 20 |
| Display | 150 |
The price sorts from lowest to highest and the id breaks the tie between Mouse and Keyboard. Without a second criterion, the order of tied rows is not guaranteed.
Check your understanding: Which item would come first with ORDER BY price DESC, id ASC?
Show answer
Display, priced 150: DESC puts the highest prices first. Mouse and Keyboard would follow, ordered by id.
How to use ORDER BY
ASC sorts from lowest to highest and is usually the default. DESC reverses the direction. The second criterion only breaks ties in the first.
What changes from case to case
Sorting by aliases or expressions
SELECT name,
price * stock AS stock_value
FROM products
ORDER BY stock_value DESC, id;Using the alias saves repeating the expression and makes the intent easier to read. Being able to use aliases in ORDER BY is common, although the exact rules get more complicated in set queries.
Where NULL values appear
The default position of NULL is not the same on every engine. PostgreSQL supports NULLS FIRST and NULLS LAST; other engines need an extra expression. If the position of nulls matters, do not rely on the default.
Common mix-ups with ORDER BY
Limiting before defining a sufficient order
LIMIT 10 without a stable order does not mean “the first ten” in a reproducible sense.
Sorting by position
ORDER BY 2 is valid on several engines, but it breaks silently if the column list changes. Using names or aliases makes maintenance easier.