Sub topic 2
Selectivity: when an index helps and when it does not
This chapter assumes you know basic SQL (SELECT, WHERE, ORDER BY), understand tables, rows, and primary keys, and can run PostgreSQL 11 or later. Examples use the orders table from earlier chapters.
Selectivity
Selectivity is the fraction of rows a condition keeps. A condition that matches 2 rows out of 10 million is highly selective. One that matches 9 million rows is not. An index helps when it leads the database to a small set of rows. When a condition matches most of the table, reading the table directly is often cheaper.
CREATE TABLE orders (
id bigint PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL,
created_at timestamptz NOT NULL,
total_cents integer NOT NULL
);
CREATE INDEX orders_status_idx ON orders (status);Reading query plans with EXPLAIN
EXPLAIN shows the plan the planner chose without running the query. EXPLAIN ANALYZE runs it and adds actual timings and row counts.
Index Scan using orders_customer_id_idx on orders (cost=0.43..8.45 rows=2 width=40)
Index Cond: (customer_id = 42)A Seq Scan line means the database reads every row. An Index Scan line means it follows the index. Compare estimated rows with actual rows in EXPLAIN ANALYZE. Large gaps often mean stale statistics.
Composite indexes and the leftmost-prefix rule
A composite index covers several columns in a fixed order. The index can seek on the leading column and any columns after it that are also constrained.
CREATE INDEX orders_customer_created_idx
ON orders (customer_id, created_at);This index serves WHERE customer_id = 42 and WHERE customer_id = 42 AND created_at >= '2026-01-01'. It does not serve WHERE created_at >= '2026-01-01' efficiently, because the leading column is missing.
Writing predicates an index can use
Wrapping an indexed column in a function usually prevents an index seek. Compare the column to a range instead.
-- Index-friendly
SELECT count(*) FROM orders
WHERE created_at >= '2026-01-01' AND created_at < '2026-02-01';
-- Usually not index-friendly
SELECT count(*) FROM orders
WHERE date_trunc('month', created_at) = '2026-01-01';Clustered and secondary indexes
A clustered index stores table rows in index order. A secondary index stores its own sorted copy of the key and points back to the row. In PostgreSQL, table rows are not kept in primary-key order, so every index is effectively secondary. In MySQL InnoDB, the primary key is clustered.
Exercise
Table orders has 95% of rows with status 'open'. Will WHERE status = 'open' likely use orders_status_idx?
Show answer
Probably not. Most rows match, so a sequential scan is usually cheaper than following the index to each row.