A table has no fixed row order (Chapter 1). If the order matters, ask for it.
Sort by a column
SELECT name, price
FROM products
ORDER BY price;| Keyword | Order | Numbers | Text | Dates |
|---|---|---|---|---|
ASC (the default) | ascending | small to large | A to Z | earlier first |
DESC | descending | large to small | Z to A | later first |
ORDER BY price DESC puts the most expensive product first.
In this database, upper-case letters sort before lower-case letters, so 'sudo Coffee Mug' comes after 'Root Hoodie'.
Several sort keys
SELECT name, country
FROM customers
ORDER BY country, name;The rows are sorted by country. Rows with the same country are then sorted by name. Each key has its own direction: ORDER BY country ASC, name DESC.
result
| name | country |
|---|---|
| Lucas Silva | BR |
| Ava Chen | CA |
| Liam Patel | CA |
| Omar Haddad | CA |
| Hannah Weber | DE |
The column in ORDER BY does not have to be in the SELECT list. SELECT name FROM customers ORDER BY signup_date is correct.
Where NULL goes
PostgreSQL sorts NULL as larger than every value: last with ASC, first with DESC.