SELECT, WHERE and ORDER BY

The clause order the database actually uses, NULL as unknown, and the two honest averages that disagree.

11 min read🐘 Relational Databases in Depth

Every query in this course is a variation on one statement, so it is worth being precise about the parts before the interesting ones arrive. Most of what surprises people later is not joins or window functions — it is NULL, and it is here.

The shape, and the order it runs in

sql
select   name, salary          -- 5. which columns come back
from     employee              -- 1. where the rows come from
where    salary > 5000         -- 2. which rows survive
group by department            -- 3. how they are collapsed
having   count(*) > 3          -- 4. which groups survive
order by salary desc           -- 6. how the result is sorted
limit    10;                   -- 7. how many you keep

You write it in that order and the database does not run it in that order — the numbers are the logical sequence. Two consequences follow immediately, and both look arbitrary until you know why:

  • where cannot use a column alias. select salary * 12 as annual ... where annual > 100000 fails, because where runs before the select list exists.
  • order by can. It runs after, so the alias is there.

That is also why where filters rows and having filters groups: one runs before the grouping, the other after.

NULL is not a value, and this is where the day goes

NULL means unknown. Not zero, not empty string — unknown. Every comparison with an unknown is itself unknown, and where keeps only rows that are true.

Four employees. Two of them have no manager recorded and one has no salary:

plaintext
### rows in the table        -> 4
### count(manager)           -> 2
### where manager = null     -> 0
### where manager is null    -> 2
### where manager <> 'bo'    -> 0

Line by line, because each is a bug somebody has shipped:

  • count(*) is 4, count(manager) is 2. count(column) counts non-null values. count(*) counts rows. They answer different questions and look like the same one.
  • = null returns nothing, ever. Not an error — an empty result. is null is the only test.
  • <> 'bo' returns nothing either, and this is the one that catches experienced people. Two employees do not have 'bo' as their manager — but their manager is unknown, and unknown is not provably different from 'bo', so they are excluded. "Not X" silently drops every row where the value is missing. If you want them, ask: where manager <> 'bo' or manager is null.

And then the same question, answered two ways:

plaintext
### avg(salary)              -> 7000.0
### sum(salary)/count(*)     -> 5250

Both are "the average salary". avg ignores the null row and divides by 3; sum/count(*) divides by 4. Neither is wrong — they answer average of the salaries we know and average across all employees, treating unknown as zero. The bug is not picking one; the bug is not noticing there was a choice.

Sorting, and where NULL goes

plaintext
### order by salary, nulls where?
###   cy null
###   ana 5000
###   di 7000
###   bo 9000

The null sorted first here. That is not a rule you can rely on: the SQL standard leaves it to the implementation, PostgreSQL puts nulls last ascending, and others differ. If it matters, say so — order by salary nulls last — rather than discovering the difference when you change database.

order by and limit belong together

limit 10 without order by means any ten rows. Not the first ten, not the newest ten — whichever ten the plan produced, which can change when the data grows, an index is added, or the plan flips to a parallel scan.

And ordering by a column with ties has the same problem one level down: tied rows may come back in any order, and in a different order on the next query. A paginated query must sort by something unique — usually the id as a final tiebreaker — or rows move between pages. The pagination lesson in the API course is this same fact arriving as a customer complaint.

distinct is usually a symptom

select distinct is a sorting or hashing step over the whole result, and it is nearly always added to hide duplicates that a join produced:

sql
-- duplicates because each customer has many orders
select distinct c.name from customer c join orders o on o.customer_id = c.id;
 
-- says what you meant, and can stop at the first match
select c.name from customer c where exists (select 1 from orders o where o.customer_id = c.id);

When distinct appears, the useful question is where did the duplicates come from — the answer is usually a join whose cardinality is not what the author thought, and the joins lesson is where that is taken apart.

Reading before writing

Three habits that make the rest of this course easier:

  • select * is fine at a prompt and wrong in code. It fetches columns you do not use, breaks when somebody adds one, and hides the dependency from anyone reading the query.
  • Qualify column names once there is more than one table. o.id and c.id are different columns, and an unqualified id is a question the reader has to answer.
  • Filter as early as you can express it. The planner will often move it for you, but a query that says what it means is a query you can read a plan for.

Under the hood: walking a B-tree, and why WHERE sometimes needs no sort at all

The production-engineering course's slow-query lesson covers whether the planner picks an index over a sequential scan, from statistics and estimated selectivity. This section is about what a B-tree index actually is, and why that structure explains two things this lesson has not touched yet: how an equality lookup finds a row without reading the table, and why order by on an indexed column sometimes costs nothing extra.

A B-tree index is a sorted, hierarchical structure, not a lookup table. A root page holds a handful of key ranges, each pointing to a child page; each child page does the same, one or two levels down, until a leaf page holds the actual sorted keys — and, for each key, a pointer to the row's physical location (PostgreSQL calls this a TID, a tuple identifier: page number plus offset). Finding where salary = 7000 means comparing 7000 against the root page's ranges, following one pointer down, comparing again, following another pointer, until a leaf page is reached — typically two to four page reads for a table with millions of rows, because each level of the tree fans out to dozens or hundreds of children. That is the mechanical reason an index lookup is close to constant-time relative to table size: the tree's height grows logarithmically, not linearly, with row count.

This is also why a range condition and an order by on the same column can be almost free together. Leaf pages in a B-tree are linked in sorted order — after finding the first leaf entry that satisfies salary > 5000, the index can walk forward along the leaf chain, and every entry it visits is already in ascending order. If the query also says order by salary, the database does not need a separate sort step at all: it can return rows in the order the index already gives them. Take away the index, or ask for a sort on a column the index does not cover, and the database has no choice but to gather every qualifying row first and run an explicit sort (the Sort step visible in an EXPLAIN plan) — which is real work, and the reason "the plan has a Sort node" is worth noticing when reading one.

An index scan and an index-only scan are not the same operation, and the difference is about correctness, not just speed. A plain index scan uses the B-tree to find which rows match, then still has to visit the actual table (the "heap," in PostgreSQL's terms) for each one — to read the columns the query asked for that are not in the index, and, more subtly, to check visibility: whether that row version is actually visible to the current transaction under MVCC, since the index entry itself does not carry that information. An index-only scan skips the second trip, but only when two things both hold: every column the query needs is present in the index itself (a covering index), and PostgreSQL's visibility map already knows the containing page has no rows that need a fresh visibility check (a page marked "all visible," true once it has been vacuumed since its last modification). Miss either condition and the planner falls back to an ordinary index scan with the heap visit — which is why adding columns to an index for "index-only scan" purposes only pays off on a table whose pages are actually getting vacuumed and marked visible; the JDBC-level ResultSet code from the driver lessons never sees this distinction, only its effect on latency.

Try it yourself

Reason through what a composite index can serve without a sort

A table has an index on (customer_id, created_at). Two queries run against it:

  1. where customer_id = 41 order by created_at desc
  2. where created_at > '2026-01-01' order by customer_id
Only the first can walk the index leaf order for free

The index is sorted by customer_id first, and only sorted by created_at within each customer_id. Query 1 fixes customer_id to a single value, so within that one value the matching leaf entries are already in created_at order (descending, if the index or the scan direction matches) — the database can walk the leaf chain and return rows presorted, with no separate sort step. Query 2 does not fix customer_id at all; created_at > '2026-01-01' can match rows spread across every customer_id, and within the index those rows are grouped by customer_id first, not globally ordered by created_at — so satisfying order by customer_id from this index would mean jumping between many different, non-adjacent parts of the leaf chain rather than reading it straight through, which the database will not do. It instead gathers the qualifying rows (however it finds them) and runs an explicit sort. Same index, same two columns, and only the query whose equality condition matches the index's leading column gets the sort for free — which is the practical reading of the composite-index PRODUCTION note above.

Misconceptions

  • "An index means the database never has to touch the table." Only an index-only scan avoids the heap visit, and only when every needed column is in the index and the page is marked all-visible in the visibility map. An ordinary index scan — the common case — still visits the table for every matching row, to fetch columns and to confirm visibility.
  • "Adding order by to a query that already has a matching index is free." It is free only when the sort's column(s) align with how the index is actually ordered — which, for a composite index, depends on the equality columns coming first, as the PRODUCTION note above shows. An order by on a column that is not the index's leading (or only) sorted dimension for that query still costs an explicit sort, index or no index.

Sources

  • PostgreSQL documentation, Chapter 11, "Indexes" (B-tree indexes, index-only scans, the visibility map, multicolumn indexes).
  • PostgreSQL documentation, Chapter 14, "Performance Tips" (EXPLAIN output and its Sort/Index Scan/Index Only Scan node types).
  • Markus Winand, Use the Index, Luke (B-tree traversal and composite-index column ordering).
Progress is saved on this device and to your account when signed in.