Sub topic 13
Indexing for the queries you run
This chapter assumes you have the authors, books, book_authors, and readings tables from earlier chapters, and that you can run psql. You should be comfortable with joins and WHERE clauses. The goal is to decide which indexes this schema needs, and to avoid adding ones it doesn't.
What an index does and what it costs
An index is a separate data structure that PostgreSQL maintains beside a table. It lets the database find rows matching a condition without reading the whole table. The default type is a B-tree, which supports =, <, >, BETWEEN, and ORDER BY on the indexed columns.
Every index has a price:
- Each
INSERTmust add an entry to every index on the table. - An
UPDATEthat changes an indexed column must update that index as well. - Indexes take disk space and add work for
VACUUM.
So the rule is to index for queries you actually run, not for every column. A personal book log is small, but the habits you build here carry over to larger systems.
What you already have for free
PostgreSQL creates an index automatically for every PRIMARY KEY and every UNIQUE constraint. In this schema that gives you:
authors_pkey,books_pkey, andreadings_pkeyon the identity columns.- A unique index on
books.isbn13, which also makesON CONFLICT (isbn13)work. book_authors_pkeyon(book_id, author_id).
PostgreSQL does not create an index on the referencing side of a foreign key. The REFERENCES clause only checks that the target row exists. So readings.book_id and book_authors.author_id have no index yet.
Column order in a composite index
A B-tree on (book_id, author_id) is sorted by book_id first, then by author_id within each book_id. It helps queries that filter on the leftmost column or columns:
WHERE book_id = 7can use it.WHERE book_id = 7 AND author_id = 3can use it.WHERE author_id = 3cannot use it efficiently, because matching entries are scattered through the whole index.
That last case is exactly the query "all books by this author". The primary key covers lookups from book to authors, but not from author to books.
Indexing the foreign keys
Add the two missing foreign-key indexes:
CREATE INDEX book_authors_author_id_idx ON book_authors (author_id);
CREATE INDEX readings_book_id_idx ON readings (book_id);These pay off in two ways. They speed up joins that start from an author or a book and look for the matching rows in the child table. They also speed up referential actions. When you delete a book, ON DELETE CASCADE on book_authors must find the child rows. Without an index on the child column, PostgreSQL scans the whole child table for each deleted parent row. The same applies to the ON DELETE RESTRICT check on author_id.
Here is where each lookup direction gets its index:
Partial indexes for a small slice of the data
Most queries on readings probably care about a subset. You might often ask "what am I reading right now?" Only a few rows have status = 'reading', so indexing all of them wastes space. A partial index includes only rows matching a predicate:
CREATE INDEX readings_currently_reading_idx
ON readings (book_id)
WHERE status = 'reading';
CREATE INDEX readings_finished_on_idx
ON readings (finished_on DESC)
WHERE status = 'finished';The first serves a query like SELECT book_id FROM readings WHERE status = 'reading'. The second serves "my ten most recently finished books":
SELECT book_id, finished_on, rating
FROM readings
WHERE status = 'finished'
ORDER BY finished_on DESC
LIMIT 10;The planner uses a partial index only when it can prove the query's WHERE clause implies the index predicate. The query must therefore include status = 'finished' itself. A query without it cannot use this index, even if you know every row it returns happens to be finished.
Expression indexes for case-insensitive lookups
An index on title does not help WHERE lower(title) = 'dune', because the query compares a computed value. Index the same expression:
CREATE INDEX books_title_lower_idx ON books (lower(title));
SELECT book_id, title
FROM books
WHERE lower(title) = lower('Dune');The query expression must match the index expression exactly. If you index lower(title) but query with upper(title), the index is ignored.
Building an index on a table in use
A plain CREATE INDEX blocks writes to the table while it builds. On a table that other sessions are writing to, use:
CREATE INDEX CONCURRENTLY readings_rating_idx ON readings (rating);This takes longer and cannot run inside a transaction block. If it fails partway, it leaves an invalid index behind. Drop it with DROP INDEX and try again.
Checking that an index is used
Small tables are a trap. With a few dozen rows, a sequential scan (reading the whole table) is cheaper than an index lookup, so the planner ignores your index. That is correct behavior, not a bug. To see an index matter, test on a scratch database with realistic row counts:
INSERT INTO books (title)
SELECT 'Generated Book ' || g
FROM generate_series(1, 100000) AS g;
INSERT INTO readings (book_id)
SELECT book_id FROM books;
ANALYZE books;
ANALYZE readings;ANALYZE refreshes the table statistics the planner uses to estimate row counts. After bulk loads, run it before judging a plan. The next chapter shows how to read the EXPLAIN output for these queries.
To find indexes you never use, query the statistics view:
SELECT relname AS table_name,
indexrelname AS index_name,
idx_scan
FROM pg_stat_user_indexes
WHERE schemaname = 'public'
ORDER BY idx_scan, relname;An index with idx_scan = 0 after a representative period of use is a candidate for removal. Primary key and unique indexes can show zero scans and still be required, because they enforce constraints.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Assuming foreign keys create indexes | Slow author-to-books joins and slow cascading deletes | Index each referencing column you join or delete through |
| Putting columns in the wrong order | Index is ignored for queries on the second column | Put the column you filter on alone first, or add a separate index |
| Indexing low-selectivity columns such as `status` alone | Planner often chooses a sequential scan anyway | Use a partial index for the rare values |
| Wrapping an indexed column in a function | Index not usable | Index the expression, or rewrite the condition |
| Testing on a tiny table | Planner correctly skips the index | Load generated data and run `ANALYZE` |
| Indexing every column | Slower writes and wasted disk | Add indexes when a real query needs them |
Where full-text search fits
B-tree indexes cannot answer "which titles contain this word". That job belongs to a GIN index on a tsvector column, which a later chapter covers. The decision process is the same: look at the query, pick the index type that supports its operators, and check the plan.
Exercise
The primary key on bookauthors is (bookid, authorid). A teammate says the query "SELECT bookid FROM bookauthors WHERE authorid = 5" is already covered by the primary key index, so no extra index is needed. Is that right? What would you add, and what else benefits from it besides this query?
Show answer
No. A B-tree is sorted by bookid first, so a filter on authorid alone cannot use it efficiently. Add CREATE INDEX bookauthorsauthorididx ON bookauthors (authorid);. It also speeds the foreign-key check that runs when you delete an author under ON DELETE RESTRICT, and joins that start from an author and look up their books.
Exercise
You run SELECT * FROM readings ORDER BY finishedon DESC LIMIT 10; and the planner ignores your partial index readingsfinishedonidx (finished_on DESC) WHERE status = 'finished'. Why, and how do you fix the query?
Show answer
The query has no status = 'finished' condition, so PostgreSQL cannot prove every row it needs is in the partial index, which holds only finished rows. Add WHERE status = 'finished' to the query so it implies the index predicate.