An index lets the database find rows without reading the whole table, much as a book’s index takes you to a page without reading every page before it. Queries never mention an index; the database decides for itself when one helps.
CREATE INDEX index_nameON table_name (column1, column2);The examples use the Invoices and Suppliers tables from the example database.
Indexing a column you search on
Section titled “Indexing a column you search on”Looking up invoices by supplier is a common query. Without an index, the database reads every invoice to find the matching ones. With one, it goes straight to them:
CREATE INDEX IX_Invoices_SupplierON Invoices (Supplier);Nothing about the query changes:
SELECT InvoiceID, AmountFROM InvoicesWHERE Supplier = 'Kestrel Catering';Before the index, SQLite’s query plan for this reads SCAN Invoices, every row; afterwards it reads SEARCH Invoices USING INDEX IX_Invoices_Supplier. With four invoices the difference is invisible, but with four million it is the difference between an instant answer and a long wait.
Several columns
Section titled “Several columns”An index can cover more than one column, in a set order. One on production and then date suits queries that pick a production and a date range:
CREATE INDEX IX_Invoices_Production_DateON Invoices (ProductionID, InvoiceDate);Like a phone book sorted by surname and then first name, it helps when the search starts with the first column. It cannot jump straight to rows by InvoiceDate alone, because the dates are only in order within each production.
Unique indexes
Section titled “Unique indexes”CREATE UNIQUE INDEX speeds up searches and also refuses duplicates, much like a UNIQUE constraint:
CREATE UNIQUE INDEX UX_Suppliers_NameON Suppliers (Name);Adding a second supplier called Kestrel Catering is now refused.
The cost
Section titled “The cost”Every index has to be kept up to date. Each insert, update and delete changes the index as well as the table, and the index takes up storage. Index the columns that queries search, join or sort on often, and leave the rest alone.
A primary key is indexed automatically, and so is a UNIQUE constraint, so neither needs one of its own. Foreign key columns often benefit from an index, because joins run on them.
Removing an index
Section titled “Removing an index”| Database | Statement |
|---|---|
| PostgreSQL, Oracle, SQLite | DROP INDEX IX_Invoices_Supplier; |
| SQL Server, Access | DROP INDEX IX_Invoices_Supplier ON Invoices; |
| MySQL | ALTER TABLE Invoices DROP INDEX IX_Invoices_Supplier; |