Sorting with Multiple Columns and NULL Handling
You'll learn how to sort query results by multiple columns in priority order and control where NULL values appear.
Multi-Level Sorting
When you sort by multiple columns, SQL applies them in order—like sorting a deck of cards first by suit, then by rank within each suit. The first column you list has the highest priority, the second breaks ties, and so on.
SELECT customer_name, city, total_spent
FROM customers
ORDER BY city ASC, total_spent DESC;
This query sorts customers by city alphabetically first. Within each city, customers are then sorted by total_spent from highest to lowest. Think of it as nested sorting: primary sort, then secondary sort within groups.
NULL Positioning
By default, databases treat NULL values inconsistently—some put them first, others last. You can control this explicitly:
SELECT product_name, warranty_months
FROM products
ORDER BY warranty_months DESC NULLS LAST;
The NULLS FIRST or NULLS LAST keywords let you decide where missing values appear in your sorted results. This is crucial when NULLs represent "unknown" or "not applicable" rather than zero.
Practical Example
SELECT employee_name, department, salary
FROM employees
ORDER BY department ASC, salary DESC NULLS LAST;
This sorts employees alphabetically by department, then by salary (high to low) within each department, placing anyone with an unknown salary at the bottom of their department group.
Key Takeaway: Multi-column sorting applies priorities left-to-right in your ORDER BY clause, and explicit NULL handling (NULLS FIRST/NULLS LAST) ensures predictable placement of missing values in your sorted results.