L4Intermediate
Database Query Optimization Intuition
30 minWhen performance tuning
Format: Understand the N+1 problem and the concept of indexes.
N+1 Problem:
Scenario: Display 10 articles, each showing the author's name.
Bad approach (11 queries):
Query 1: Fetch 10 articles
Queries 2-11: Fetch the author for each article separately
Good approach (2 queries):
Query 1: Fetch 10 articles
Query 2: Fetch all authors at once
Index analogy: A database index = a book's table of contents. Without a table of contents, finding a word means flipping through the entire book. With a table of contents, you go directly to the right page.
Exercise: Do the following queries need an index?
- Find a user by user ID -> ?
- Sort articles by creation time -> ?
- Search for a user by email -> ?
- Full-text search of article content -> ?