frameworks
November 24, 2026 · 8 min read · 2 views

Drizzle ORM 0.35: Powerful Type-Safe Database Queries with New RelationBuilder and Performance Improvements

Drizzle ORM 0.35 introduces RelationBuilder for intuitive relational queries, improved type inference, and performance optimizations—making database interactions safer and faster.

Drizzle ORM 0.35: Powerful Type-Safe Database Queries with New RelationBuilder and Performance Improvements

Drizzle ORM has become a go-to choice for TypeScript developers who want compile-time type safety without sacrificing developer experience. The latest release, version 0.35, introduces significant improvements to relational query handling, type inference, and performance—addressing common pain points in modern application development.

In this post, we’ll explore what’s new in Drizzle 0.35, how to leverage the new RelationBuilder API, and how these changes improve your database layer.

What’s New in Drizzle 0.35

RelationBuilder API for Intuitive Relational Queries

One of the standout features in 0.35 is the new RelationBuilder API, which simplifies how developers construct complex relational queries. Previously, defining relationships and querying across multiple tables required careful attention to joins and type definitions. The new API streamlines this process significantly.

The RelationBuilder pattern allows you to define relationships declaratively and then query them naturally:

import { drizzle } from "drizzle-orm/node-postgres";
import { pgTable, serial, text, integer, timestamp } from "drizzle-orm/pg-core";
import { relations } from "drizzle-orm";

// Define tables
const users = pgTable("users", {
  id: serial("id").primaryKey(),
  name: text("name").notNull(),
  email: text("email").notNull().unique(),
  createdAt: timestamp("created_at").defaultNow(),
});

const posts = pgTable("posts", {
  id: serial("id").primaryKey(),
  userId: integer("user_id").notNull(),
  title: text("title").notNull(),
  content: text("content"),
  createdAt: timestamp("created_at").defaultNow(),
});

const comments = pgTable("comments", {
  id: serial("id").primaryKey(),
  postId: integer("post_id").notNull(),
  userId: integer("user_id").notNull(),
  text: text("text").notNull(),
  createdAt: timestamp("created_at").defaultNow(),
});

// Define relationships using RelationBuilder
const usersRelations = relations(users, ({ many }) => ({
  posts: many(posts),
  comments: many(comments),
}));

const postsRelations = relations(posts, ({ one, many }) => ({
  author: one(users, {
    fields: [posts.userId],
    references: [users.id],
  }),
  comments: many(comments),
}));

const commentsRelations = relations(comments, ({ one }) => ({
  post: one(posts, {
    fields: [comments.postId],
    references: [posts.id],
  }),
  author: one(users, {
    fields: [comments.userId],
    references: [users.id],
  }),
}));

// Export schema
export const schema = {
  users,
  posts,
  comments,
  usersRelations,
  postsRelations,
  commentsRelations,
};

With these relationships defined, querying nested data becomes dramatically simpler:

const db = drizzle(client, { schema });

// Query a user with all their posts and comments
const userWithContent = await db.query.users.findFirst({
  where: (users, { eq }) => eq(users.id, 1),
  with: {
    posts: {
      columns: { id: true, title: true, createdAt: true },
      with: {
        comments: {
          columns: { text: true, createdAt: true },
          with: {
            author: {
              columns: { id: true, name: true },
            },
          },
        },
      },
    },
  },
});

Notice how the with clause mirrors your relationship definitions. This approach eliminates manual JOIN construction and ensures type safety at every level.

Enhanced Type Inference and Validation

Drizzle 0.35 improves type inference significantly, particularly when working with nullable columns and complex selections. The TypeScript compiler now catches more schema-related errors at compile time rather than runtime.

// Type-safe column selection
const userSummary = await db
  .select({
    id: users.id,
    email: users.email,
    postCount: sql`COUNT(${posts.id})`.as("post_count"),
  })
  .from(users)
  .leftJoin(posts, eq(users.id, posts.userId))
  .groupBy(users.id);

// TypeScript knows userSummary is an array of { id: number, email: string, postCount: number }
// and will error if you try to access properties that don't exist
userSummary.forEach(({ id, email, postCount }) => {
  console.log(`User ${id}: ${email} has ${postCount} posts`);
});

Step-by-Step Guide: Migrating to Drizzle 0.35

Step 1: Update Drizzle and Dependencies

npm install drizzle-orm@^0.35.0 drizzle-kit@^0.26.0

If you’re using a specific database driver (PostgreSQL, MySQL, SQLite), ensure it’s compatible:

# For PostgreSQL
npm install pg

# For MySQL 2
npm install mysql2

# SQLite requires no additional driver (built-in)

Step 2: Refactor Schema with Relations

If you have an existing schema without formal relation definitions, add them:

// Before (implicit relationships)
const users = pgTable("users", { id: serial("id").primaryKey() });
const posts = pgTable("posts", { userId: integer("user_id") });

// After (explicit relationships with RelationBuilder)
const usersRelations = relations(users, ({ many }) => ({
  posts: many(posts),
}));

const postsRelations = relations(posts, ({ one }) => ({
  author: one(users, { fields: [posts.userId], references: [users.id] }),
}));

Step 3: Update Query Logic

Replace manual JOINs with the new relational query API where it makes sense:

// Before (manual join)
const user = await db
  .select({
    userId: users.id,
    userName: users.name,
    postId: posts.id,
    postTitle: posts.title,
  })
  .from(users)
  .leftJoin(posts, eq(users.id, posts.userId))
  .where(eq(users.id, 1));

// After (relational query)
const user = await db.query.users.findFirst({
  where: (users, { eq }) => eq(users.id, 1),
  with: {
    posts: {
      columns: { id: true, title: true },
    },
  },
});

Step 4: Run Migrations

npm run drizzle-kit migrate

Drizzle Kit will generate migration files for schema changes if any exist. Review and apply them.

Performance Improvements in 0.35

Query Compilation Optimization

Drizzle 0.35 optimizes how queries are compiled to raw SQL. For applications running thousands of queries, this results in measurable improvements:

  • Reduced compilation overhead: Query builders now cache compilation results more efficiently.
  • Smaller generated SQL: Unnecessary parentheses and redundant conditions are eliminated.
  • Batch operations: New .batch() API for multi-row inserts and updates reduces network round-trips.
// New batch API for efficient bulk operations
const newPosts = [
  { userId: 1, title: "Post 1", content: "Content 1" },
  { userId: 1, title: "Post 2", content: "Content 2" },
  { userId: 2, title: "Post 3", content: "Content 3" },
];

await db
  .insert(posts)
  .values(newPosts)
  .returning();

Common Pitfalls to Avoid

Pitfall 1: Circular Relationship Definitions

If two tables reference each other, Drizzle 0.35 handles it, but be explicit:

// This works, but be clear about the direction
const usersRelations = relations(users, ({ many }) => ({
  posts: many(posts),
}));

const postsRelations = relations(posts, ({ one }) => ({
  author: one(users), // Explicitly reference back
}));

Pitfall 2: Over-Fetching with Nested Relations

The with clause is powerful, but deep nesting can result in excessive data transfer. Use columns to select only what you need:

// Bad: fetches all columns at every level
const user = await db.query.users.findFirst({
  with: {
    posts: {
      with: {
        comments: {
          with: {
            author: true, // Everything!
          },
        },
      },
    },
  },
});

// Good: selective columns
const user = await db.query.users.findFirst({
  columns: { id: true, name: true },
  with: {
    posts: {
      columns: { id: true, title: true },
      with: {
        comments: {
          columns: { text: true },
          with: {
            author: {
              columns: { id: true, name: true },
            },
          },
        },
      },
    },
  },
});

Pitfall 3: Forgetting to Export Relations

Relations must be included in your schema export for Drizzle Kit to recognize them:

// In your schema file (db/schema.ts)
export const schema = {
  users,
  posts,
  comments,
  usersRelations, // Don't forget!
  postsRelations,
  commentsRelations,
};

Why It Matters

Database interactions are a cornerstone of modern applications. In a typical web service, database queries can account for 20-40% of execution time and are a frequent source of runtime errors. Drizzle ORM 0.35 addresses both concerns:

  1. Type Safety: TypeScript catches schema mismatches before code runs. For teams developing complex applications, this prevents entire classes of bugs.

  2. Developer Experience: The new RelationBuilder API reduces cognitive load. Developers write cleaner, more maintainable code without learning complex SQL or Join syntax.

  3. Performance: For data-heavy applications, query optimization and batch operations directly impact user experience and infrastructure costs.

Testing Your Migrations

When adopting new Drizzle features, test thoroughly. Use tools like Webhook Tester to inspect database query logs if you’re debugging complex relationships:

// Add logging middleware to inspect generated SQL
db.on.select = (query) => {
  console.log("Generated SQL:", query.getSQL());
};

For validating query results, the JSON Formatter is handy for pretty-printing and inspecting nested query responses:

const user = await db.query.users.findFirst({
  with: { posts: true },
});

console.log(JSON.stringify(user, null, 2));
// Pretty-print with the JSON Formatter tool for analysis

Practical Real-World Example: Blog Platform Schema

Let’s build a complete schema for a blog platform using Drizzle 0.35:

import { pgTable, serial, text, integer, boolean, timestamp, varchar } from "drizzle-orm/pg-core";
import { relations } from "drizzle-orm";

// Users table
const users = pgTable("users", {
  id: serial("id").primaryKey(),
  username: varchar("username", { length: 255 }).notNull().unique(),
  email: varchar("email", { length: 255 }).notNull().unique(),
  avatarUrl: text("avatar_url"),
  bio: text("bio"),
  createdAt: timestamp("created_at").defaultNow().notNull(),
});

// Posts table
const posts = pgTable("posts", {
  id: serial("id").primaryKey(),
  authorId: integer("author_id").notNull(),
  title: varchar("title", { length: 255 }).notNull(),
  slug: varchar("slug", { length: 255 }).notNull().unique(),
  content: text("content").notNull(),
  published: boolean("published").default(false).notNull(),
  createdAt: timestamp("created_at").defaultNow().notNull(),
  updatedAt: timestamp("updated_at").defaultNow().notNull(),
});

// Comments table
const comments = pgTable("comments", {
  id: serial("id").primaryKey(),
  postId: integer("post_id").notNull(),
  authorId: integer("author_id").notNull(),
  content: text("content").notNull(),
  createdAt: timestamp("created_at").defaultNow().notNull(),
});

// Likes table
const likes = pgTable("likes", {
  id: serial("id").primaryKey(),
  postId: integer("post_id").notNull(),
  userId: integer("user_id").notNull(),
  createdAt: timestamp("created_at").defaultNow().notNull(),
});

// Define relationships
const usersRelations = relations(users, ({ many }) => ({
  posts: many(posts),
  comments: many(comments),
  likes: many(likes),
}));

const postsRelations = relations(posts, ({ one, many }) => ({
  author: one(users, {
    fields: [posts.authorId],
    references: [users.id],
  }),
  comments: many(comments),
  likes: many(likes),
}));

const commentsRelations = relations(comments, ({ one }) => ({
  post: one(posts, {
    fields: [comments.postId],
    references: [posts.id],
  }),
  author: one(users, {
    fields: [comments.authorId],
    references: [users.id],
  }),
}));

const likesRelations = relations(likes, ({ one }) => ({
  post: one(posts, {
    fields: [likes.postId],
    references: [posts.id],
  }),
  user: one(users, {
    fields: [likes.userId],
    references: [users.id],
  }),
}));

// Query example: Get a published post with comments and likes
const getPostWithDetails = async (postId: number) => {
  return await db.query.posts.findFirst({
    where: (posts, { eq, and }) => and(
      eq(posts.id, postId),
      eq(posts.published, true)
    ),
    columns: { id: true, title: true, slug: true, content: true, createdAt: true },
    with: {
      author: {
        columns: { id: true, username: true, avatarUrl: true },
      },
      comments: {
        columns: { id: true, content: true, createdAt: true },
        with: {
          author: {
            columns: { id: true, username: true, avatarUrl: true },
          },
        },
      },
      likes: {
        columns: { id: true },
      },
    },
  });
};

Debugging Relational Queries

When things go wrong, use the SQL Formatter to understand the generated SQL:

const query = db.query.posts
  .findMany({
    with: { author: true, comments: true },
  })
  .toSQL();

console.log(query.sql); // Print generated SQL
// Use the SQL Formatter tool to validate and prettify

Conclusion

Drizzle ORM 0.35 represents a significant step forward in making database development in TypeScript safer and more intuitive. The RelationBuilder API, combined with improved type inference and performance optimizations, makes it an excellent choice for teams building data-intensive applications.

Whether you’re starting a new project or migrating from raw SQL or other ORMs, Drizzle 0.35 provides the tools to build robust, maintainable, and performant database layers. Start with the relational query API, leverage type safety, and watch your development velocity improve.

This post was generated with AI assistance and reviewed for accuracy.