Menu

1 / 2

Query Optimization: Stop Scanning Every Row

DEV Community·Tosh·6 months ago
#Y7CRcCYb
#database#performance#sql#index#slow
Reading 0:00
15s threshold

Your query is slow. You check: the database is fine. Connections are fine. The query is just... slow.

You look at the query:

SELECT * FROM orders WHERE user_id = 123

Enter fullscreen mode

Exit fullscreen mode

Seems simple. Why is it slow?

Because there's no index on user_id . The database scans every row to find matching ones.

With a million rows, that's a million comparisons.

Add an index. Instant 100x speedup.

The Index

An index is a lookup table.

Without index:

SELECT * FROM orders WHERE user_id = 123 → Database scans all 1 M rows → Finds matches → Returns results

Enter fullscreen mode

Exit fullscreen mode

With index:

SELECT * FROM orders WHERE user_id = 123 → Index lookup : user_id = 123 → row IDs [ 5 , 12 , 99 , ...] → Fetch those rows → Returns results

Enter fullscreen mode

Exit fullscreen mode

Index is pre-sorted.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.