π± BasicsbeginnerCommonly used
How to sort results with ORDER BY in SQL
Sort query results by one or more columns, ascending or descending.
Sort ascending (A β Z, 1 β 9)All databases
SELECT name, age
FROM users
ORDER BY age ASC;ASC sorts from smallest to largest (or A to Z). ASC is the default so it can be omitted.
Sort descending (Z β A, 9 β 1)All databases
SELECT name, age
FROM users
ORDER BY age DESC;DESC sorts from largest to smallest (or Z to A).
When to use: Getting the newest records, highest scores, most recent dates.
Sort by multiple columnsAll databases
SELECT name, country, age
FROM users
ORDER BY country ASC, age DESC;First sorts by country A-Z, then within each country sorts by age from oldest to youngest.
When to use: When you need a primary and secondary sort.
Sort by column positionAll databases
SELECT name, age, country
FROM users
ORDER BY 2 DESC; -- 2 = age columnYou can reference columns by their position number in the SELECT list.
Avoid in production β fragile if column order changes.
Sort NULLs last (PostgreSQL)PostgreSQL
SELECT name, score
FROM users
ORDER BY score DESC NULLS LAST;By default PostgreSQL puts NULLs first in DESC order. NULLS LAST puts them at the end.
Common Mistakes
- βRelying on default sort order without ORDER BY β SQL tables have no guaranteed order without it
- βSorting by column alias in databases that do not support it (use column name or position instead)