By default, SQL doesn't guarantee any particular order for the rows a query returns — the database is free to hand them back in whatever order is most convenient internally, which is often (but not reliably) insertion order. ORDER BY is how you take control and explicitly sort your results.
This matters more than it sounds: a report sorted by hire date, a leaderboard sorted by score, or a product list sorted by price all depend on ORDER BY to be useful at all.
Basic Syntax: ASC and DESC
SELECT name, salary
FROM employees
ORDER BY salary DESC;
Result:
name | salary
--------------|--------
Alice Chen | 95000.00
Priya Nair | 88000.00
Marco Diaz | 72000.00
ASC (ascending, smallest/earliest first) is the default if you leave it off, so ORDER BY salary and ORDER BY salary ASC do the same thing. DESC reverses that to largest/latest first.
Sorting by Multiple Columns
You can sort by more than one column — the second column only matters for breaking ties in the first:
SELECT name, department, salary
FROM employees
ORDER BY department ASC, salary DESC;
Result:
name | department | salary
--------------|--------------|--------
Alice Chen | Engineering | 95000.00
Priya Nair | Engineering | 88000.00
Marco Diaz | Sales | 72000.00
Here, rows are grouped alphabetically by department first, and within each department, the highest earners appear first — a pattern you'll use constantly in real reports.
Sorting by Column Position
SQL technically allows sorting by a column's position number in the SELECT list instead of its name:
-- Sorts by the 3rd selected column (salary)
SELECT name, department, salary
FROM employees
ORDER BY 3 DESC;
This works, but it's fragile — if someone reorders the SELECT list later, the sort silently changes meaning without any error. Most style guides recommend always sorting by column name instead, reserving position-based sorting for quick throwaway queries at most.
Sorting with NULLs
Rows with a NULL value in the sort column need special attention — different databases place NULLs first or last by default (PostgreSQL puts them last in ASC order, for example, while others vary), so if NULL placement matters for your report, check your specific database's behavior rather than assuming.
Combined with WHERE for filtering, ORDER BY rounds out the two most common things you'll do to almost every query you write: narrow down which rows you want, then decide what order to see them in.
