Skip to content
Back to 50 Concepts
Topic 17 of 50query-executionBeginner

# Topic 17: ORDER BY Sorting

Sorting query results, multi-column ordering, ASC and DESC, NULLS FIRST / NULLS LAST, and avoiding in-memory sort spills.

1. Definition

The ORDER BY clause sorts the result set of a query by one or more columns or expressions in ascending (ASC) or descending (DESC) order.

Relational Invariant:Deterministic relational algebra contract evaluated by the Cost-Based Optimizer.

2. Explain Like I'm 5

Intuitive mental model for beginners

Relational databases do not store rows in any guaranteed order. ORDER BY is the organizer that sorts items alphabetically by name, or numerically by price.

3. Animation & Visual Simulation

Interactive Engine Trace
Interactive Engine Simulation

ORDER BY Sorting Visual Simulator

Step 1 of 3
SQL>SELECT id, customer, amount FROM invoices ORDER BY amount DESC NULLS LAST LIMIT 10;Active Input

Step 1: Input & Parsing Stage

Engine Action: Validate SQL syntax and resolve schema metadata for ORDER BY Sorting
SQL Input

Initiating ORDER BY Sorting

Schema Catalog

Checking Table Invariants

How the Database Executes This:

The database engine inspects active tables, verifies permissions, and prepares the physical operation.

💡 Alphabetizing index cards: If they are already filed in order (indexed), you pick them up instantly; if they are in a messy pile, you must sit down and sort them on your desk.

4. Real-World Example

An executive leaderboard displays top sales reps ordered by sales revenue, with ties broken by seniority.

Sales Leaderboard
namerevenuehire_date
Alice$150,0002021-01-15
Bob$120,0002020-05-10
Charlie$120,0002022-09-01
Relational walkthrough: ORDER BY revenue DESC, hire_date ASC breaks ties deterministically.

5. SQL Syntax

ANSI SQL / PostgreSQL Dialect
Step 1: Multi-column sorting
SELECT name, department, salary
FROM employees
ORDER BY department ASC, salary DESC;
First groups by department alphabetically, then sorts salaries highest to lowest within each department.
Step 2: Explicit NULL placement
SELECT id, name, priority
FROM tasks
ORDER BY priority DESC NULLS LAST;
Ensures tasks without a priority value do not appear at the top of the list.

6. Important Rules & Behaviors

RuleBehavioral Explanation
No Default OrderWithout an ORDER BY clause, the database makes ZERO guarantee about physical row return order.
Position NumbersORDER BY 1, 2 sorts by the 1st and 2nd columns in the SELECT projection, but explicit names are preferred.
NULL Placement DefaultsIn PostgreSQL, ASC defaults to NULLS LAST, while DESC defaults to NULLS FIRST.
Sort memory boundary (work_mem)If sorted tuples exceed work_mem, the engine spills to disk using an external two-pass merge sort.
Index-backed sorting (zero CPU)Scanning an index in key order satisfies ORDER BY without performing an in-memory sort operation.

7. Deep Dive: Index Sorting vs In-Memory work_mem Spills

If an index matches the requested ORDER BY clause (e.g. index on (department, salary DESC)), the engine traverses the index leaf pointers directly in pre-sorted order. Without an index, the engine performs an external sort, which spills to disk if work_mem is exceeded.

-- EXPLAIN showing index traversal with ZERO sorting cost:
EXPLAIN ANALYZE
SELECT id, created_at FROM orders ORDER BY created_at DESC LIMIT 10;
-- Result: "Index Scan Backward using idx_orders_created_at"
Caution: Sorting unindexed million-row tables causes temporary disk files and high query latency.

8. Advantages & Disadvantages

Advantages

  • •Guarantees deterministic presentation order.
  • •Enables correct pagination when combined with LIMIT.

Disadvantages & Trade-offs

  • •Unindexed sorts require high memory and CPU to sort rows in work_mem.

9. Common Interview Questions

Q1.What happens when an ORDER BY query exceeds available work_mem in PostgreSQL?

The database first attempts an in-memory QuickSort. If the candidate tuples exceed the work_mem allocation, the engine spills the intermediate tuples to temporary files on disk and performs an External Two-Pass Merge Sort. This introduces severe disk I/O latency. Increasing work_mem for specific sessions or adding an index avoids disk spills.

Q2.How can an index completely eliminate the execution cost of ORDER BY?

A B-Tree index is already physically ordered on disk. If a query orders by the indexed column (e.g. ORDER BY created_at DESC), the Cost-Based Optimizer can perform an Index Scan in the backward direction, streaming rows already sorted. EXPLAIN ANALYZE will show "Index Scan" with ZERO "Sort" nodes in the execution plan.

Q3.What is the difference between NULLS FIRST and NULLS LAST?

NULLS FIRST places all NULL records at the beginning of the result set; NULLS LAST places them at the end. In PostgreSQL: ORDER BY col ASC defaults to NULLS LAST, while ORDER BY col DESC defaults to NULLS FIRST. Explicitly specifying NULLS LAST ensures pagination consistency when descending.

Q4.Why does "ORDER BY RAND()" or "ORDER BY RANDOM()" cause catastrophic performance on large tables?

ORDER BY RANDOM() assigns a random floating-point value to every row in the table, forcing the engine to perform a full sequential scan of the entire table and sort all millions of rows in memory or disk, just to discard all but the top few. It runs in O(N log N) time and destroys database performance.

Q5.Can you sort by a column that is not included in the SELECT projection list?

Yes, in standard queries (SELECT id, name FROM users ORDER BY created_at), the engine retains created_at in the working tuple during sorting and strips it during final projection. However, if the query includes DISTINCT or UNION, all ORDER BY expressions MUST appear in the SELECT list because duplicate elimination happens before sorting.

10. Interview-Ready Answer

“ORDER BY determines the sequence of returned tuples. Because relational tables have no intrinsic order, sorting is mandatory for pagination. Using matching B-Tree indexes eliminates in-memory sort overhead entirely.”

11. Quick Test

Scenario Question:

Which clause ensures that NULL values appear at the end of a descending sort in PostgreSQL?

Select your answer: