Overview
Drizzle’s relational query API provides a type-safe, intuitive way to query related data without writing complex SQL joins. Define relationships once in your schema, then query nested data with full TypeScript inference.Defining Relations
One-to-Many Relationships
Use therelations() function to define relationships between tables:
Many-to-Many Relationships
Implement junction tables for many-to-many relationships:Self-Referencing Relations
Create hierarchical structures with self-references:Querying Related Data
Basic Relational Query
Query with nested relations using thewith option:
Nested Relations
Query multiple levels deep:Filtering Related Data
Apply filters, limits, and ordering to nested relations:Selecting Specific Columns
Choose which columns to include:Advanced Patterns
Using Extras for Computed Fields
Add computed columns with SQL expressions:Find One with Relations
Query a single record with relations:Using Placeholders in Relational Queries
Combine with prepared statements for reusable queries:Performance Considerations
Relational queries generate optimized SQL with JSON aggregation to minimize round trips to the database.
Understand Query Generation
Drizzle transforms relational queries into efficient SQL:Optimize Deep Nesting
Migration from SQL Queries
Before: Manual Joins
After: Relational Queries
Type Safety
Relational queries provide complete type inference:Best Practices
1
Define relations in a separate file or alongside tables
Keep your schema organized by grouping tables with their relations.
2
Use explicit field mappings
Always specify
fields and references for one() relations to avoid ambiguity.3
Leverage TypeScript inference
Let TypeScript guide you with auto-completion instead of referring to docs.
4
Apply filters at the relation level
Use
where on nested relations for efficient filtering.5
Limit nested data
Always use
limit on one-to-many relations in production to prevent excessive data loading.