Browse SQL Topics โ–ผ

ORDER BY

๐Ÿ“‚ Sorting & Pagination ๐Ÿ“˜ Lesson 28 of 81

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:

  1. All employees are first grouped alphabetically by their department (Engineering, Marketing, Sales).
  2. Within Engineering, the highest earners appear first (salary DESC).
  3. 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 LIMIT without an ORDER BY! Without an explicit order, LIMIT 10 returns 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 in WHERE?โ€

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: NULL is treated as the lowest possible value (appears at the very top in ASC, and at the very bottom in DESC).
  • In PostgreSQL and Oracle: NULL values sort highest by default. You can explicitly dictate their placement using NULLS FIRST or NULLS 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

  1. Alphabetical Sorting of Numbers Stored as Text: If a column has type VARCHAR instead of INTEGER, the numbers 1, 2, 10, 20 will sort as '1', '10', '2', '20'. Always verify column data types.
  2. Clause Order Errors: The sequence of clauses is strict: SELECT -> FROM -> WHERE -> ORDER BY -> LIMIT. Placing ORDER BY before WHERE produces an immediate syntax error.
  3. 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.

Test your understanding of ORDER BY

Quick interactive practice questions with instant feedback.

Take Quiz โ†’