Drizzle ORM is designed to be a thin typed layer on top of SQL.
We truly believe we’ve designed the best way to operate an SQL database from TypeScript and it’s time to make it better.
Relational queries are meant to provide you with a great developer experience for querying
nested relational data from an SQL database, avoiding multiple joins and complex data mappings.
It is an extension to the existing schema definition and query builder.
You can opt-in to use it based on your needs.
We’ve made sure you have both the best-in-class developer experience and performance.
index.ts
schema.ts
⚠️ If you have SQL schema declared in multiple files you can do it like that
index.ts
schema1.ts
schema2.ts
Modes
Drizzle relational queries always generate exactly one SQL statement to run on the database and it has certain caveats.
To have best in class support for every database out there we’ve introduced modes.
Drizzle relational queries use lateral joins of subqueries under the hood and for now PlanetScale does not support them.
When using mysql2 driver with regular MySQL database — you should specify mode: "default"
When using mysql2 driver with PlanetScale — you need to specify mode: "planetscale"
Declaring relations
One-to-one
Drizzle ORM provides you an API to define one-to-one relations between tables with the relations operator.
An example of a one-to-one relation between users and users, where a user can invite another (this example uses a self reference):
Another example would be a user having a profile information stored in separate table. In this case, because the foreign key is stored in the “profile_info” table, the user relation have neither fields or references. This tells Typescript that user.profileInfo is nullable:
One-to-many
Drizzle ORM provides you an API to define one-to-many relations between tables with relations operator.
Example of one-to-many relation between users and posts they’ve written:
Now lets add comments to the posts:
Many-to-many
Drizzle ORM provides you an API to define many-to-many relations between tables through so called junction or join tables,
they have to be explicitly defined and store associations between related tables.
Example of many-to-many relation between users and groups:
Foreign keys
You might’ve noticed that relations look similar to foreign keys — they even have a references property. So what’s the difference?
While foreign keys serve a similar purpose, defining relations between tables, they work on a different level compared to relations.
Foreign keys are a database level constraint, they are checked on every insert/update/delete operation and throw an error if a constraint is violated.
On the other hand, relations are a higher level abstraction, they are used to define relations between tables on the application level only.
They do not affect the database schema in any way and do not create foreign keys implicitly.
What this means is relations and foreign keys can be used together, but they are not dependent on each other.
You can define relations without using foreign keys (and vice versa), which allows them to be used with databases that do not support foreign keys.
The following two examples will work exactly the same in terms of querying the data using Drizzle relational queries.
You can specify actions that should occur when the referenced data in the parent table is modified. These actions are known as “foreign key actions.” PostgreSQL provides several options for these actions.
On Delete/ Update Actions
CASCADE: When a row in the parent table is deleted, all corresponding rows in the child table will also be deleted. This ensures that no orphaned rows exist in the child table.
NO ACTION: This is the default action. It prevents the deletion of a row in the parent table if there are related rows in the child table. The DELETE operation in the parent table will fail.
RESTRICT: Similar to NO ACTION, it prevents the deletion of a parent row if there are dependent rows in the child table. It is essentially the same as NO ACTION and included for compatibility reasons.
SET DEFAULT: If a row in the parent table is deleted, the foreign key column in the child table will be set to its default value if it has one. If it doesn’t have a default value, the DELETE operation will fail.
SET NULL: When a row in the parent table is deleted, the foreign key column in the child table will be set to NULL. This action assumes that the foreign key column in the child table allows NULL values.
Analogous to ON DELETE there is also ON UPDATE which is invoked when a referenced column is changed (updated). The possible actions are the same, except that column lists cannot be specified for SET NULL and SET DEFAULT. In this case, CASCADE means that the updated values of the referenced column(s) should be copied into the referencing row(s).
in drizzle you can add foreign key action using references() second argument.
type of the actions
In the following example, adding onDelete: 'cascade' to the author field on the posts schema means that deleting the user will also delete all related Post records.
Disambiguating relations
Drizzle also provides the relationName option as a way to disambiguate
relations when you define multiple of them between the same two tables. For
example, if you define a posts table that has the author and reviewer
relations.
Querying
Relational queries are an extension to Drizzle’s original query builder.
You need to provide all tables and relations from your schema file/files upon drizzle()
initialization and then just use the db.query API.
ℹ️
drizzle import path depends on the database driver you’re using.
index.ts
schema.ts
Drizzle provides .findMany() and .findFirst() APIs.
Find many
Find first
💡
.findFirst() will add limit 1 to the query.
Include relations
With operator lets you combine data from multiple related tables and properly aggregate results.
Getting all posts with comments:
Getting first post with comments:
You can chain nested with statements as much as necessary.
For any nested with queries Drizzle will infer types using Core Type API.
Get all users with posts. Each post should contain a list of comments:
Partial fields select
columns parameter lets you include or omit columns you want to get from the database.
ℹ️
Drizzle performs partial selects on the query level, no additional data is transferred from the database.
Keep in mind that a single SQL statement is outputted by Drizzle.
Get all posts with just id, content and include comments:
Get all posts without content:
ℹ️
When both true and false select options are present, all false options are ignored.
If you include the name field and exclude the id field, id exclusion will be redundant,
all fields apart from name would be excluded anyways.
Exclude and Include fields in the same query:
Only include columns from nested relations:
Nested partial fields select
Just like with partial select, you can include or exclude columns of nested relations:
Select filters
Just like in our SQL-like query builder,
relational queries API lets you define filters and conditions with the list of our operators.
You can either import them from drizzle-orm or use from the callback syntax:
Find post with id=1 and comments that were created before particular date:
Limit & Offset
Drizzle ORM provides limit & offset API for queries and for the nested entities.
Find 5 posts:
Find posts and get 3 comments at most:
⚠️
offset is only available for top level query.
Find posts with comments from the 5th to the 10th post:
Order By
Drizzle provides API for ordering in the relational query builder.
You can use same ordering core API or use
order by operator from the callback with no imports.
Order by asc + desc:
Include custom fields
Relational query API lets you add custom additional fields.
It’s useful when you need to retrieve data and apply additional functions to it.
⚠️
As of now aggregations are not supported in extras, please use core queries for that.
lowerName as a key will be included to all fields in returned object.
⚠️
You have to explicitly specify .as("<name_for_column>")
To retrieve all users with groups, but with the fullName field included (which is a concatenation of firstName and lastName),
you can use the following query with the Drizzle relational query builder.
To retrieve all posts with comments and add an additional field to calculate the size of the post content and the size of each comment content:
Prepared statements
Prepared statements are designed to massively improve query performance — see here.
In this section, you can learn how to define placeholders and execute prepared statements
using the Drizzle relational query builder.