Shaping queries for screens

Intermediate · 5 min

Fetch what a Taskboard screen needs in one query instead of twenty: relational queries, grouped counts, and the join fan-out that inflates your numbers.

Before thisTyped queries with an ORM in a feature

basarat · 5 min

Shaping queries for screens

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by basaratReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Design the query from the screen backwards: list the fields the screen shows, then fetch exactly those in as few queries as possible.
  • Looping over rows and querying inside the loop turns one screen into dozens of queries, which is the N+1 problem.
  • A relational query fetches a parent with its children and their authors in a single round trip.
  • Joining two one-to-many tables and then counting multiplies rows, so counts must be computed per table before joining or in subqueries.
  • Counting how many queries a request runs is a cheap, reliable way to catch a slow screen before users do.

Start from the screen

Taskboard’s project page shows a list of tasks. Each row has the title, the status, the assignee’s name, and a count of comments. That list is a sentence about the screen, and it decides the query. Tables are the wrong place to start. What the screen displays is the right one.

The easy way to build it is the slow way, and it works fine on your laptop with five rows.

The N+1 trap

Fetch the tasks, then loop and fetch each task’s comments:

const rows = await db.select().from(tasks).where(eq(tasks.projectId, 1)).limit(20);
for (const t of rows) {
  await db.select().from(comments).where(eq(comments.taskId, t.id));
}

Each query is simple and typed. I counted the queries this runs on the seeded database (Drizzle 0.45.4 on PGlite 0.5.17): 21. One for the list, plus one per task. That’s the N+1 problem: 1 query for the list and N more for the details. On a laptop with an in-process database each call takes microseconds, so nothing feels wrong. In production each call is a network round trip to a database that may be in another machine, and the page takes seconds. The backend roadmap explains the mechanics in the N+1 query problem and eager loading. The full-stack lesson is that the screen’s shape causes it: the moment a list row shows data from another table, you’ve invited it.

Fetch the tree in one go

Drizzle has a relational query API for exactly this. First you tell it how tables relate:

export const tasksRelations = relations(tasks, ({ one, many }) => ({
  assignee: one(users, { fields: [tasks.assigneeId], references: [users.id] }),
  comments: many(comments),
}));

Then you ask for a task with the parts you want:

const board = await db.query.tasks.findMany({
  where: eq(tasks.projectId, 1),
  limit: 20,
  orderBy: desc(tasks.id),
  with: {
    assignee: { columns: { name: true } },
    comments: { with: { author: { columns: { name: true } } } },
  },
});

The same count: 1 query. The result comes back already nested the way a component wants to read it, with assignee.name and comments[].author.name, and the columns option keeps unrelated columns (such as emails) out of the result. That last part matters for the seam: a query that selects everything is one careless JSON.stringify away from sending something private to the browser.

I checked this on the same data: the 21-query loop became a single call. I did not benchmark the generated SQL, and relational queries are not magic. The library builds one statement with joins or subqueries, and a very wide tree can still be heavy. Count queries to find N+1, then measure time for everything else.

When the screen wants numbers

The board header says “Website relaunch: 25 todo, 25 doing, 25 done”. That’s an aggregate, and it should be one grouped query, not a fetch-everything-and-count in JavaScript:

const summary = await db
  .select({ projectId: tasks.projectId, status: tasks.status, n: count() })
  .from(tasks)
  .groupBy(tasks.projectId, tasks.status);

One query, six rows (two projects times three statuses), instead of loading a hundred tasks to count them. The database is built for this, so let it do the counting.

The fan-out trap

Now the screen wants, per task, the comment count and the attachment count. The natural query joins both child tables and counts. I ran it for one task that has 3 comments and 4 attachments:

select count(c.id) comments, count(a.id) attachments
from tasks t
left join comments c on c.task_id = t.id
left join attachments a on a.task_id = t.id
where t.id = 1
{ comments: 12, attachments: 12 }

Wrong twice. The true answers are 3 and 4. Joining two one-to-many tables gives every comment a row for every attachment: 3 times 4 is 12. Both counts then count those 12 rows. This is join fan-out, and it’s a particularly nasty bug because the query runs, the numbers look plausible, and nothing errors.

Count each child table separately and combine the results:

select t.id,
  (select count(*) from comments c where c.task_id = t.id) as comments,
  (select count(*) from attachments a where a.task_id = t.id) as attachments
from tasks t
{ id: 1, comments: 3, attachments: 4 }
{ id: 2, comments: 0, attachments: 0 }

Correct, and task 2 correctly shows zeros. A grouped subquery joined back in (a common table expression) does the same thing and is often faster on large tables. The rule: when you aggregate over more than one child table, aggregate each separately before you combine them. The most reliable test is a row you can verify by hand, like a task with 3 and 4.

Shape the response, too

The query’s result is not automatically your API’s response. Often you will map it: rename fields, drop the ones the client doesn’t need, turn dates into strings. Keep that mapping in one function so the response type and the query agree. The next group, starting with designing endpoints for the UI, is about that shape.

A habit: count queries in tests

N+1 is invisible in code review and obvious in a number. In an integration test, wrap the database client, count the calls for one request, and assert a small ceiling. When someone adds a field to the list screen and the count jumps from 2 to 22, the test fails before the page ships. I counted queries in my scratch run by wrapping the client’s query method with a counter, which took four lines.

What the video covers

basarat’s “Drizzle relations are amazing // Stop using manual joins” is about five minutes and was published in June 2024. The description is channel links, so the content is inferred from the title: it argues for Drizzle’s relational queries over hand-written joins, which is the middle section of this lesson. It is short and covers one technique. It says nothing I can confirm about aggregates or fan-out, which come from my own run above. Drizzle changed its relational query API after this video, and Nev the Dev’s 2025 “Drizzle’s new relational API is nuts!” is linked as a look at the newer one.

Where this fits

Fetching one screen’s worth of data efficiently is solved. Real lists are longer than a screen, though, and people want to filter and search them. That is the next lesson: pagination, filtering and search end to end.

Check yourself

  1. 01What is the N+1 problem in Taskboard's project page?

    One query loads 20 tasks, then a separate query per task loads its comments. That is 21 queries where one or two would do.

  2. 02Why did counting comments and attachments in one joined query return 12 and 12 for a task with 3 and 4?

    Joining both child tables multiplies the rows, 3 times 4 equals 12, so every count sees the fan-out. Counting in per-table subqueries gives 3 and 4.

  3. 03Where do you start when designing the query for a screen?

    With the fields the screen displays. The shape of the screen decides which tables, joins and aggregates the query needs.

  4. 04How do you detect N+1 without reading code?

    Count the queries a request runs, in a log or a test. A number that grows with the number of rows is the sign.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark