SQL Database Indexing
Definition
A database index is a data structure that improves the speed of data retrieval operations by creating a sorted reference to one or more columns of a table.
Introduction to SQL Database Indexing
Indexes are the single most impactful performance optimization in SQL. Without an index, the database must scan every row in a table (full table scan). With the right index, it can jump directly to matching rows in microseconds. Understanding when and how to create indexes separates junior from senior database engineers.
Syntax
-- Create a simple index CREATE INDEX idx_name ON table(column); -- Create a composite index CREATE INDEX idx_name ON table(col1, col2); -- Create a unique index CREATE UNIQUE INDEX idx_name ON table(column); -- Drop an index DROP INDEX idx_name;
Examples
Create Index on Frequently Queried Column
-- Without index: full table scan on 1M rows -- With index: direct lookup in milliseconds CREATE INDEX idx_employees_email ON employees(email); -- Now this query is instant: SELECT * FROM employees WHERE email = 'john@example.com';
Creates a B-tree index on the email column. Queries filtering by email now skip the full table scan.
Try in PlaygroundComposite Index for Multi-Column Filters
-- Optimizes queries that filter on both columns CREATE INDEX idx_emp_dept_salary ON employees(department, salary); -- This query uses the composite index efficiently: SELECT name FROM employees WHERE department = 'Engineering' AND salary > 80000;
Composite indexes work left-to-right. This index helps queries filtering on department alone, or department + salary, but NOT salary alone.
Try in PlaygroundCheck if Index is Being Used (EXPLAIN)
-- PostgreSQL EXPLAIN ANALYZE SELECT * FROM employees WHERE email = 'john@example.com'; -- MySQL EXPLAIN SELECT * FROM employees WHERE email = 'john@example.com';
EXPLAIN shows the query execution plan. Look for 'Index Scan' (good) vs 'Seq Scan' or 'Full Table Scan' (potentially slow).
Try in PlaygroundCommon Mistakes
Over-indexing — too many indexes slow down INSERT/UPDATE/DELETE operations (indexes must be maintained)
Wrong column order in composite indexes — the most selective column should come first
Indexing low-cardinality columns (e.g., boolean fields) — provides minimal benefit
Not indexing foreign key columns — JOIN performance suffers dramatically without FK indexes
Using functions on indexed columns in WHERE: WHERE UPPER(name) = 'JOHN' cannot use an index on name
Frequently Asked Questions
What is a database index and how does it work?
When should you NOT use an index?
What is a composite index in SQL?
What is a covering index?
Related SQL Topics
Practice This in the SQL Playground
Write real queries, see live results, and master SQL Database Indexing hands-on. 100% free.