wasAsked.

How does indexing improve query performance?

Capgemini · Full Stack Developer · technical

Published

Year not specified · SQL

Community answers

Posted by wasAsked editorial collection

An index is a separate data structure (usually a B-tree) that keeps column values sorted with pointers to the rows. It lets the database find rows without reading the whole table. Without an index SELECT * FROM Orders WHERE CustomerId = 42; The database performs a full table scan: it reads every row (or every page) and checks the condition. On millions of rows, this is slow and uses lots of I/O. With an index on CustomerId The database performs an index seek: it navigates the B-tree from the root to the leaf in a few steps (logarithmic time), finds the matching entries and reads only those rows. Reading 5 rows instead of 5 million makes the query orders of magnitude faster. How indexes help different operations - Equality and range filters: WHERE Email = ?, WHERE OrderDate BETWEEN ? AND ?. - Joins: indexes on foreign keys speed up JOIN conditions. - Sorting: ORDER BY on indexed columns can avoid a separate sort step. - Grouping and aggregates: MIN and MAX can read one end of the index; GROUP BY can use ordered data. - Uniqueness: unique indexes enforce constraints efficiently. Covering indexes If an index contains every column the query needs (key columns plus INCLUDE columns in SQL Server), the database reads only the index and never touches the table: CREATE INDEX IX_Orders_Customer_Date ON Orders (CustomerId, OrderDate DESC) INCLUDE (Total); SELECT OrderDate, Total FROM Orders WHERE CustomerId = 42 ORDER BY OrderDate DESC; Composite index column order matters An index on (CustomerId, OrderDate) helps WHERE CustomerId = ? and WHERE CustomerId = ? AND OrderDate > ?, but not WHERE OrderDate > ? alone (the leftmost-prefix rule). When indexes do not help - Low selectivity columns (a Status column with two values) — scanning may be cheaper. - Functions on indexed columns (WHERE YEAR(OrderDate) = 2026 or LOWER(Email) = ...) prevent normal index use; rewrite as ranges or use computed or functional indexes. - Leading wildcards (LIKE '%term'). - Implicit type conversions between parameters and columns. Costs - Every index must be updated on INSERT, UPDATE and DELETE, so writes become slower. - Extra storage and memory. - Too many overlapping indexes waste resources. Approach: index based on real query patterns, verify with execution plans, keep statistics up to date, and remove unused indexes.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics