Skip to main content
Kysely is NOT an ORM. Kysely DOES NOT have the concept of relations. Kysely IS a query builder. Kysely DOES build the SQL you tell it to, nothing more, nothing less.
Having said that, there are ways to nest related rows in your queries. You just have to do it using the tools SQL and the underlying dialect (e.g. PostgreSQL, MySQL, or SQLite) provide.

Prerequisites

This recipe is supported on:
  • PostgreSQL (all versions)
  • MySQL versions 8.0.14 and higher
  • SQLite (with ParseJSONResultsPlugin)
MySQL 8.0.14+ is required due to the way subqueries use outer references in this recipe. See the MySQL 8.0.14 changelog for details.

JSON data types and functions

PostgreSQL and MySQL have rich JSON support through their json data types and functions. The pg and mysql2 node drivers automatically parse returned json columns as JavaScript objects.

Parsing JSON in SQLite

The built-in SqliteDialect and some third-party dialects don’t parse returned JSON columns to objects automatically. If your JSON columns get returned as strings, use the ParseJSONResultsPlugin:

Basic example

Let’s fetch a list of people and nest each person’s pets and mother into the returned objects. Here’s the raw PostgreSQL SQL we want to generate:

Using helper functions

Kysely provides helper functions to simplify this pattern:

Import built-in helpers

These helpers are included in Kysely. Import them based on your dialect:

Type-safe queries with helpers

With these helpers, our query becomes much more readable:

Creating reusable relation helpers

For repeated use across your codebase, create dedicated helper functions:
Now your queries become even cleaner:

Handling nullability

Kysely marks selections as nullable if it can’t determine that the related object always exists. Use $notNull() when you know a relation exists:

Conditional relations

Use $if to select relations conditionally:
For better performance, make sure you have indices on foreign key columns like pet.owner_id and person.mother_id.