Sub topic 2
What an Index Is and What It Trades
Assume you know basic SQL, including SELECT, WHERE, ORDER BY, and JOIN. You should also know that a table contains rows and columns, and that a primary key identifies a row.
An index is a separate data structure that helps a database find rows without examining every row in a table. It stores selected column values in an organized form, together with a way to locate the matching table rows.
The problem: scanning every row
Without a useful index, the database can perform a sequential scan. It reads each row and tests the WHERE condition.
For a table with 100 rows, this is usually cheap. For a table with 100 million rows, checking every row can require substantial disk reads and CPU time, even when only one row matches.
An index changes the search strategy. The database searches the smaller index first, finds references to matching rows, and then reads those rows from the table.
Creating a basic index
This PostgreSQL example creates an index on customer_id:
CREATE TABLE orders (
id bigint PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL,
created_at timestamptz NOT NULL,
total_cents integer NOT NULL
);
CREATE INDEX orders_customer_id_idx
ON orders (customer_id);
SELECT *
FROM orders
WHERE customer_id = 42;The index does not change the query's result. It gives the query planner another possible way to produce that result. The planner compares estimated costs and may choose the index, a sequential scan, or another plan.
An index is most useful when it lets the database discard many rows. An index on a column containing only two values, such as is_active, may be less useful for a query that asks for all active rows. The planner may decide that reading most of the table directly is cheaper.
What an index costs
Indexes improve some reads, but they are not free.
| Benefit or cost | Effect |
|---|---|
| Faster selective reads | Finds a small matching set without scanning the whole table |
| Faster ordering | May provide rows in index order |
| Extra storage | Stores another copy of indexed values and row references |
| Slower writes | Inserts, updates, and deletes must maintain the index |
| More maintenance | Statistics and index space may need ongoing care |
If an indexed column changes, the database may need to update the index entry. A table with many indexes can therefore have slower write operations. Extra indexes also increase backup size and memory pressure.
A primary key often creates a unique index automatically, depending on the database system. A separate ordinary index is appropriate when queries frequently filter, join, or sort by another column.
Exercise
A query returns 90 percent of a large table. Will an index on its filter column always make the query faster?
Show answer
No. Reading most rows through the index can require many table lookups. The planner may choose a sequential scan because it is cheaper.