An index in SQL is a performance-optimization feature that allows the database to find rows faster, without scanning the entire table. It works like an index in a book — instead of flipping through every page, you can jump directly to the page number listed in the index.
Indexes are created on one or more columns of a table and store a sorted representation of the column values, along with pointers to the actual data rows.
Why are indexes used?
SELECT queries, especially when using WHERE, JOIN, ORDER BY, and GROUP BY clausesPRIMARY KEY or UNIQUE constraints)However, indexes come with trade-offs: they consume extra storage and slightly slow down INSERT, UPDATE, and DELETE operations because the index must be updated as well.
CREATE INDEX idx_name
ON customers (last_name);This creates an index on the last_name column of the customers table.
CREATE UNIQUE INDEX idx_email
ON users (email);This ensures that each email in the users table is unique.
CREATE INDEX idx_name_city
ON customers (last_name, city);Creates an index using both last_name and city.
DROP INDEX idx_email;Removes the index named idx_email.
WHERE, JOIN, and ORDER BY clausesidx_table_column)EXPLAIN to understand index usageAsk the AI if you need help understanding or want to dive deeper in any topic