Sorting & Limiting: ORDER BY and LIMIT 🔢
In relational databases, rows are stored as an unordered set (based on mathematical relation theory).
If you do not specify an order, the database engine returns rows in whatever sequence happens to be quickest off the physical disk or buffer cache. The order may change between queries!
To guarantee consistent, predictable ordering, you must use ORDER BY.
1. Single Column Sorting with ORDER BY ↕️
The ORDER BY clause sorts your output:
ASC(Ascending): Smallest to largest (, , oldest to newest date). This is the default!DESC(Descending): Largest to smallest (, , newest to oldest date).
Example 1: Sort by Salary Ascending (Lowest to Highest)
SELECT first_name, salaryFROM employeesORDER BY salary ASC; -- (ASC is optional, but good for clarity)Example 2: Sort by Salary Descending (Highest to Lowest)
SELECT first_name, salaryFROM employeesORDER BY salary DESC;Result:
┌────────────┬────────┐
│ first_name │ salary │
├────────────┼────────┤
│ Priya │ 98000 │ <-- Highest paid first
│ Aarav │ 95000 │
│ Neha │ 64000 │
│ Rahul │ 62000 │
│ Amit │ 55000 │ <-- Lowest paid last
└────────────┴────────┘
2. Multi-Column Sorting (Tie-Breaking) 👔
What happens if multiple employees belong to the same department? How should they be sorted?
You can provide multiple columns separated by commas. The database sorts by the first column; if values are identical (a tie), it uses the second column:
SELECT first_name, department, salaryFROM employeesORDER BY department ASC, salary DESC;How SQL processes this:
- Groups all
Engineeringrows together, allMarketingrows together, allSalesrows together (). - Within each department, sorts individuals from highest to lowest salary ().
3. Where Do NULL Values Go in Sorting? 🤔
Different SQL dialects have slightly different default rules for sorting missing (NULL) values:
- In PostgreSQL and Oracle,
NULLS FIRSTis default forDESC, andNULLS LASTforASC. - In MySQL and SQLite,
NULLvalues are treated as the lowest possible values.
Standard SQL lets you explicitly control this with NULLS FIRST or NULLS LAST:
-- Always put employees with missing bonus data at the end:SELECT first_name, bonusFROM employeesORDER BY bonus DESC NULLS LAST;4. Restricting Rows with LIMIT 🛑
When building modern web and mobile apps, you rarely want to return 100,000 rows to the user's phone. You want the top 5, top 10, or page 1.
Use the LIMIT clause to restrict the number of rows returned:
-- Find the Top 3 Highest Paid Employees:SELECT first_name, salaryFROM employeesORDER BY salary DESCLIMIT 3;Result:
┌────────────┬────────┐
│ first_name │ salary │
├────────────┼────────┤
│ Priya │ 98000 │
│ Aarav │ 95000 │
│ Neha │ 64000 │
└────────────┴────────┘
Critical Rule: Never use
LIMITwithout anORDER BY! WithoutORDER BY, the database returns an unpredictable, arbitrary subset of rows.
5. Pagination with OFFSET 📄
How do Google search results or e-commerce catalog pages work? When you click "Page 2", the app skips the first 10 items and displays the next 10 items.
In SQL, this is achieved using LIMIT and OFFSET:
LIMIT n: How many rows to take.OFFSET m: How many rows to skip from the beginning.
-- Page 1 (Items 1 to 5):SELECT id, title, priceFROM productsORDER BY id ASCLIMIT 5 OFFSET 0;-- Page 2 (Items 6 to 10):SELECT id, title, priceFROM productsORDER BY id ASCLIMIT 5 OFFSET 5;-- Page 3 (Items 11 to 15):SELECT id, title, priceFROM productsORDER BY id ASCLIMIT 5 OFFSET 10;The Universal Pagination Formula:
⚡ Performance Caution on Deep Offset Pagination:
OFFSET 1000000 LIMIT 10forces the database to read 1,000,010 rows from disk, discard the first million, and return 10. For massive scale, professional backend engineers use Keyset / Cursor Pagination (WHERE id > last_seen_id ORDER BY id ASC LIMIT 10), which runs in time!
6. The True Execution Order of SQL Clauses ⚙️
Here is one of the most important concepts every software engineer must internalize:
SQL queries are NOT executed in the order they are written!
Look at how you write a query:
-- 1. Written Order:SELECT department, salary -- 1FROM employees -- 2WHERE salary > 60000 -- 3ORDER BY salary DESC -- 4LIMIT 5; -- 5Now, look at how the database engine actually executes it under the hood:
┌────────────────────────────────────────────────────────┐
│ SQL ENGINE EXECUTION ORDER │
├───────┬──────────────┬─────────────────────────────────┤
│ Step 1│ FROM │ Locate the table on disk │
│ Step 2│ WHERE │ Filter individual rows │
│ Step 3│ SELECT │ Pick and compute column values │
│ Step 4│ ORDER BY │ Sort the selected rows │
│ Step 5│ LIMIT/OFFSET │ Truncate and skip result rows │
└───────┴──────────────┴─────────────────────────────────┘
Try the Interactive Visual Stepper 🕹️
Step through a live query pipeline below to see rows loaded, filtered, grouped, and sorted one clause at a time:
The database engine identifies the target table ('employees') on disk or buffer cache and loads all 5 raw records into working memory.
employees table5 rows in memoryWhy Does This Matter?
Because WHERE runs beforeSELECT, you cannot use a column alias defined in SELECT inside your WHERE clause!
-- ❌ FAILS WITH ERROR: Column "annual_pay" does not exist!SELECT first_name, salary * 12 AS annual_payFROM employeesWHERE annual_pay > 1000000; -- Engine doesn't know what annual_pay is yet!-- ✅ CORRECT:SELECT first_name, salary * 12 AS annual_payFROM employeesWHERE (salary * 12) > 1000000;However, because ORDER BY runs afterSELECT, using aliases in ORDER BY works seamlessly:
-- ✅ WORKS PERFECTLY:SELECT first_name, salary * 12 AS annual_payFROM employeesORDER BY annual_pay DESC;Flashcard Checkpoint 🎴
Why can you use a column alias in ORDER BY, but NOT in a WHERE clause?
What is the default sort direction of an ORDER BY clause if you omit ASC or DESC?