CREATE INDEX

The SQL CREATE INDEX Statement

An index is a separate data structure that lets the database find rows quickly without reading the whole table, like the index at the back of a book.

CREATE INDEX index_name
ON table_name (column1, column2, ...);

-- duplicate values are not allowed
CREATE UNIQUE INDEX index_name
ON table_name (column1, ...);

See the Difference

EXPLAIN QUERY PLAN (SQLite) shows how a query will run. Before the index, the database must SCAN the whole table:

Without index

Without an index, the plan shows a full SCAN of the table:

EXPLAIN QUERY PLAN
SELECT * FROM Customers WHERE Country = 'India';

Result: 1 row

idparentnotuseddetail
20216SCAN Customers

With index

After the index, it can SEARCH directly:

CREATE INDEX idx_customers_country ON Customers (Country);

EXPLAIN QUERY PLAN
SELECT * FROM Customers WHERE Country = 'India';

Result: 1 row

idparentnotuseddetail
3062SEARCH Customers USING INDEX idx_customers_country (Country=?)

DROP INDEX

-- SQLite, PostgreSQL, Oracle
DROP INDEX idx_customers_country;
-- MySQL
ALTER TABLE Customers DROP INDEX idx_customers_country;
-- SQL Server
DROP INDEX Customers.idx_customers_country;