Indexes
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,JOINandORDER BYon that column skip most of the table. CREATE INDEX name ON table (column);creates one;DROP INDEX name;removes it.- Primary keys and
UNIQUEconstraints create indexes automatically. EXPLAINshows 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:
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:
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';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
CREATE INDEX index_name ON table_name (column_name);The same query after indexing studied_on:
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';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.
Indexes You Already Have
Every primary key and UNIQUE constraint creates an index automatically, to check for duplicates quickly. The Fee Tracker's indexes:
SELECT tablename, indexname, indexdef
FROM pg_indexes
WHERE schemaname = 'public'
ORDER BY tablename, indexname; 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
| Kind | Example | Helps with |
|---|---|---|
| Single column | CREATE INDEX ... ON payments (paid_on) | WHERE paid_on = ..., ranges, ORDER BY paid_on |
| Multi-column | CREATE INDEX ... ON payments (student_id, paid_on) | WHERE student_id = 101 AND paid_on > ..., and student_id alone |
| Unique | CREATE UNIQUE INDEX ... ON students (email) | Lookups, and refusing duplicates |
| Expression | CREATE 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.
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:
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;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.
| Add an index when | Skip it when |
|---|---|
| A big table is often filtered or joined on the column | The table is small |
| The query returns a small fraction of the rows | The query returns most of the table anyway |
| Reads matter more than write speed | The 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
CREATE INDEX payments_student_id_idx ON payments (student_id);
SELECT indexname, indexdef
FROM pg_indexes
WHERE tablename = 'payments'
ORDER BY indexname;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.
Key Takeaways
| You want to | Write |
|---|---|
| Index a column | CREATE INDEX study_log_studied_on_idx ON study_log (studied_on); |
| Index two columns | CREATE INDEX ... ON payments (student_id, paid_on); |
| Case-insensitive uniqueness | CREATE UNIQUE INDEX ... ON students (lower(email)); |
| See if it's used | EXPLAIN ANALYZE SELECT ... |
| Remove it | DROP INDEX study_log_studied_on_idx; |
Was this tutorial helpful?