Indexes & Performance — SQL

An index is a sorted list for one column, which the database uses to go straight to the rows you want. Without an index, to find the orders with customer_id…

When your online shop first opened, the orders table held 4 rows, and every query came back right away. A year later it holds 100,000. The exact same query, for example one that finds a customer's orders, starts to feel slow, even though the result is still only 2 orders.

What helps here is an index: an extra list that the database makes for one column. With that list, the database can go straight to the rows you want, without reading the whole table. It works like the index at the back of a cookbook. You want "beef curry", so you open the index, find "beef curry, page 112", and go straight to page 112. Without that index, you would turn the pages from page one until you found it. In the database, the book is the table, each page is a row, and the cookbook's index is the database's index.

The table we use

The orders table in the exercise holds 4 orders. The customer_id column holds the number of the customer who placed the order. Budi is customer_id 1, Siti is 2 and Andi is 3:

id customer_id product amount
1 1 Laptop 1200
2 2 Mouse 15
3 2 Keyboard 50
4 3 Monitor 350

Your shop runs this query all the time: "show every order of customer 2".

SELECT * FROM orders WHERE customer_id = 2;

The result is 2 rows: Mouse and Keyboard.

Without an index, every row is read

Guess first: the table holds 100,000 rows and has no index yet. How many rows does the database read to find the two orders of customer 2? 2, about 50,000, or 100,000?

The answer is all 100,000, even though the result is only 2. The database has no record of where customer 2's rows are. So it reads rows 1, 2, 3 and so on, and checks the customer_id of each row. This is called a full table scan (reading the whole table). On a 4-row table, this still feels fast.

You can ask the database to show its plan for a query: the way the database will run that query. The command word is EXPLAIN. In SQLite, the database this exercise uses, write EXPLAIN QUERY PLAN in front of the query. You get a plan that is easy to read:

EXPLAIN QUERY PLAN
SELECT * FROM orders WHERE customer_id = 2;
SCAN orders

SCAN orders means "read the whole orders table from start to end", so a full table scan. The query itself doesn't run: you only get the plan.

Make an index with CREATE INDEX

The command below makes an index for the customer_id column:

CREATE INDEX idx_orders_customer ON orders(customer_id);

This index keeps every customer_id value sorted. Each value points to its rows: 1 to row 1, 2 to rows 2 and 3 (Mouse and Keyboard), 3 to row 4. Because the values are sorted, the database finds the number 2 quickly, like looking up a word in a dictionary without reading from page one.

After you make the index, run the same EXPLAIN QUERY PLAN again:

SEARCH orders USING INDEX idx_orders_customer (customer_id=?)

SEARCH ... USING INDEX means the database no longer reads the whole table; it searches through the index idx_orders_customer. (customer_id=?) names the column being searched, and ? stands for its value (here 2). The SELECT doesn't change at all: the database itself chooses when to use the index.

In the Lab, with 100,000 rows in real SQLite, the same query takes about 4 ms (milliseconds) without the index and about 0.1 ms with it. The exact numbers depend on your device, but with the index the query is tens of times faster.

The price of an index

An index speeds up reads: SELECT with WHERE, JOIN, and ORDER BY. But an index is a copy of one column, and that copy must always be kept up to date. Every INSERT, UPDATE or DELETE on orders also changes idx_orders_customer. So an index makes writes a little slower; writes are the commands that add, change or delete rows. An index also takes storage space. If a table has 3 indexes, one INSERT writes to 4 places: the table, plus its 3 indexes.

When to make an index

Index it No need
A column often in WHERE, like email for login A column that is almost never searched
A column used in a JOIN, like customer_id A small table, say a settings table with 10 rows
A column often used in ORDER BY A table written far more often than it's read, like a log (a record of events)

A PRIMARY KEY column such as id is already fast to look up, so it needs no extra index. A UNIQUE column also gets an index automatically.

📌 EXPLAIN in MySQL and PostgreSQL

In MySQL and PostgreSQL you only write EXPLAIN in front of the query: EXPLAIN SELECT * FROM users WHERE email = '[email protected]';. The output looks different. MySQL shows a table with columns like type and rows. PostgreSQL writes Seq Scan (read every row) or Index Scan (search through an index). SQLite also has EXPLAIN without QUERY PLAN, but its output is a list of machine instructions that is hard to read. In all three databases, a regular index is a B-tree, a structure that branches like a tree and keeps its contents sorted. PostgreSQL also has other kinds of index, for example GIN, for searching inside text or JSON (a data format). But a B-tree covers almost every need.

⚠️ An index on the wrong column, with the wrong name, or on everything

TL;DR: An index is a sorted list for one column, which the database uses to go straight to the rows you want. Without an index, to find the orders with customer_id 2, the database reads every row (SCAN), even when the result is 2 rows out of 100,000. CREATE INDEX idx_orders_customer ON orders(customer_id); makes an index for the customer_id column of the orders table. The plan of this search (the way the database runs the query) then becomes SEARCH orders USING INDEX, which means searching through the index. You see the plan with EXPLAIN QUERY PLAN in SQLite, or EXPLAIN in MySQL and PostgreSQL. An index speeds up reads (SELECT) but slows writes (INSERT, UPDATE, DELETE) a little, because the index is updated too. So put an index on columns often found in WHERE, JOIN and ORDER BY, not on every column.

⚡ Without an index, everything is read

Guess first: the orders table holds 100,000 rows and has no index yet (an extra list that helps find rows). How many rows does the database read to find the two orders with customer_id 2?

All 100,000. The database has no record of where those rows are, so it reads the rows one by one. This is called a full table scan.

Meaning: EXPLAIN QUERY PLAN in front of a query shows the plan for that query: the way the database will run it. When the query looks for customer_id 2, the plan is SCAN orders, which means read the whole orders table.

⚡ Make an index

Write:

CREATE INDEX idx_orders_customer ON orders(customer_id);

Meaning: This command makes an index for the customer_id column of the orders table. The index keeps the customer_id values sorted, and each value points to its rows. The plan becomes SEARCH orders USING INDEX: the database searches through the index and no longer reads the whole table.

The exercise checks for an index named exactly idx_orders_customer.

⚡ The query doesn't change

Write:

SELECT * FROM orders WHERE customer_id = 2;

Meaning: The query for the orders with customer_id 2 doesn't need to change. The database itself chooses when to use the index. The result is still 2 orders: Mouse and Keyboard.

⚡ The price of an index

Meaning: An index speeds up reads (SELECT). But every write (INSERT, UPDATE, DELETE) has to update the index too, so writes get a little slower. Put an index on columns often found in WHERE, JOIN and ORDER BY, not on every column.

What you will learn