Sub topic 13
Indexing for the queries you run
Assume you know SELECT, joins, and basic table design. This chapter also assumes PostgreSQL 12 or newer and the book-tracking tables from earlier chapters: books, authors, book_authors, and readings.
An index is a separate data structure that helps PostgreSQL find rows without checking every row in a table. An index can make a query faster, but it uses disk space and slows inserts, updates, and deletes because the index must also be maintained.
Indexes for relationships
Primary keys already have indexes. PostgreSQL does not automatically create an index on the referencing side of a foreign key. Add indexes for foreign-key columns that you use to find related rows.
CREATE INDEX IF NOT EXISTS book_authors_author_id_idx
ON book_authors (author_id);
CREATE INDEX IF NOT EXISTS readings_book_id_idx
ON readings (book_id);The first index supports queries such as “find every book by this author.” The second supports queries such as “find the reading entries for this book.”
| Index type | Useful for | Example |
|---|---|---|
| B-tree | Equality, ranges, and sorting | `WHERE author_id = 1` |
| GIN | Searching compound values such as `tsvector` | Full-text title search |
A B-tree is PostgreSQL’s default index type. It works well with comparisons such as =, <, >, and BETWEEN. It can also help with ORDER BY when the indexed column matches the ordering.
SELECT b.title
FROM books AS b
JOIN book_authors AS ba USING (book_id)
WHERE ba.author_id = 1
ORDER BY b.title;The index on book_authors.author_id narrows the join input. PostgreSQL may still choose a sequential scan, which reads the whole table, if the table is small or if most rows match. That choice can be correct.
Inspecting the plan
Use EXPLAIN to see the plan PostgreSQL intends to use. Add ANALYZE to run the query and show actual row counts and timings.
EXPLAIN (ANALYZE, BUFFERS)
SELECT b.title
FROM books AS b
JOIN book_authors AS ba USING (book_id)
WHERE ba.author_id = 1;Look for nodes such as Index Scan, Bitmap Index Scan, or Bitmap Heap Scan. Compare estimated rows with actual rows. A large difference can indicate stale statistics or data that does not match PostgreSQL’s assumptions.
Run ANALYZE after a large data load so the planner has current statistics:
ANALYZE books;
ANALYZE book_authors;
ANALYZE readings;Full-text search with a GIN index
A normal B-tree index is not designed to search words inside titles. PostgreSQL full-text search converts text into a tsvector, which represents searchable words. A GIN index then makes searches over that value efficient.
ALTER TABLE books
ADD COLUMN IF NOT EXISTS search tsvector
GENERATED ALWAYS AS (to_tsvector('english', title)) STORED;
CREATE INDEX IF NOT EXISTS books_search_idx
ON books USING gin (search);
SELECT title
FROM books
WHERE search @@ websearch_to_tsquery('english', 'example');The english configuration normalizes common word forms and ignores some stop words. Choose a configuration that matches the language of your data.
Common indexing errors
- Creating an index for every column wastes storage and increases write cost.
- Indexing a column that a query never filters, joins, or sorts rarely helps.
- Forgetting the foreign-key side can make relationship lookups slower.
- Judging a plan without
ANALYZEhides actual runtime behavior. - Testing only with a tiny table may hide problems that appear with production-sized data.
Exercise
Which index type should support a query using search @@ websearch_to_tsquery('english', 'mystery'), and why?
Show answer
Use a GIN index on the generated tsvector column. GIN indexes are designed for membership searches over compound values such as the tokens in full-text documents.