SQL Indexes
What you will learn
- What an index is and what it costs
- How to create and drop an index
- How to see whether a query uses an index
- How a unique index doubles as a rule
This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). The indexes you create exist only in your browser's copy of the data; Reset data removes them. For EXPLAIN QUERY PLAN the cell shows only the plan text. Run the cells from top to bottom. (Database Fundamentals, chapter 7, covers indexes in depth; this is the practical start.)
1. What an index is
An index is a sorted list of the values of a column with a pointer to each row, like the index at the back of a book. With one, the database can jump to the matching rows instead of reading the whole table. It makes WHERE, JOIN and ORDER BY on that column faster and makes writes slightly slower, because the index must be updated too.
2. See the plan before the index
EXPLAIN QUERY PLAN in front of a query shows how the database will run it. SCAN means it reads every row. SEARCH ... USING INDEX means it jumps through an index:
EXPLAIN QUERY PLAN SELECT * FROM orders WHERE customer_id = 17;
plan
-----------
SCAN orders
(1 row)
EXPLAIN QUERY PLAN SELECT * FROM transactions WHERE account_id = 17;
plan
-----------------
SCAN transactions
(1 row)
EXPLAIN QUERY PLAN SELECT * FROM submissions WHERE student_id = 17;
plan
----------------
SCAN submissions
(1 row)
3. CREATE INDEX
CREATE INDEX name ON table (column) builds the index. A common name is idx_table_column:
CREATE INDEX idx_orders_customer ON orders (customer_id);
EXPLAIN QUERY PLAN SELECT * FROM orders WHERE customer_id = 17;
plan
-------------------------------------------------------------
SEARCH orders USING INDEX idx_orders_customer (customer_id=?)
(1 row)
CREATE INDEX idx_transactions_account ON transactions (account_id);
EXPLAIN QUERY PLAN SELECT * FROM transactions WHERE account_id = 17;
plan
-----------------------------------------------------------------------
SEARCH transactions USING INDEX idx_transactions_account (account_id=?)
(1 row)
CREATE INDEX idx_submissions_student ON submissions (student_id);
EXPLAIN QUERY PLAN SELECT * FROM submissions WHERE student_id = 17;
plan
---------------------------------------------------------------------
SEARCH submissions USING INDEX idx_submissions_student (student_id=?)
(1 row)
The plan changed from SCAN to SEARCH ... USING INDEX. The answer is the same; only the way of finding it changed. On a table of millions of rows the difference is large; on these small tables it is hard to feel, but the plan shows it.
4. Which columns to index
Good candidates are columns used to find or join rows:
- columns in
WHEREconditions that pick a few rows out of many; - foreign key columns (the "many" side of a join), as in the examples above;
- columns used in
ORDER BYon big tables.
An index on a column with few different values (a status with three values) rarely helps, because every lookup still matches a large part of the table. Do not index everything: each index uses space and slows writes.
5. UNIQUE indexes
CREATE UNIQUE INDEX also refuses duplicates, so it is a rule as well as a speed-up (Database Fundamentals, lesson 7.3):
CREATE TABLE lib_codes (code TEXT, label TEXT);
CREATE UNIQUE INDEX idx_codes_code ON lib_codes (code);
INSERT INTO lib_codes VALUES ('A1', 'first');
(1 row changed)
INSERT INTO lib_codes VALUES ('A1', 'second');
IntegrityError: UNIQUE constraint failed: lib_codes.code
CREATE TABLE lib_codes (code TEXT, label TEXT);
CREATE UNIQUE INDEX idx_codes_code ON lib_codes (code);
INSERT INTO lib_codes VALUES ('A1', 'first');
(1 row changed)
INSERT INTO lib_codes VALUES ('A1', 'second');
IntegrityError: UNIQUE constraint failed: lib_codes.code
CREATE TABLE lib_codes (code TEXT, label TEXT);
CREATE UNIQUE INDEX idx_codes_code ON lib_codes (code);
INSERT INTO lib_codes VALUES ('A1', 'first');
(1 row changed)
INSERT INTO lib_codes VALUES ('A1', 'second');
IntegrityError: UNIQUE constraint failed: lib_codes.code
6. Indexes on several columns
An index on two columns helps queries that fix the first column (or both). The order matters (Database Fundamentals, lesson 7.5):
CREATE INDEX idx_orders_city_status ON orders (ship_city, status);
EXPLAIN QUERY PLAN SELECT * FROM orders WHERE ship_city = 'Leeds' AND status = 'paid';
EXPLAIN QUERY PLAN SELECT * FROM orders WHERE status = 'paid';
plan
---------------------------------------------------------------------------
SEARCH orders USING INDEX idx_orders_city_status (ship_city=? AND status=?)
(1 row)
plan
-----------
SCAN orders
(1 row)
CREATE INDEX idx_accounts_type_status ON accounts (account_type, status);
EXPLAIN QUERY PLAN SELECT * FROM accounts WHERE account_type = 'savings' AND status = 'open';
EXPLAIN QUERY PLAN SELECT * FROM accounts WHERE status = 'open';
plan
----------------------------------------------------------------------------------
SEARCH accounts USING INDEX idx_accounts_type_status (account_type=? AND status=?)
(1 row)
plan
-------------
SCAN accounts
(1 row)
CREATE INDEX idx_sections_term_course ON sections (term, course_id);
EXPLAIN QUERY PLAN SELECT * FROM sections WHERE term = '2025-Spring' AND course_id = 1;
EXPLAIN QUERY PLAN SELECT * FROM sections WHERE course_id = 1;
plan
-----------------------------------------------------------------------------
SEARCH sections USING INDEX idx_sections_term_course (term=? AND course_id=?)
(1 row)
plan
-------------
SCAN sections
(1 row)
The query on the first column uses the index; the query on the second column alone does not.
7. DROP INDEX
An index you do not need only costs time and space. Remove it with DROP INDEX; the table and its rows are untouched:
DROP INDEX idx_orders_city_status;
SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'orders' ORDER BY name;
name
-------------------
idx_orders_customer
(1 row)
DROP INDEX idx_accounts_type_status;
SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'accounts' ORDER BY name;
name
----
(0 rows)
DROP INDEX idx_sections_term_course;
SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'sections' ORDER BY name;
name
----
(0 rows)
Worked example: should I index this column?
| Question | Answer for orders.customer_id |
|---|---|
Is it used in WHERE or JOIN? |
yes: "orders of a customer", joins to customers |
| Does a lookup pick a few rows out of many? | yes: a customer has few orders |
| Is the table big or will it grow? | yes |
| Is it written to very often? | moderately |
Index it, then check with EXPLAIN QUERY PLAN that the query uses it. For a column like status with three values, the answer to the second question is no. The columns are examples.
Common mistakes
- Indexing every column.
- Indexing a column with few different values.
- Expecting an index on the second column of a two-column index to help a query on that column alone.
- Never checking the plan.
- Forgetting that indexes slow down writes.
Key takeaways
- An index is a sorted list that lets the database jump to rows instead of scanning.
CREATE INDEX name ON table (column);DROP INDEX name.EXPLAIN QUERY PLANshowsSCANorSEARCH ... USING INDEX.- Index columns used to find or join rows;
UNIQUEindexes also enforce a rule. - Each index costs space and write time.
Practice
1. Which statement creates an index on customer_id of orders?
Show answer
CREATE INDEX idx_orders_customer ON orders (customer_id);
2. What does SCAN in a query plan mean?
Show answer
The database reads every row of the table.
3. Why does a UNIQUE index refuse a duplicate?
Show answer
It enforces that each value occurs only once, so a second row with the same value breaks the rule.
4. Why is an index on a three-value status column rarely useful?
Show answer
Each value still matches a large part of the table, so the database gains little from jumping.
5. What does DROP INDEX remove?
Show answer
Only the index; the table and its rows stay.
6. Which columns of a two-column index help a query?
Show answer
A query that fixes the first column (or both); a query on the second column alone does not use it.