Sorting Results
1. Sorting by Single Column
SELECT * FROM orders ORDER BY placed_at;
| Default | Behavior |
| Direction | ASC |
| NULLs | NULLS LAST for ASC, NULLS FIRST for DESC |
2. Sorting by Multiple Columns
SELECT * FROM orders ORDER BY customer_id, placed_at DESC;
3. Ascending Order
SELECT * FROM customers ORDER BY full_name ASC;
4. Descending Order
SELECT * FROM orders ORDER BY total_cents DESC;
5. Sorting with NULL Values
SELECT * FROM customers ORDER BY last_seen DESC NULLS LAST;
| Clause | Effect |
| NULLS FIRST | NULLs at top |
| NULLS LAST | NULLs at bottom |
6. Sorting by Expression
SELECT * FROM customers ORDER BY length(full_name), full_name;
7. Sorting by Column Alias
SELECT id, total_cents/100.0 AS dollars FROM orders ORDER BY dollars DESC;
8. Sorting by Column Position
SELECT id, full_name, created_at FROM customers ORDER BY 3 DESC;
Note: Position-based ORDER BY is fragile; refactoring the SELECT list silently changes order. Prefer aliases.
9. Using COLLATE in ORDER BY
SELECT * FROM customers ORDER BY full_name COLLATE "C";
SELECT * FROM products ORDER BY name COLLATE "en-US-x-icu";
| Collation | Behavior |
| "C" / "POSIX" | Byte order (fastest, predictable) |
| ICU collations | Locale-aware, language-correct |
10. Combining ORDER BY with LIMIT
SELECT * FROM orders ORDER BY total_cents DESC LIMIT 10;
Note: Add a matching multi-column index for ORDER BY + LIMIT queries to enable top-N index scans.