Why this matters
Looping queries (N+1 problem) causes excessive DB round-trips, degrading performance. Consolidating queries reduces load and improves response times, especially at scale.
Do not perform multiple DB queries inside a loop for data you could fetch in one query. Instead, consolidate using IN clauses or JOINs to retrieve all needed data at once.
Looping queries (N+1 problem) causes excessive DB round-trips, degrading performance. Consolidating queries reduces load and improves response times, especially at scale.
Side-by-side examples engineers can pattern-match during review.
<?php
\$ids = [1,2,3];
\$data = [];
foreach (\$ids as \$id) {
\$res = \$pdo->query("SELECT * FROM items WHERE user_id = \$id");
\$data[] = \$res->fetch();
}
?><?php
\$ids = [1,2,3];
\$list = implode(',', \$ids);
\$stmt = \$pdo->query("SELECT * FROM items WHERE user_id IN (\$list)");
\$data = \$stmt->fetchAll();
?><?php
\$ids = [1,2,3];
\$data = [];
foreach (\$ids as \$id) {
\$res = \$pdo->query("SELECT * FROM items WHERE user_id = \$id");
\$data[] = \$res->fetch();
}
?><?php
\$ids = [1,2,3];
\$list = implode(',', \$ids);
\$stmt = \$pdo->query("SELECT * FROM items WHERE user_id IN (\$list)");
\$data = \$stmt->fetchAll();
?>From the same buckets as this rule.
Review SQL/database migrations for operations that can lock large tables or cause downtime. Examples: creating indexes without CONCURRENTLY (Postgres), ALTER COLUMN TYPE on big tables, adding NOT NULL without backfill, long-running updates without batching. Require an online migration strategy (CONCURRENTLY, backfill in batches, dual-write/expand-contract) and a rollback plan.