ORDER BY
Sort SQL query results in ascending or descending order, handle multi-column tie-breakers, manage NULL placement, and paginate with LIMIT.
In relational database theory, a table is defined as an unordered collection of rows (a mathematical set).
Unless you explicitly add an ORDER BY clause, the database makes zero promises about the order in which rows are returned. A query might return rows in insertion order today, but after a table index rebuild, a server restart, or a database upgrade, the exact same query could return rows in a completely scrambled sequence.
If the order of your data mattersโsuch as displaying the top 10 highest-grossing movies or newest blog posts firstโyou must explicitly sort it with ORDER BY.
The Fundamental Sorting Syntax
The ORDER BY clause appears after FROM and WHERE:
SELECT product_name, price
FROM products
ORDER BY price;
Ascending (ASC) vs Descending (DESC)
ASC(Ascending): The default. Lowest to highest (numbers 1 to 10, letters A to Z, oldest date to newest date).DESC(Descending): Highest to lowest (numbers 10 to 1, letters Z to A, newest date to oldest date).
-- Most expensive products first:
SELECT product_name, price
FROM products
ORDER BY price DESC;
Given this table:
TABLE: products
โโโโโโฌโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโ
โ id โ product_name โ price โ
โโโโโโผโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโค
โ 1 โ Mechanical Mouse โ 29.99 โ
โ 2 โ 4K Monitor โ 399.00 โ
โ 3 โ USB-C Cable โ 9.99 โ
โ 4 โ Mechanical Board โ 89.99 โ
โโโโโโดโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโ
The descending query sorts rows by price:
โโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโ
โ product_name โ price โ
โโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโค
โ 4K Monitor โ 399.00 โ
โ Mechanical Board โ 89.99 โ
โ Mechanical Mouse โ 29.99 โ
โ USB-C Cable โ 9.99 โ
โโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโ
Multi-Column Sorting (Tie-Breakers)
What happens if multiple records have the same department or the same score? You can list multiple columns separated by commas. The database sorts by the first column, and only uses subsequent columns as tie-breakers:
SELECT last_name, first_name, department, salary
FROM employees
ORDER BY department ASC, salary DESC;
In this query:
- All employees are first grouped alphabetically by their
department(Engineering,Marketing,Sales). - Within
Engineering, the highest earners appear first (salary DESC). - Within
Marketing, the highest earners appear first, and so on.
Paginating Results with LIMIT and OFFSET
Often you do not want all 50,000 sorted rowsโyou just want the top 5, or you want page 2 of a search result. Combine ORDER BY with LIMIT and OFFSET:
-- Top 3 highest-rated movies
SELECT title, rating
FROM movies
ORDER BY rating DESC
LIMIT 3;
-- Page 2 of products (skipping the first 10, taking the next 10)
SELECT id, title, price
FROM products
ORDER BY id ASC
LIMIT 10 OFFSET 10;
[!WARNING] Never use
LIMITwithout anORDER BY! Without an explicit order,LIMIT 10returns 10 arbitrary, unpredictable rows.
Why Column Aliases Work in ORDER BY
A classic technical interview question asks:
โWhy can you use a column alias in
ORDER BY, but you get an error if you use it inWHERE?โ
The answer lies in the logical execution order of SQL clauses:
1. FROM โโโบ Identify the table
2. WHERE โโโบ Filter rows (Aliases DO NOT exist yet!)
3. SELECT โโโบ Pick columns and calculate aliases (AS)
4. ORDER BY โโโบ Sort the final output (Aliases CAN be used!)
5. LIMIT โโโบ Restrict the final output count
Because WHERE executes before SELECT, the database does not know what your alias means yet. But because ORDER BY runs after SELECT, aliases are fully recognized:
-- VALID: The alias 'annual_pay' is recognized in ORDER BY!
SELECT name, salary * 12 AS annual_pay
FROM employees
WHERE salary > 3000
ORDER BY annual_pay DESC;
How NULL Values Are Handled
How should the database sort a row whose value is NULL (unknown)?
- In SQLite and MySQL:
NULLis treated as the lowest possible value (appears at the very top inASC, and at the very bottom inDESC). - In PostgreSQL and Oracle:
NULLvalues sort highest by default. You can explicitly dictate their placement usingNULLS FIRSTorNULLS LAST:
-- Push missing values to the end regardless of direction
SELECT name, score
FROM players
ORDER BY score DESC NULLS LAST;
Common Traps to Avoid
- Alphabetical Sorting of Numbers Stored as Text: If a column has type
VARCHARinstead ofINTEGER, the numbers1,2,10,20will sort as'1','10','2','20'. Always verify column data types. - Clause Order Errors: The sequence of clauses is strict:
SELECT->FROM->WHERE->ORDER BY->LIMIT. PlacingORDER BYbeforeWHEREproduces an immediate syntax error. - Expensive Sorting on Large Unindexed Tables: Sorting millions of rows by a column without a database index forces the database to write temporary files to disk, drastically slowing down response times.
Next Steps
Master this concept to build a rock-solid foundation. Next, proceed to sorting-asc-desc.