Indexes

Updated · 11 min read
mediumPostgreSQL 18sqlindexescreate-indexexplainperformanceinterview

An index is a separate, sorted structure that lets the database find rows by a column's value without reading the whole table, like the index at the back of a book. To find "joins" in a 500-page book, you don't read every page; you look it up in the index, which says "page 214". Without an index, a query like WHERE studied_on = '2025-12-19' must read every row and check each one. This lesson builds a 200,000-row table, watches a lookup read all of it, then adds an index and watches the same lookup read a few hundred rows. It also covers what indexes cost, because they aren't free.

In One Minute

  • An index on a column lets WHERE, JOIN and ORDER BY on that column skip most of the table.
  • CREATE INDEX name ON table (column); creates one; DROP INDEX name; removes it.
  • Primary keys and UNIQUE constraints create indexes automatically.
  • EXPLAIN shows whether a query uses an index (Index Scan, Bitmap Index Scan) or reads everything (Seq Scan).
  • Every index slows down writes and uses disk space; add the ones your queries need, not one per column.

A Table Big Enough to Notice

The Fee Tracker's tables are tiny, so every query is instant. To see what an index does, each example below builds a study log with 200,000 rows, two years of sessions for the three students:

SQL
CREATE TABLE study_log (
  log_id     INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  student_id INTEGER NOT NULL,
  studied_on DATE NOT NULL,
  minutes    INTEGER NOT NULL
);
 
INSERT INTO study_log (student_id, studied_on, minutes)
SELECT 101 + (g % 3), DATE '2024-01-01' + (g % 730), 15 + (g % 90)
FROM generate_series(1, 200000) AS g;
 
ANALYZE study_log;

generate_series makes the numbers 1 to 200,000, and each becomes a row. ANALYZE updates the statistics the planner uses to choose a plan. In Try it, building the table takes a second or two.

Without an Index: Reading Everything

With no index on studied_on, finding one day's sessions means checking every row:

SQL▶ Try it
CREATE TABLE study_log (log_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, student_id INTEGER NOT NULL, studied_on DATE NOT NULL, minutes INTEGER NOT NULL);
INSERT INTO study_log (student_id, studied_on, minutes) SELECT 101 + (g % 3), DATE '2024-01-01' + (g % 730), 15 + (g % 90) FROM generate_series(1, 200000) AS g;
ANALYZE study_log;
 
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT count(*) FROM study_log WHERE studied_on = DATE '2025-12-19';
Output
CREATE TABLE
 
INSERT 0 200000
 
ANALYZE
 
                        QUERY PLAN
----------------------------------------------------------
 Aggregate (actual rows=1.00 loops=1)
   ->  Seq Scan on study_log (actual rows=273.00 loops=1)
         Filter: (studied_on = '2025-12-19'::date)
         Rows Removed by Filter: 199727
(4 rows)

EXPLAIN ANALYZE runs the query and reports what actually happened. Seq Scan is a sequential scan: read the whole table, front to back. It found 273 matching rows and removed 199,727 that didn't match. Every row was read to find 0.14% of them.

With an Index: Going Straight There

SQL
CREATE INDEX index_name ON table_name (column_name);

The same query after indexing studied_on:

SQL▶ Try it
CREATE TABLE study_log (log_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, student_id INTEGER NOT NULL, studied_on DATE NOT NULL, minutes INTEGER NOT NULL);
INSERT INTO study_log (student_id, studied_on, minutes) SELECT 101 + (g % 3), DATE '2024-01-01' + (g % 730), 15 + (g % 90) FROM generate_series(1, 200000) AS g;
 
CREATE INDEX study_log_studied_on_idx ON study_log (studied_on);
ANALYZE study_log;
 
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT count(*) FROM study_log WHERE studied_on = DATE '2025-12-19';
Output
CREATE TABLE
 
INSERT 0 200000
 
CREATE INDEX
 
ANALYZE
 
                                       QUERY PLAN
----------------------------------------------------------------------------------------
 Aggregate (actual rows=1.00 loops=1)
   ->  Bitmap Heap Scan on study_log (actual rows=273.00 loops=1)
         Recheck Cond: (studied_on = '2025-12-19'::date)
         Heap Blocks: exact=273
         ->  Bitmap Index Scan on study_log_studied_on_idx (actual rows=273.00 loops=1)
               Index Cond: (studied_on = '2025-12-19'::date)
               Index Searches: 1
(7 rows)

Now the plan starts with a Bitmap Index Scan on the new index, which finds exactly the 273 matching rows, and then reads only the parts of the table that hold them. No rows were read just to be thrown away. On a table of millions of rows, that's the difference between a query taking seconds and one taking milliseconds, and it grows with the table: the scan's work grows with the table's size, while the index lookup barely changes.

Without an index, all 200,000 rows are checked to find 273; with one, the index points straight at the 273

Indexes You Already Have

Every primary key and UNIQUE constraint creates an index automatically, to check for duplicates quickly. The Fee Tracker's indexes:

SQL▶ Try it
SELECT tablename, indexname, indexdef
FROM pg_indexes
WHERE schemaname = 'public'
ORDER BY tablename, indexname;
Output
  tablename  |     indexname      |                                            indexdef
-------------+--------------------+------------------------------------------------------------------------------------------------
 cities      | cities_pkey        | CREATE UNIQUE INDEX cities_pkey ON public.cities USING btree (city, state)
 courses     | courses_pkey       | CREATE UNIQUE INDEX courses_pkey ON public.courses USING btree (course_id)
 courses     | courses_title_key  | CREATE UNIQUE INDEX courses_title_key ON public.courses USING btree (title)
 enrollments | enrollments_pkey   | CREATE UNIQUE INDEX enrollments_pkey ON public.enrollments USING btree (student_id, course_id)
 payments    | payments_pkey      | CREATE UNIQUE INDEX payments_pkey ON public.payments USING btree (payment_id)
 students    | students_email_key | CREATE UNIQUE INDEX students_email_key ON public.students USING btree (email)
 students    | students_pkey      | CREATE UNIQUE INDEX students_pkey ON public.students USING btree (student_id)
(7 rows)

That's why WHERE student_id = 103 is already fast, and why foreign key columns are worth a second look: payments.student_id has no index of its own (the primary key index is on payment_id). PostgreSQL doesn't index foreign key columns automatically, so if you often look up or join payments by student, CREATE INDEX payments_student_id_idx ON payments (student_id); helps.

Kinds of Index

KindExampleHelps with
Single columnCREATE INDEX ... ON payments (paid_on)WHERE paid_on = ..., ranges, ORDER BY paid_on
Multi-columnCREATE INDEX ... ON payments (student_id, paid_on)WHERE student_id = 101 AND paid_on > ..., and student_id alone
UniqueCREATE UNIQUE INDEX ... ON students (email)Lookups, and refusing duplicates
ExpressionCREATE UNIQUE INDEX ... ON students (lower(email))WHERE lower(email) = ...; case-insensitive uniqueness

A multi-column index works like a phone book sorted by last name, then first name: it helps find a last name, or a last name with a first name, but not a first name alone. An expression index finally solves the case problem from UNIQUE and PRIMARY KEY: with a unique index on lower(email), 'SRIHITHA.ANAMANENI@EXAMPLE.COM' is refused as a duplicate of Srihitha's address.

A query can only use an index if it compares the indexed column directly. WHERE EXTRACT(YEAR FROM studied_on) = 2025 wraps the column in a function, so the index on studied_on can't help, and PostgreSQL scans everything. The half-open range WHERE studied_on >= '2025-01-01' AND studied_on < '2026-01-01' asks the same question and can use the index.

Sorted by student_id, then paid_on: easy to find student 101, or 101 in December; not December alone

What Indexes Cost

Every index makes inserts, updates and deletes slower, because the index must be updated too, and it takes disk space. The study log's index on studied_on:

SQL▶ Try it
CREATE TABLE study_log (log_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, student_id INTEGER NOT NULL, studied_on DATE NOT NULL, minutes INTEGER NOT NULL);
INSERT INTO study_log (student_id, studied_on, minutes) SELECT 101 + (g % 3), DATE '2024-01-01' + (g % 730), 15 + (g % 90) FROM generate_series(1, 200000) AS g;
CREATE INDEX study_log_studied_on_idx ON study_log (studied_on);
 
SELECT pg_size_pretty(pg_relation_size('study_log')) AS table_size,
       pg_size_pretty(pg_relation_size('study_log_studied_on_idx')) AS index_size;
Output
CREATE TABLE
 
INSERT 0 200000
 
CREATE INDEX
 
 table_size | index_size
------------+------------
 8656 kB    | 1480 kB
(1 row)

The index is about a sixth the size of the table, and each new session must now go into both. That's a good trade for a column you search by all the time, and a bad one for a column you never search by. Small tables don't need indexes at all: reading a few hundred rows is already instant, and PostgreSQL will often ignore an index on a tiny table anyway.

Each INSERT writes the table and every index; the index on studied_on adds about 1.4 MB to an 8.5 MB table
Add an index whenSkip it when
A big table is often filtered or joined on the columnThe table is small
The query returns a small fraction of the rowsThe query returns most of the table anyway
Reads matter more than write speedThe table is written constantly and rarely searched

DROP INDEX study_log_studied_on_idx; removes an index you don't need. SQL Server writes DROP INDEX name ON table, and MySQL DROP INDEX name ON table or ALTER TABLE t DROP INDEX name. Tabs showing each database's version are coming to this course. Reading EXPLAIN goes much deeper into EXPLAIN.

Common Mistakes

Indexing every column. Each index slows every write. Index what your queries filter and join on.

Wrapping the column in a function. WHERE lower(email) = ... can't use a plain index on email. Use an expression index, or compare the bare column.

Forgetting foreign key columns. PostgreSQL doesn't index them automatically. Index the ones you join or filter on.

Expecting an index on a tiny table to help. Scanning a few rows is already instant.

Interview Corner

What is an index, and how does it speed up queries?

A separate, sorted structure (usually a B-tree) mapping column values to row locations. The database can find matching rows by searching the index instead of scanning the whole table.

What are the downsides of indexes?

They slow inserts, updates and deletes, because every index must be maintained, and they use disk space. Unused indexes are pure cost.

Why might a query not use an index on its column?

The condition wraps the column in a function or cast, the query returns a large part of the table, the table is small, or the statistics suggest a scan is cheaper.

Practice

Challenge: Payments are often looked up by student. Create an index named payments_student_id_idx on payments (student_id), then list the indexes on payments from pg_indexes.

Show solution
SQL▶ Try it
CREATE INDEX payments_student_id_idx ON payments (student_id);
 
SELECT indexname, indexdef
FROM pg_indexes
WHERE tablename = 'payments'
ORDER BY indexname;
Output
CREATE INDEX
 
        indexname        |                                     indexdef
-------------------------+----------------------------------------------------------------------------------
 payments_pkey           | CREATE UNIQUE INDEX payments_pkey ON public.payments USING btree (payment_id)
 payments_student_id_idx | CREATE INDEX payments_student_id_idx ON public.payments USING btree (student_id)
(2 rows)

Two indexes: the primary key's, created automatically, and the new one. On a table this small it makes no measurable difference, but on a payments table with millions of rows, lookups and joins by student would use it.

Quick check: Indexes

3 questions
1EXPLAIN shows Seq Scan with Rows Removed by Filter: 199727 for a query that returns 273 rows. What does that suggest?
2Which indexes does PostgreSQL create automatically?
3Which condition can use an index on studied_on?

Key Takeaways

You want toWrite
Index a columnCREATE INDEX study_log_studied_on_idx ON study_log (studied_on);
Index two columnsCREATE INDEX ... ON payments (student_id, paid_on);
Case-insensitive uniquenessCREATE UNIQUE INDEX ... ON students (lower(email));
See if it's usedEXPLAIN ANALYZE SELECT ...
Remove itDROP INDEX study_log_studied_on_idx;

Was this tutorial helpful?

Lesson 60 of 115