Introduction
Indexes help the database find data faster, like a shortcut in a book's table of contents.
CREATE INDEX index_name ON table_name (column1, column2, ...);
CREATE INDEX idx_lastname ON employees (last_name);
CREATE INDEX idx_name_dob ON employees (last_name, date_of_birth);
CREATE UNIQUE INDEX idx_email ON users (email);
CREATE TABLE employees ( id INT PRIMARY KEY, first_name VARCHAR(50), last_name VARCHAR(50), department VARCHAR(50) ); CREATE INDEX idx_department ON employees (department); INSERT INTO employees (id, first_name, last_name, department) VALUES (1, 'Alice', 'Smith', 'Sales'), (2, 'Bob', 'Brown', 'HR'), (3, 'Carol', 'Davis', 'Sales'); EXPLAIN SELECT * FROM employees WHERE department = 'Sales';
email in a table users?orders with an index on customer_id, what will happen when you run this query?SELECT * FROM orders WHERE customer_id = 123;
last_name but your query SELECT * FROM employees WHERE first_name = 'John'; is slow. What is the likely problem?products with columns category, price, and stock. You often run this query:SELECT * FROM products WHERE category = 'Books' AND price < 20;Which index strategy is best to speed up this query?
Pass the test and this pattern moves unknown