Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Comprehensive Postgres performance optimization and best practices guide maintained by Supabase
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/data-n-plus-one.md
1---2title: Eliminate N+1 Queries with Batch Loading3impact: MEDIUM-HIGH4impactDescription: 10-100x fewer database round trips5tags: n-plus-one, batch, performance, queries6---78## Eliminate N+1 Queries with Batch Loading910N+1 queries execute one query per item in a loop. Batch them into a single query using arrays or JOINs.1112**Incorrect (N+1 queries):**1314```sql15-- First query: get all users16select id from users where active = true; -- Returns 100 IDs1718-- Then N queries, one per user19select * from orders where user_id = 1;20select * from orders where user_id = 2;21select * from orders where user_id = 3;22-- ... 97 more queries!2324-- Total: 101 round trips to database25```2627**Correct (single batch query):**2829```sql30-- Collect IDs and query once with ANY31select * from orders where user_id = any(array[1, 2, 3, ...]);3233-- Or use JOIN instead of loop34select u.id, u.name, o.*35from users u36left join orders o on o.user_id = u.id37where u.active = true;3839-- Total: 1 round trip40```4142Application pattern:4344```sql45-- Instead of looping in application code:46-- for user in users: db.query("SELECT * FROM orders WHERE user_id = $1", user.id)4748-- Pass array parameter:49select * from orders where user_id = any($1::bigint[]);50-- Application passes: [1, 2, 3, 4, 5, ...]51```5253Reference: [N+1 Query Problem](https://supabase.com/docs/guides/database/query-optimization)54