pbPassingBI
/
Foundations & querying beginner 5 min

Sorting and limiting results

ORDER BY, ASC/DESC, and the dialect differences in LIMIT.

What you'll be able to do
  • Sort by one or more columns
  • Control null placement
  • Limit rows across different dialects

ORDER BY

SELECT name, total FROM orders
ORDER BY total DESC;

ASC is the default and can be omitted. Sort by several columns by listing them — each direction is set independently:

ORDER BY city ASC, total DESC

That sorts cities alphabetically, and within each city puts the largest orders first.

Sorting by alias or position

ORDER BY runs after SELECT, so unlike WHERE it can use column aliases:

SELECT price * qty AS revenue
FROM sales
ORDER BY revenue DESC;

Ordering by position — ORDER BY 2 — works but breaks the moment someone reorders the SELECT list. Avoid it outside quick exploration.

Where nulls sort

Nulls sort last in ascending order in PostgreSQL and Oracle, first in MySQL and SQL Server. If it matters, be explicit where supported:

ORDER BY total DESC NULLS LAST

Limiting rows

The dialects differ, which is worth knowing for interviews:

SELECT ... ORDER BY total DESC LIMIT 10;              -- Postgres, MySQL, SQLite
SELECT TOP 10 ... ORDER BY total DESC;                -- SQL Server
SELECT ... ORDER BY total DESC FETCH FIRST 10 ROWS ONLY;  -- Oracle, standard SQL

Always pair a limit with ORDER BY. Without one, which ten rows you get is arbitrary and can change between runs.

Key points
  • ORDER BY can use SELECT aliases; WHERE cannot
  • LIMIT / TOP / FETCH FIRST are dialect-specific
  • A limit without ORDER BY returns an arbitrary set of rows
Check yourself