Skip to main content

Overview

Drizzle ORM provides a powerful relational query system that allows you to define relationships between tables and fetch related data with type-safe, intuitive syntax.

Defining Relations

Relations are defined separately from table schemas using the relations function:

One-to-Many

Define a one-to-many relationship:
schema.ts

One-to-One

Define a one-to-one relationship:

Many-to-Many

Use a junction table for many-to-many relationships:

Composite Foreign Keys

Define relations with composite keys:

Relational Queries

Once relations are defined, use the relational query API for intuitive data fetching:

Find First

Find a single record:

Find Many

Find multiple records:

Nested Relations

Fetch deeply nested relationships:

Filtering Relations

Filter, order, and limit related records:

Selecting Columns

Choose specific columns to return:

Extras

Add computed fields to queries:

Where Operators

All standard operators are available in relational queries:

Order By

Limit and Offset

Self-Referencing Relations

Define hierarchical relationships:

Relation Names

Disambiguate multiple relations to the same table:

Nullable Relations

Relations automatically handle nullable foreign keys:

Best Practices

  • Define all relations: Even if you only query from one side, define both sides for completeness
  • Use relation names: For multiple relations to the same table, always specify relationName
  • Optimize queries: Use columns to select only needed fields
  • Pagination: Always use limit and offset for large datasets
  • Filter relations: Filter nested relations to reduce data transfer
Relational queries can become slow with deeply nested relations. Consider using separate queries or implementing pagination for nested data.

Comparison with SQL Joins

The relational API provides cleaner syntax and automatic result grouping, while the query builder offers more control over the SQL output.

Next Steps

Migrations

Learn how to manage schema changes

Transactions

Execute atomic database operations