SQL indexes: speed up queries with CREATE INDEX

An index does for a table what the index at the back of a textbook does for you: instead of flipping through every page, you look the term up and jump straight to the right place. This lesson covers when an index pays off, how to create one and why the order of its columns matters.

In short: CREATE INDEX idx_customers_city ON customers (city) builds a sorted directory of the city column. Queries with WHERE city = … can then find their rows without reading the whole table. CREATE UNIQUE INDEX also blocks duplicate values. An index never changes what your queries return, only how the database gets there.

What you should know first: filtering rows with WHERE and primary keys.

Try it now

After your statement, the exercise lists every column of the table and the position it holds in an index you created. Empty means there's no index on that column.

Task Customer service looks up a customer's orders on the phone all day long, always with WHERE customer_id = … on the orders table. Create an index on the customer_id column for that. You choose the name, for example idx_orders_customer. To check it, the exercise lists every column of orders and the position it holds in an index you created.

orders 18 rows, 5 columns
order_idcustomer_idorder_datestatusemployee_id
100112026-01-08delivered3
100242026-01-12delivered4
100332026-01-20delivered3
100472026-02-03delivered4
100522026-02-11cancelled8
100612026-02-25delivered3
1007102026-03-04delivered2
100852026-03-17delivered4
100982026-03-30delivered3
101062026-04-07delivered8
1011122026-04-22delivered4
101232026-05-06delivered3
101392026-05-19cancelled8
101472026-06-02shipped4
101512026-06-10shipped3
1016112026-06-12openNULL
101742026-06-13openNULL
1018102026-06-14openNULL

How an index works

Without an index, there's only one way for the database to find every customer in Boston: read each row and check the city. An index stores the values of a column in sorted order, each with a pointer back to its row. Just like the index in a book, the database looks up "Boston" and goes straight to the matching rows.

CREATE INDEX idx_customers_city ON customers (city);

SELECT name, segment
FROM customers
WHERE city = 'Boston';
namesegment
Harbor Fremont PartnersBusiness
Chloe EvansConsumer

The result is identical with or without the index. The difference only shows up in the query plan, which you get by putting EXPLAIN QUERY PLAN in front of the query. Without the index it says SCAN customers: the whole table. With the index it says SEARCH customers USING INDEX idx_customers_city (city=?): a targeted lookup. The next lesson shows you how to read these plans.

You never mention the index in your query. The database decides on its own whether it helps. You only need the name to remove the index later (DROP INDEX idx_customers_city). Names like idx_table_column are a good habit: months later you'll still know what it's for.

Unique indexes: UNIQUE stops duplicates

With CREATE UNIQUE INDEX, the index does more than speed up searches. It guards your data: each value may appear only once, so a second product with the same name is rejected. The table has to be clean when you create the index. If a value is already in there twice, the database refuses to build it. Empty values (NULL) don't count as duplicates in SQLite, so several rows without a value are fine.

Task The last import created the item "Lever arch file, gray" a second time: product_id 50, stock 0. Delete that duplicate row, then create a unique index on the name column of products so no name can appear twice again. To check it, the exercise tries to add the file once more (with INSERT OR IGNORE) and then lists every product.

products 13 rows, 5 columns
product_idnamecategorypricestock
1Copy paper, 500 sheetsPaper4.99420
2Blue ballpoint pens, 10-packWriting3.49310
3Lever arch file, grayFiling2.79185
4Comfort office chairFurniture18912
5Standing deskFurniture4495
6Black ink cartridgePrinter supplies24.964
7Yellow sticky notes, 12 padsWriting6.990
8Mono laser printer L30Electronics2198
927-inch monitorElectronics27915
10Notebook A5, ruledPaper5.49140
11Black toner XLPrinter supplies89.922
12Cross-cut shredderElectronics1290
50Lever arch file, grayFiling2.790

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

Multi-column indexes: order matters

An index can cover several columns. It's then sorted like a phone book: by last name first, and by first name where last names match. Looking up "Bradley, Tom" is quick. Finding everyone called Tom is not, because they're spread across the whole book.

CREATE INDEX idx_employees_department_salary
  ON employees (department, salary);

SELECT first_name, last_name, salary
FROM employees
WHERE department = 'Sales' AND salary > 48000;
first_namelast_namesalary
MarcusAllen49200
TomBradley62400

The plan shows (department=? AND salary>?), so both conditions use the index. Ask only for WHERE salary > 48000 and you're back to SCAN employees, because salary isn't the first column. That leads to the rule of thumb the SQLite and PostgreSQL docs both describe: columns you compare with = go first, and the column with a range (>, <, BETWEEN) comes after them. Columns to the right of a range condition no longer help the database jump to the right rows.

Task When customers call back, sales looks up a customer's orders from a given date on, always in the form WHERE customer_id = … AND order_date >= …. Create a single index on both columns, in the order that lets SQLite use both conditions. To check it, the exercise lists every column of orders and the position it holds in an index you created.

orders 18 rows, 5 columns
order_idcustomer_idorder_datestatusemployee_id
100112026-01-08delivered3
100242026-01-12delivered4
100332026-01-20delivered3
100472026-02-03delivered4
100522026-02-11cancelled8
100612026-02-25delivered3
1007102026-03-04delivered2
100852026-03-17delivered4
100982026-03-30delivered3
101062026-04-07delivered8
1011122026-04-22delivered4
101232026-05-06delivered3
101392026-05-19cancelled8
101472026-06-02shipped4
101512026-06-10shipped3
1016112026-06-12openNULL
101742026-06-13openNULL
1018102026-06-14openNULL

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

What an index costs

Indexes aren't free. Every INSERT, UPDATE and DELETE has to keep them up to date, and they take up storage. That's why the PostgreSQL documentation recommends removing indexes that are seldom or never used. In practice:

  • Index the columns you often search, join or sort on, such as foreign keys like customer_id.
  • Don't add an index for the primary key. It already has one.
  • On very small tables an index saves next to nothing. The database decides for itself whether to use it.

When an index can't help

The first common case is a function wrapped around the column. With WHERE strftime('%Y', order_date) = '2026', the database has to work out the year for every row, but an index on order_date only knows the dates themselves. Write WHERE order_date BETWEEN '2026-01-01' AND '2026-12-31' instead; the date functions lesson has more. The second is a LIKE pattern that starts with a wildcard. For name LIKE '%Ltd' the database would have to look inside every name, and a sorted list is no use for that. According to the SQLite docs, SQLite doesn't even try the index when the pattern begins with a wildcard.

Common mistakes

Leaving out the index name

CREATE INDEX ON orders (customer_id) doesn't work in SQLite. The exercise reports a syntax error near "ON". The name belongs between INDEX and ON.

A unique index on a column with duplicates

If a value already appears twice, the unique index fails. The exercise says: "This value already exists in products.name. The column allows each value only once (primary key or UNIQUE)." Clean up the data first, then create the index.

Using the same name twice

Each index name can exist only once in a SQLite database. On the second attempt the exercise tells you the name already exists and suggests another name or IF NOT EXISTS.

Columns in the wrong order

An index on (order_date, customer_id) is not the same as one on (customer_id, order_date). In the exercise you'll see it in the positions 1 and 2 of the check, and the message reads: "Columns and row count match, but not every value."

Indexes in MySQL, PostgreSQL, SQL Server and SQLite

CREATE INDEX name ON table (column) and CREATE UNIQUE INDEX look the same in all four. The differences are in the details:

TopicMySQLPostgreSQLSQL ServerSQLite
drop an indexDROP INDEX name ON tableDROP INDEX [IF EXISTS] nameDROP INDEX [IF EXISTS] name ON tableDROP INDEX [IF EXISTS] name
several NULLs in a unique indexallowedallowedone row with NULL at mostallowed
worth knowingCREATE INDEX is mapped to ALTER TABLEDROP INDEX CONCURRENTLY avoids a long lockCLUSTERED or NONCLUSTERED; nonclustered by default, one clustered index per table at mostmulti-column primary keys get their own index (sqlite_autoindex_…)

SQL Server has supported IF EXISTS on DROP INDEX since SQL Server 2016. A clustered index there holds the table's data itself, which is why a table can only have one.

Sources: MySQL Reference Manual (CREATE INDEX, DROP INDEX), PostgreSQL documentation (Indexes, Multicolumn Indexes, DROP INDEX), Microsoft Learn (CREATE INDEX, DROP INDEX), sqlite.org (CREATE INDEX, DROP INDEX, The SQLite Query Optimizer Overview).

FAQ

Does an index make every query faster?

No. It helps queries that search, join or sort on its first column. Queries that need every row anyway gain little, and writes get a bit slower.

What's the difference between a unique index and UNIQUE in CREATE TABLE?

Both block duplicate values, and in SQLite a UNIQUE constraint in CREATE TABLE is backed by an index too. The difference is that you can add or drop an index at any time without rebuilding the table.

Does an index help with LIKE 'Harbor%'?

Sometimes. SQLite has its own conditions for this; for example, the index has to match how LIKE treats upper and lower case (COLLATE NOCASE). EXPLAIN QUERY PLAN tells you whether it kicks in. With a wildcard at the start, it never helps.

Up next: EXPLAIN

The query plan tells you whether your index is actually being used. The next lesson shows you how to read SCAN and SEARCH and how to rewrite slow queries.

Practice EXPLAIN

Write to us

Choose language

Select your preferred language