Domdhi logoDOMDHI.OS
BACK_TO_COURSE

What You Need to Know to Judge SQL

Indexes and Why a Query Is Slow

Slow Means Reading Too Much

SQL Server stores data in 8 KB pages. A slow query is almost always one that reads far more pages than its answer needs. An index is a sorted copy of some columns, like the index in the back of a book: jump to the right spot instead of reading every page.

Same query, three ways, on a 500,000-row Orders table:

SELECT OrderId, OrderDate, Status
FROM dbo.Orders
WHERE CustomerId = 42;   -- returns 52 rows
Index on Orders Pages read
None on CustomerId (reads the whole table) 8,442
(CustomerId) 171
(CustomerId, OrderDate) INCLUDE (Status) 3

The second one finds the 52 orders fast, then goes back to the table for each one to fetch the missing columns. That's a key lookup. The third holds everything the query asked for, so it never goes back. That's a covering index:

CREATE INDEX IX_Orders_CustomerId_OrderDate
ON dbo.Orders (CustomerId, OrderDate)
INCLUDE (Status);

Column order matters. A phone book sorted by last name, then first name, is useless for finding everybody named Dom. This index helps when you filter by CustomerId. It can't jump to anything if all you have is OrderDate.

Having an Index Isn't Enough

You can write a query so the index can't be used properly. Wrap the column in a function and SQL Server has to compute it for every row. With an index on OrderDate, counting March 2025:

-- Reads the entire index: 994 pages
SELECT COUNT(*) FROM dbo.Orders
WHERE YEAR(OrderDate) = 2025 AND MONTH(OrderDate) = 3;

-- Jumps to March: 25 pages
SELECT COUNT(*) FROM dbo.Orders
WHERE OrderDate >= '20250301' AND OrderDate < '20250401';

Same answer, 10,602. The rule: leave the column bare on its side of the comparison. Three things break it:

Slow Why
YEAR(OrderDate) = 2025 function wrapped around the column
Email LIKE '%@example.com' starts with a wildcard, so there's no starting point
Email = N'...' when Email is varchar type mismatch, so the column can get converted row by row

That last one is sneaky. Looking up one email out of 10,000 read 2 pages with '...' and 49 with N'...'. One letter. That's with the SQL_Latin1_General_CP1_CI_AS collation. The same test with a Windows collation (Latin1_General_CI_AS) still jumped straight to the row, 2 pages either way. So check your column's collation, and match the types regardless.

INFO

Indexes aren't free. Every insert, delete and change to an indexed column has to update them too. More isn't better. The right few is better.

QUIZ

Which filter lets an index on OrderDate jump straight to March 2025?

Sign in to track lesson progress and earn a certificate.SIGN IN TO SAVE PROGRESS