An index helps the database find data faster, like a book's index helps you find a topic quickly.
How an index works (B-tree mental model) in SQL
CREATE INDEX index_name ON table_name (column_name);
name column of the customers table to speed up searches by customer 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);
This example creates a table of employees, inserts some data, then creates an index on the department column. The EXPLAIN QUERY PLAN shows how the database uses the index to find employees in the Sales department faster.
CREATE TABLE employees ( id INT PRIMARY KEY, name VARCHAR(50), 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';
A B-tree index works like a tree with branches and leaves, helping the database jump quickly to the right data instead of looking at every row.
Indexes speed up reads but can slow down writes because the index must be updated when data changes.
Not every query benefits from an index; sometimes a full table scan is faster for small tables.
An index is like a fast lookup guide for your data.
It uses a B-tree structure to quickly find values without scanning the whole table.
Creating indexes on columns you search often can make your queries much faster.