Introduction
Indexes help databases find information faster, just like an index in a book helps you find a topic quickly.
CREATE INDEX index_name ON table_name (column_name);
CREATE INDEX idx_customer_name ON customers (name);
CREATE INDEX idx_order_date ON orders (order_date);
CREATE INDEX idx_product_category ON products (category, price);
CREATE TABLE employees ( id INT PRIMARY KEY, name VARCHAR(100), department VARCHAR(50) ); INSERT INTO employees (id, name, department) VALUES (1, 'Alice', 'Sales'), (2, 'Bob', 'HR'), (3, 'Charlie', 'Sales'), (4, 'Diana', 'IT'); CREATE INDEX idx_department ON employees (department); EXPLAIN QUERY PLAN SELECT * FROM employees WHERE department = 'Sales';
email in the users table?CREATE INDEX index_name ON table_name(column_name);.orders with 1 million rows and an index on customer_id, what is the expected result of this query?SELECT * FROM orders WHERE customer_id = 123;
customer_id helps the database quickly locate rows matching that value.username column, but your query is still slow:SELECT * FROM users WHERE username LIKE '%admin%';
sales with columns sale_id, product_id, and sale_date. You often run this query:SELECT * FROM sales WHERE product_id = 101 AND sale_date >= '2024-01-01';
product_id and a range on sale_date.Pass the test and this pattern moves unknown