…
…
SQL and Database Fundamentals · Lesson 39 / 41 · Indexes and permissions
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
The student records system is growing: the enrollment table has 781 rows today and will reach hundreds of thousands within a few years. Two queries that run hundreds of times a day, "the student list of one section" and "the students of one department in a given year", already show signs of slowing down. You want to see why, and pick the right index for each.
So far in this unit you inserted rows, updated them, deleted them, protected changes with transactions and saved frequent queries as views. In all of that we assumed that the question was "is the result correct?". In this lesson the question changes: the result is correct, but how long does it take? The two queries in the case return in the blink of an eye today. Will they still do that when the table is a hundred times larger?
In this lesson you will:
enrollment (offering_id) for the section list, student (department_id, year) for the department and year search.EXPLAIN, and say when an index does not help.There are two ways to look for the word "normalization" in a thick book: read the book from the first page to the last, or look it up in the index at the back and go straight to the right page. A database faces the same choice in every query. To find the rows that match WHERE offering_id = 31, it has no other way, so it reads every row of the table one by one and keeps the ones that match. This is called a sequential scan.
You do not notice a sequential scan on 781 rows; the computer reads that many rows in a moment. But the same scan takes seconds on a few million rows, and if the query runs thousands of times a day, those seconds add up. An index is a separate structure that keeps the values of one or more columns in order and points each value to its row in the table. The default index type in PostgreSQL is the B-tree: it keeps the values in a sorted tree and finds a value among millions of rows in a few steps. A B-tree is used for equality (=), greater than and less than, BETWEEN and ORDER BY.
There is good news about indexes: some are already in place. When you defined the PRIMARY KEY and UNIQUE constraints in lesson 29, PostgreSQL automatically built a unique index for each of them, so that it can enforce those rules. When a new row is inserted, it answers "does this number already exist?" by looking at the index, not by scanning the whole table. You read the existing indexes from a system view called pg_indexes; you query it just like the views in lesson 38.
Example 1 (case): The indexes on enrollment and student
SELECT tablename, indexname FROM pg_indexes WHERE schemaname = 'public' AND tablename IN ('enrollment', 'student') ORDER BY tablename, indexname;
Output tablename | indexname
------------+----------------------------------------
enrollment | enrollment_pkey
enrollment | enrollment_student_id_offering_id_key
student | student_pkey
student | student_student_no_key
(4 rows)All four indexes come from constraints: names that end in _pkey belong to the primary key, and names that end in _key belong to a UNIQUE constraint. This is why searching by student_no is already fast. Now look at what is not in the list. enrollment.offering_id is a foreign key you created in lesson 30, and the section list query uses exactly this column. It has no index. A common misunderstanding is that a foreign key column is indexed automatically. PostgreSQL asks for an index on the column a foreign key points to (the primary key of the other table), but it does not put an index on the column that does the pointing. The case database has 13 indexes in all its tables, and none of them is on a foreign key column. Foreign keys that are often joined and filtered are therefore the first candidates for an index.
The cell below returns the indexes of the enrollment table with their full definitions. The indexdef column shows the command that built the index. Run it, then change the table name to course_offering: how many indexes are there, and do you see an index for term_id?
Try it now· not graded; doesn't affect progress
To speed up the section list, you build an index on the offering_id column. The command takes the name of the index, the table, and the columns in parentheses. The name is your choice; the form table_what_idx makes it easier to read. If you do not write a name, PostgreSQL makes one up.
Example 2 (case): An index for the section list
CREATE INDEX enrollment_offering_idx ON enrollment (offering_id); SELECT indexname FROM pg_indexes WHERE tablename = 'enrollment' ORDER BY indexname;
Output indexname
----------------------------------------
enrollment_offering_idx
enrollment_pkey
enrollment_student_id_offering_id_key
(3 rows)The table now has three indexes. Nothing happened to the rows; the index is a separate structure that sits next to the table. The queries did not change either: SELECT * FROM enrollment WHERE offering_id = 31 is written exactly as before, and the database itself decides whether to use the index.
A multi-column index. The second slow query uses two conditions: WHERE department_id = 4 AND year = 2. One index can cover more than one column: CREATE INDEX student_department_year_idx ON student (department_id, year);. Here the order of the columns matters. Think of a phone book: people are sorted by last name first, and people with the same last name are sorted by first name inside that group. You can find someone whose last name and first name you know right away, and also everyone whose last name you know, because they all stand next to each other. But to find everyone whose first name is "Elena" you have to read the book from start to finish, because the Elenas are spread under every last name. A multi-column index is used from the left in the same way: a (department_id, year) index directly helps searches for department_id = 4 and for department_id = 4 AND year = 2, but it does not help a search for year = 2 alone efficiently. In this last case PostgreSQL 18 can use the index by skipping through each value of the first column (a skip scan); this works when the first column has only a few distinct values, but it does not replace a direct search. The rule is simple: the column you search most often goes first in the index.
Which search does the index CREATE INDEX student_department_year_idx ON student (department_id, year); help the least?
The same rule shows an unnecessary index in the case. The enrollment table already has the index of the UNIQUE (student_id, offering_id) constraint, and its first column is student_id. So the search "all enrollments of one student" uses this index from the left; building a separate index on student_id would do the same job twice. The same index does not help a search by offering_id, because that column is second; this is why the section list needed its own index.
An expression index. In lesson 26 you saw that some email addresses were typed in uppercase or with leading spaces; this is why the login screen looks up an address with WHERE LOWER(email) = 'zara.silva@students.northbridge.example'. Even if you build an index on the email column, this search cannot use it: the index keeps the values of the column in order, not the results of LOWER(email). When the condition is on the result of a function, the index is built on that expression: CREATE INDEX student_email_lower_idx ON student (LOWER(email));. The rule: an index works when it is built on exactly the same expression as the one in WHERE. For the same reason, searches with an unknown start cannot use a B-tree either: WHERE last_name LIKE '%son' says "ending in son", but the index sorts last names from the start; to find last names that end in "son" you would read all the pages of the phone book as well. (Searches with a known start such as LIKE 'Lin%' can use an index with some settings.)
Now put together what you learned. For each query on the left, choose the index that helps it. When you decide, ask two questions: "Which columns or which expression is in the condition?" and "Is the first column of the index in the condition?"
Match each query with the index that speeds it up.
For each row, pick its match from the list, then check.
SELECT * FROM enrollment WHERE offering_id = 31SELECT * FROM student WHERE LOWER(email) = 'maya.chen@students.northbridge.example'WHERE department_id = 4 AND year = 2, and often just WHERE department_id = 4SELECT * FROM student WHERE last_name LIKE '%son'You built the index, but is it really used? You see this by writing EXPLAIN in front of the query. EXPLAIN does not run the query; it shows how the database plans to run it. The part that prepares this plan is called the planner.
In the plan lines you look for two things. Seq Scan on enrollment means a sequential scan: the whole table is read, and the condition is applied to each row in the Filter line. Index Scan or Bitmap Index Scan on <index name> says that an index is used and which one; this time the condition appears in the Index Cond line. In real output each line also ends with estimates in parentheses such as cost=... and rows=.... cost is not seconds; it is a relative score the planner uses to compare its options, and the numbers change from one environment to another. That is why we removed those parentheses in the outputs below. The node names (Seq Scan, Index Scan) do not change.
Example 3 (case): The plan before and after the index
Before the index is built:
EXPLAIN SELECT * FROM enrollment WHERE offering_id = 31;
OutputSeq Scan on enrollment
Filter: (offering_id = 31)After the index is built:
CREATE INDEX enrollment_offering_idx ON enrollment (offering_id); ANALYZE enrollment; EXPLAIN SELECT * FROM enrollment WHERE offering_id = 31;
OutputBitmap Heap Scan on enrollment
Recheck Cond: (offering_id = 31)
-> Bitmap Index Scan on enrollment_offering_idx
Index Cond: (offering_id = 31)In the first plan all 781 rows are read. In the second, the index enrollment_offering_idx first finds where the rows of section 31 are (Bitmap Index Scan), and then only those rows are fetched from the table (Bitmap Heap Scan); section 31 has 16 enrollments. A plan is read from the inside out: the indented line with -> runs first and passes its result to the line above it. The ANALYZE enrollment line in between is new: it updates the statistics of the table (how many rows there are and how the values are spread out), and the planner makes its decision from these statistics. Running ANALYZE after a big change is like giving the planner an up-to-date map.
But does the planner always use an index when there is one? The UNIQUE index on student_no has been there from the start. Look at that one too:
Example 4 (case): An index exists, but the plan is still a scan
ANALYZE student; EXPLAIN SELECT * FROM student WHERE student_no = '202601001';
OutputSeq Scan on student
Filter: ((student_no)::text = '202601001'::text)There is an index on student_no, but the plan in Example 4 is a Seq Scan. Why?
This corrects the most important misunderstanding in the lesson: having an index does not mean it will be used. Each time, the planner asks "which path is cheapest?". On a small table the answer is often a scan, and so it is for a search that returns many rows. In terms of the book: you do not look at the index of a four-page leaflet, you just read it. If you want to see how long a query really takes, EXPLAIN ANALYZE runs the query and also prints the times; we do not use it in this lesson because the times change from computer to computer.
If an index speeds things up, why don't we put one on every column? Because it is not free. Go back to the book: when a new page is added to the book, the index has to be updated too. In a table, every INSERT, UPDATE and DELETE updates not only the table but all of its indexes; a row added to a table with eight indexes is written in nine places. Every index also takes up space on disk. You slow down writing to speed up reading, and the trade is worth it only when reads are really frequent.
Good candidates are columns that are often used in WHERE, JOIN and ORDER BY and that hold many distinct values. Columns with few distinct values are usually not good candidates:
In the student table, 28 students have a scholarship and 92 do not. Is an index on the has_scholarship column useful?
An index that is not used, or that does the same job as another index, is removed with DROP INDEX index_name;. You cannot remove the index of a constraint this way: the command DROP INDEX course_code_key; gives the error cannot drop index course_code_key because constraint course_code_key on table course requires it, because the UNIQUE constraint relies on that index to enforce the rule.
One kind of index both speeds up searches and enforces a rule: CREATE UNIQUE INDEX. In lesson 29 you saw that a UNIQUE constraint treats a difference in uppercase and lowercase and a leading space as different values. CREATE UNIQUE INDEX student_email_unique ON student (LOWER(TRIM(email))); compares the addresses in their cleaned form; the same address cannot be entered with two different spellings. A unique index, like a constraint, has to fit the existing data: because some students in the case share a last name, CREATE UNIQUE INDEX student_last_name_idx ON student (last_name); is rejected with the error could not create unique index "student_last_name_idx". If you want to speed up searches by last name, you build a normal index.
An index decision is made by measuring, not by guessing. Put the steps in order:
Put in order the steps you follow when a query gets slow.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
The tables in the case are small, so the effect of an index stayed limited. To see the difference you need a big table. Let's build the orders table of an online store with 50,000 rows. The generate_series in the setup line produces the numbers from 1 to 50,000; it is not the topic of this lesson, so accept it as a ready-made setup. In the end each of 1,000 customers has 50 orders.
Example 5 (outside the case): An orders table with 50,000 rows
CREATE TABLE orders AS SELECT g AS id, g % 1000 AS customer_id, g % 500 + 1 AS amount, DATE '2026-01-01' + g % 365 AS order_date FROM generate_series(1, 50000) AS g; ANALYZE orders; EXPLAIN SELECT * FROM orders WHERE customer_id = 42;
OutputSeq Scan on orders
Filter: (customer_id = 42)Without an index, all 50,000 rows are read to find 50 rows. If you add CREATE INDEX orders_customer_idx ON orders (customer_id); and run ANALYZE, the same EXPLAIN gives this:
OutputBitmap Heap Scan on orders
Recheck Cond: (customer_id = 42)
-> Bitmap Index Scan on orders_customer_idx
Index Cond: (customer_id = 42)This time the planner chose the index, because only 50 rows out of 50,000 are wanted. As you will see in your own environment, the cost estimate in parentheses falls to a small fraction of the one in the scan plan. In the cell below, the indexed version is ready. Run it, then try two tasks:
1. Delete the CREATE INDEX line and run it again. What did the plan turn back into?
2. Put the line back and change the condition to amount = 42. Does the index help this query? Why?
Try it now· not graded; doesn't affect progress
In the second task the plan becomes a Seq Scan again: the index is built on customer_id, but the condition is on amount. An index helps only a condition that uses the column (or the expression) it was built on. Back to the case: on the 781-row enrollment table today, enrollment_offering_idx is a small gain, but when the table reaches hundreds of thousands of rows it will be the structure that saves the section list from a scan. Building the index before the table grows, knowing the query pattern, is a good habit for this reason.
You can count the indexes per table on pg_indexes with the grouping you learned in lesson 12.
SELECT tablename, COUNT(*) AS indexes FROM pg_indexes WHERE schemaname = 'public' GROUP BY tablename ORDER BY tablename;
Output tablename | indexes
-----------------+---------
course | 2
course_offering | 1
department | 2
enrollment | 2
instructor | 2
student | 2
term | 2
(7 rows)There are 13 indexes in total; all of them come from primary key or UNIQUE constraints. The course_offering table has only its primary key index: none of its three foreign keys (course_id, term_id, instructor_id) is indexed.
CREATE UNIQUE INDEX student_email_unique ON student (LOWER(TRIM(email))); SELECT indexname FROM pg_indexes tablename = indexname;
Putting an index on every column because "the system is slow". Unnecessary indexes slow down every INSERT, UPDATE and DELETE, take up disk space, and most of them are never used: on small tables and on columns with few values such as has_scholarship the planner still chooses a scan, and on a column like student_id, which is already the first column of an index, a new index does the same job a second time. First use EXPLAIN to see that the query really does a sequential scan, then build an index only on the columns that are often used in conditions and joins, in the order and with the expression used in the condition; after you build it, check that the plan has changed.
CREATE INDEX name ON table (columns)); PRIMARY KEY and UNIQUE build their own index, a foreign key column is not indexed automatically, and the existing indexes appear in pg_indexes.LOWER(email)) needs an expression index, and a LIKE '%son' search with an unknown start cannot use a B-tree.EXPLAIN shows the plan (Seq Scan is a scan, Index Scan or Bitmap Index Scan is an index); the planner chooses a scan on a small table on purpose, and every index adds a cost to writes and to disk space.Next lesson: with roles and privileges you will decide who can see and change what in the database, and you will see how queries built by joining text can be attacked.
Exercises and quiz are for members
This lesson has 6 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
Output indexname
--------------------------
student_email_unique
student_pkey
student_student_no_key
(3 rows)The index was built, because no two addresses are the same even in their cleaned form; the 9 students with an empty email are not an obstacle either, because NULL values are not counted as equal to each other. From now on, a copy of an existing address typed in uppercase or with a leading space is rejected too. The same command does not work for last_name: because some students share a last name, you get a could not create unique index error.