Say you’re building a blog with a profile page for each contributor. On Ada’s page, for example, you might show her name, the titles of her two latest published posts, and a label that says “3 published posts.”
In this tutorial, you’ll build one Drizzle query to load the author, pick the two titles to display, and calculate the full count. You’ll also see how to render an empty list for an author with only drafts and return a 404 when the author doesn’t exist.
Run the author page query
This example uses PostgreSQL and drizzle-orm@1.0.0-rc.5, a v1 release candidate. Drizzle Run creates the tables and seeds a fresh database for each run.
Load the playground and click Run. The first three result cards show Ada’s page, an author with only drafts, and a missing author. The last card shows the prepared query’s results for Ada and Grace.
Open the full playground and open a copy to edit the code.
Model authors, posts, and drafts
An author has a unique slug, the part of the URL that identifies their page. A post belongs to an author through authorId. A timestamp in publishedAt marks a published post. A draft leaves it null.
import { pgTable, integer, text, timestamp } from "drizzle-orm/pg-core";
export const users = pgTable("users", { id: integer("id").primaryKey(), name: text("name").notNull(), slug: text("slug").notNull().unique(),});
export const posts = pgTable("posts", { id: integer("id").primaryKey(), title: text("title").notNull(), publishedAt: timestamp("published_at", { mode: "string", withTimezone: true }), authorId: integer("author_id") .notNull() .references(() => users.id),});The foreign key keeps every post attached to an existing author. Multiple posts can point to the same author. The unique constraint on slug ensures each URL identifies at most one author.
In the playground, Ada has three published posts and a draft. Grace has one draft. Those two authors let you check whether the query both excludes drafts and keeps an author whose published list is empty.
Define the relation in the direction you read
The page starts with an author and loads their posts. Add the defineRelations import near the top of schema.ts and place the relation after the table definitions.
import { defineRelations } from "drizzle-orm";
export const relations = defineRelations({ users, posts }, (r) => ({ users: { posts: r.many.posts({ from: r.users.id, to: r.posts.authorId, }), },}));From each user row, Drizzle matches users.id to posts.authorId. Use r.many.posts() because the author can have any number of posts, including zero. The name posts is the key you’ll use in with.
Drizzle Run binds the exported relations to its connected db. In an existing Node.js app that uses pg, pass the relations to drizzle() yourself. This setup assumes DATABASE_URL points to a PostgreSQL database where the tables already exist.
import { Pool } from "pg";import { drizzle } from "drizzle-orm/node-postgres";import { relations } from "./schema";
const client = new Pool({ connectionString: process.env.DATABASE_URL });
export const db = drizzle({ client, relations });Find the author by URL slug
Start with the row that determines whether the page exists. where matches the slug from the URL. The slug is unique, so use findFirst() to get one object or undefined directly. findMany() would give you an array to unwrap.
import { db } from "./db";
const author = await db.query.users.findFirst({ where: { slug: "ada" },});This returns Ada’s user row with her id, name, and slug. Drizzle selects every user column by default. The foreign key connects the rows in PostgreSQL, but this query has only asked for the author so far.
{ "id": 1, "name": "Ada", "slug": "ada"}Choose the fields and include the posts
Use columns to keep the fields your page uses. The author header only needs name. The ID still connects the records and the slug still filters the author when both are omitted from the response.
Use with to load a named relation alongside the author. with: { posts: true } would attach every post with every post column. Pass an object under posts when you want to configure that list. Its columns block applies to the post rows, so you can keep just the titles.
import { db } from "./db";
const author = await db.query.users.findFirst({ where: { slug: "ada" }, columns: { name: true }, with: { posts: { columns: { title: true }, }, },});The result has a name and a nested posts array. It contains four titles at this point, including Ada’s draft, “Ada’s next post.” Selecting columns controls the shape of each row. We still need to decide which rows belong in that array.
Here’s the result from one run.
{ "name": "Ada", "posts": [ { "title": "Getting started with Drizzle" }, { "title": "Loading related data" }, { "title": "Building an author page" }, { "title": "Ada's next post" } ]}Load only the two latest published posts
Add the three highlighted lines inside with.posts to choose which posts appear on the page.
import { db } from "./db";
const author = await db.query.users.findFirst({ where: { slug: "ada" }, columns: { name: true }, with: { posts: { where: { publishedAt: { isNotNull: true } }, orderBy: { publishedAt: "desc", id: "desc" }, limit: 2, columns: { title: true }, }, },});where keeps posts with a publication timestamp. Since the condition lives inside with.posts, the author stays in the result even if every post is a draft.
orderBy sorts Ada’s published posts by date, newest first, and uses the ID to break ties. Then limit: 2 takes the first two posts from that list.
Ada’s draft and her oldest published post drop out of the list.
{ "name": "Ada", "posts": [ { "title": "Building an author page" }, { "title": "Loading related data" } ]}Count all published posts with a subquery
The length of the list can only tell you how many posts the page loaded. For Ada, that’s two. To show how many she has published overall, use extras to add a computed field to the author object.
db.$count() builds a count over posts. Inside the extras callback, compare posts.authorId with author.id from the outer query and require a publication timestamp. This is a correlated subquery because the inner count uses the current author from the outer query. Use the callback’s author.id so Drizzle references the author’s alias in the generated SQL.
Return the count builder from the callback. Drizzle embeds it in the SQL it sends for the author page. You can see that statement in the playground’s Logs tab. The limit: 2 belongs to the post list, so the count still covers all three of Ada’s published posts.
import { db } from "./db";import { and, eq, isNotNull } from "drizzle-orm";import { posts } from "./schema";
export async function loadAuthorPage(slug: string) { return db.query.users.findFirst({ where: { slug }, columns: { name: true }, extras: { publishedPostCount: (author) => db.$count(posts, and(eq(posts.authorId, author.id), isNotNull(posts.publishedAt))), }, with: { posts: { where: { publishedAt: { isNotNull: true } }, orderBy: { publishedAt: "desc", id: "desc" }, limit: 2, columns: { title: true }, }, }, });}For loadAuthorPage("ada"), the query returns:
{ "name": "Ada", "publishedPostCount": 3, "posts": [ { "title": "Building an author page" }, { "title": "Loading related data" } ]}Handle a missing author and an empty post list
| Slug | Query result | What the page does |
|---|---|---|
ada |
Ada with two posts and publishedPostCount: 3 |
Show two previews and the published total |
grace |
Grace with posts: [] and publishedPostCount: 0 |
Render the author with an empty state |
unknown |
undefined |
Return a 404 |
loadAuthorPage("grace") returns an author object with no published posts.
{ "name": "Grace", "publishedPostCount": 0, "posts": []}loadAuthorPage("unknown") returns the JavaScript value undefined.
undefinedIn the HTTP handler, author == null catches both undefined and null and returns a 404. An existing author with an empty list gets a successful response, and the page can use posts.length to show its empty state.
import { loadAuthorPage } from "./author-page";
export async function getAuthorPageResponse(slug: string): Promise<Response> { const author = await loadAuthorPage(slug);
if (author == null) { return new Response("Author not found", { status: 404 }); }
return Response.json(author);}In a playground copy, open query.ts and change the nested limit from two to one. In the first result card, Ada’s list shrinks to one post and her total stays at three. Then comment out the nested where in the same query. Grace’s draft appears in the second card and her published total stays at zero. The two clauses solve different needs, so keep both publication checks for the public page.
Reuse the query with a placeholder
Every author page uses the same query. Only the slug changes. Prepare it outside loadAuthorPage() so Drizzle can build the SQL once and bind a new slug on each call. With pg, repeated calls on the same connection can also reuse the statement PostgreSQL has already parsed. PostgreSQL can reuse a plan or make one for the current values. Prepared statements in PostgreSQL (postgresql.org, opens in a new tab)
Consider this on a busy route that runs the same query often. The gain depends on how much time the database spends parsing and planning compared with running the query. For an occasional lookup, the original loadAuthorPage() is a good default.
import { db } from "./db";import { and, eq, isNotNull, sql } from "drizzle-orm";import { posts } from "./schema";
const authorPageBySlug = db.query.users .findFirst({ where: { slug: sql.placeholder("slug") }, columns: { name: true }, extras: { publishedPostCount: (author) => db.$count(posts, and(eq(posts.authorId, author.id), isNotNull(posts.publishedAt))), }, with: { posts: { where: { publishedAt: { isNotNull: true } }, orderBy: { publishedAt: "desc", id: "desc" }, limit: 2, columns: { title: true }, }, }, }) .prepare("author_page_by_slug");
export async function loadAuthorPage(slug: string) { return authorPageBySlug.execute({ slug });}sql.placeholder("slug") names the value Drizzle needs at execution time. The key in execute({ slug }) matches that name. The string in prepare("author_page_by_slug") names the prepared statement.
The handler keeps calling loadAuthorPage(slug) as before. In the playground, open prepared.ts to see the statement and run query.ts to try it with both slugs. Ada gets two posts and a total of three. Grace gets an empty list and a total of zero.