# Kysely > The most powerful type-safe SQL query builder for TypeScript - [Kysely](https://kysely.dev/index.md) ## docs ### category #### comparisons Compare SQL query builders, ORMs, SQL embedded in TypeScript, and typed SQL files, and explore the tradeoffs between libraries. - [Comparisons](https://kysely.dev/docs/category/comparisons.md): Compare SQL query builders, ORMs, SQL embedded in TypeScript, and typed SQL files, and explore the tradeoffs between libraries. #### cte Short and simple examples of how to use Common Table Expressions (CTE) in queries. - [CTE](https://kysely.dev/docs/category/cte.md): Short and simple examples of how to use Common Table Expressions (CTE) in queries. #### delete Short and simple examples of how to write DELETE queries. - [DELETE](https://kysely.dev/docs/category/delete.md): Short and simple examples of how to write DELETE queries. #### examples Short and simple examples of how to use Kysely to achieve common tasks. - [Examples](https://kysely.dev/docs/category/examples.md): Short and simple examples of how to use Kysely to achieve common tasks. #### insert Short and simple examples of how to write INSERT queries. - [INSERT](https://kysely.dev/docs/category/insert.md): Short and simple examples of how to write INSERT queries. #### integrations Kysely integrations with other libraries, ORMs, and AI assistants. - [Integrations](https://kysely.dev/docs/category/integrations.md): Kysely integrations with other libraries, ORMs, and AI assistants. #### join Examples of queries that use JOINs. - [JOIN](https://kysely.dev/docs/category/join.md): Examples of queries that use JOINs. #### merge Short and simple examples of how to write MERGE queries. - [MERGE](https://kysely.dev/docs/category/merge.md): Short and simple examples of how to write MERGE queries. #### other-runtimes Use Kysely in browsers to build type-safe queries and compile SQL without a database connection. - [Other runtimes](https://kysely.dev/docs/category/other-runtimes.md): Use Kysely in browsers to build type-safe queries and compile SQL without a database connection. #### recipes Explore Kysely recipes for reusable helpers, expressions, nested relations, database schemas, logging, and advanced TypeScript types. - [Recipes](https://kysely.dev/docs/category/recipes.md): Explore Kysely recipes for reusable helpers, expressions, nested relations, database schemas, logging, and advanced TypeScript types. #### select Short and simple examples of using the SELECT methods. - [SELECT](https://kysely.dev/docs/category/select.md): Short and simple examples of using the SELECT methods. #### transactions Short and simple examples of how to use transactions. - [Transactions](https://kysely.dev/docs/category/transactions.md): Short and simple examples of how to use transactions. #### update Short and simple examples of how to write UPDATE queries. - [UPDATE](https://kysely.dev/docs/category/update.md): Short and simple examples of how to write UPDATE queries. #### where Short and simple examples of how to use the where method to add a WHERE statement. While most of the examples show a SELECT query, the where method works exactly the same in UPDATE and DELETE queries too. - [WHERE](https://kysely.dev/docs/category/where.md): Short and simple examples of how to use the where method to add a WHERE statement. While most of the examples show a SELECT query, the where method works exactly the same in UPDATE and DELETE queries too. ### comparisons #### kysely-vs-drizzle Kysely vs Drizzle ORM for TypeScript: compile-time reference checks, typed JSON and CASE, safe query reuse, and migrating from Drizzle one query at a time. - [Kysely vs Drizzle ORM](https://kysely.dev/docs/comparisons/kysely-vs-drizzle.md): Kysely vs Drizzle ORM for TypeScript: compile-time reference checks, typed JSON and CASE, safe query reuse, and migrating from Drizzle one query at a time. #### kysely-vs-knex Compare Kysely and Knex SQL query builders: TypeScript inference through joins, aliases, and nested results, immutable query reuse, explicit execution, dialect-specific SQL, plugins, and a gradual migration plan. - [Kysely vs Knex](https://kysely.dev/docs/comparisons/kysely-vs-knex.md): Compare Kysely and Knex SQL query builders: TypeScript inference through joins, aliases, and nested results, immutable query reuse, explicit execution, dialect-specific SQL, plugins, and a gradual migration plan. #### kysely-vs-sequelize Kysely vs Sequelize: a Sequelize alternative that type-checks query references, infers result types from the selection, and migrates one query at a time. - [Kysely vs Sequelize](https://kysely.dev/docs/comparisons/kysely-vs-sequelize.md): Kysely vs Sequelize: a Sequelize alternative that type-checks query references, infers result types from the selection, and migrates one query at a time. #### kysely-vs-typeorm Kysely vs TypeORM: a TypeORM alternative that type-checks query references, infers result types from the selection, and migrates one query at a time. - [Kysely vs TypeORM](https://kysely.dev/docs/comparisons/kysely-vs-typeorm.md): Kysely vs TypeORM: a TypeORM alternative that type-checks query references, infers result types from the selection, and migrates one query at a time. #### query-builder-vs-orm Compare SQL query builders and ORMs with TypeScript examples. Learn how Kysely composes typed SQL and when to choose it over a model-based API. - [SQL query builder vs ORM in TypeScript](https://kysely.dev/docs/comparisons/query-builder-vs-orm.md): Compare SQL query builders and ORMs with TypeScript examples. Learn how Kysely composes typed SQL and when to choose it over a model-based API. #### query-builder-vs-raw-sql Compare Kysely with raw SQL in TypeScript: SQL templates, SafeQL, and typed SQL files from PgTyped, Prisma TypedSQL, and sqlc. When a query builder earns its place. - [SQL query builder vs raw SQL in TypeScript](https://kysely.dev/docs/comparisons/query-builder-vs-raw-sql.md): Compare Kysely with raw SQL in TypeScript: SQL templates, SafeQL, and typed SQL files from PgTyped, Prisma TypedSQL, and sqlc. When a query builder earns its place. ### dialects Find built-in and community Kysely dialects for PostgreSQL, MySQL, SQL Server, SQLite, and other databases. - [Dialects](https://kysely.dev/docs/dialects.md): Find built-in and community Kysely dialects for PostgreSQL, MySQL, SQL Server, SQLite, and other databases. ### examples #### cte - [Inserts, updates and deletions](https://kysely.dev/docs/examples/cte/inserts-updates-and-deletions.md): Some databases like postgres also allow you to run other queries than selects - [Simple selects](https://kysely.dev/docs/examples/cte/simple-selects.md): Common table expressions (CTE) are a great way to modularize complex queries. #### delete - [Single row](https://kysely.dev/docs/examples/delete/single-row.md): Delete a single row: #### insert - [Complex values](https://kysely.dev/docs/examples/insert/complex-values.md): In addition to primitives, the values can also be arbitrary expressions. - [Insert subquery](https://kysely.dev/docs/examples/insert/insert-subquery.md): You can create an INSERT INTO SELECT FROM query using the expression method. - [Multiple rows](https://kysely.dev/docs/examples/insert/multiple-rows.md): On dialects that support it (for example PostgreSQL) you can insert multiple - [Returning data](https://kysely.dev/docs/examples/insert/returning-data.md): On supported dialects like PostgreSQL you need to chain returning to the query to get - [Single row](https://kysely.dev/docs/examples/insert/single-row.md): Insert a single row: #### join - [Aliased inner join](https://kysely.dev/docs/examples/join/aliased-inner-join.md): You can give an alias for the joined table like this: - [Complex join](https://kysely.dev/docs/examples/join/complex-join.md): You can provide a function as the second argument to get a join - [Simple inner join](https://kysely.dev/docs/examples/join/simple-inner-join.md): Simple inner joins can be done by providing a table name and two columns to join: - [Subquery join](https://kysely.dev/docs/examples/join/subquery-join.md): You can join a subquery by providing two callbacks: #### merge - [Source row existence](https://kysely.dev/docs/examples/merge/source-row-existence.md): Update a target column based on the existence of a source row: - [Temporary changes table](https://kysely.dev/docs/examples/merge/temporary-changes-table.md): Merge new entries from a temporary changes table: #### select - [A single column](https://kysely.dev/docs/examples/select/a-single-column.md): Select a single column: - [Aliases](https://kysely.dev/docs/examples/select/aliases.md): You can give an alias for selections and tables by appending as the_alias to the name: - [All columns](https://kysely.dev/docs/examples/select/all-columns.md): The selectAll method generates SELECT *: - [All columns of a table](https://kysely.dev/docs/examples/select/all-columns-of-a-table.md): Select all columns of a table: - [Column with a table](https://kysely.dev/docs/examples/select/column-with-a-table.md): Select a single column and specify a table: - [Complex selections](https://kysely.dev/docs/examples/select/complex-selections.md): You can select arbitrary expression including subqueries and raw sql snippets. - [Distinct](https://kysely.dev/docs/examples/select/distinct.md): The API documentation is packed with examples. The API docs are hosted here, - [Distinct on](https://kysely.dev/docs/examples/select/distinct-on.md): The API documentation is packed with examples. The API docs are hosted here, - [Function calls](https://kysely.dev/docs/examples/select/function-calls.md): This example shows how to create function calls. These examples also work in any - [Generic find query](https://kysely.dev/docs/examples/select/generic-find-query.md): A generic type-safe helper function for finding a row by a column value: - [Multiple columns](https://kysely.dev/docs/examples/select/multiple-columns.md): Select multiple columns: - [Nested array](https://kysely.dev/docs/examples/select/nested-array.md): While kysely is not an ORM and it doesn't have the concept of relations, we do provide - [Nested object](https://kysely.dev/docs/examples/select/nested-object.md): While kysely is not an ORM and it doesn't have the concept of relations, we do provide - [Not null](https://kysely.dev/docs/examples/select/not-null.md): Sometimes you can be sure something's not null, but Kysely isn't able to infer #### transactions - [Controlled transaction](https://kysely.dev/docs/examples/transactions/controlled-transaction.md): A controlled transaction allows you to commit and rollback manually, execute - [Controlled transaction /w savepoints](https://kysely.dev/docs/examples/transactions/controlled-transaction-w-savepoints.md): A controlled transaction allows you to commit and rollback manually, execute - [Simple transaction](https://kysely.dev/docs/examples/transactions/simple-transaction.md): This example inserts two rows in a transaction. If an exception is thrown inside #### update - [Complex values](https://kysely.dev/docs/examples/update/complex-values.md): As always, you can provide a callback to the set method to get access - [MySQL joins](https://kysely.dev/docs/examples/update/my-sql-joins.md): MySQL allows you to join tables directly to the "main" table and update - [Single row](https://kysely.dev/docs/examples/update/single-row.md): Update a row in person table: #### where - [Complex where clause](https://kysely.dev/docs/examples/where/complex-where-clause.md): For complex where expressions you can pass in a single callback and - [Conditional where calls](https://kysely.dev/docs/examples/where/conditional-where-calls.md): You can add expressions conditionally like this: - [Object filter](https://kysely.dev/docs/examples/where/object-filter.md): You can use the and function to create a simple equality - [OR where](https://kysely.dev/docs/examples/where/or-where.md): To combine conditions using OR, you can use the expression builder. - [Simple where clause](https://kysely.dev/docs/examples/where/simple-where-clause.md): where method calls are combined with AND: - [Where in](https://kysely.dev/docs/examples/where/where-in.md): Find multiple items using a list of identifiers: ### execution Follow a Kysely query from type-safe query building through plugins, SQL compilation, database execution, and result transformation. - [Execution flow](https://kysely.dev/docs/execution.md): Follow a Kysely query from type-safe query building through plugins, SQL compilation, database execution, and result transformation. ### generating-types Generate Kysely database types from your database schema or Prisma models using tools such as kysely-codegen, kysely-typegen, prisma-kysely, and Kanel. - [Generating types](https://kysely.dev/docs/generating-types.md): Generate Kysely database types from your database schema or Prisma models using tools such as kysely-codegen, kysely-typegen, prisma-kysely, and Kanel. ### getting-started Get started with Kysely: install the package, define database types, configure a dialect, and write your first type-safe SQL queries. - [Getting started](https://kysely.dev/docs/getting-started.md): Get started with Kysely: install the package, define database types, configure a dialect, and write your first type-safe SQL queries. ### integrations #### llms Give coding agents version-matched Kysely API docs, type-checked examples, and query feedback, plus llms.txt and llms-full.txt for documentation discovery. - [LLMs](https://kysely.dev/docs/integrations/llms.md): Give coding agents version-matched Kysely API docs, type-checked examples, and query feedback, plus llms.txt and llms-full.txt for documentation discovery. #### supabase Use Kysely with Supabase by generating database types with the Supabase CLI and converting them with kysely-supabase. - [Supabase](https://kysely.dev/docs/integrations/supabase.md): Use Kysely with Supabase by generating database types with the Supabase CLI and converting them with kysely-supabase. ### intro Meet Kysely, a TypeScript SQL query builder with compile-time type safety, autocompletion, and inferred result types for joins and subqueries. - [Introduction](https://kysely.dev/docs/intro.md): Meet Kysely, a TypeScript SQL query builder with compile-time type safety, autocompletion, and inferred result types for joins and subqueries. ### migrations Write and run Kysely database migrations with up and down functions, migration providers, the Migrator API, and the kysely-ctl CLI. - [Migrations](https://kysely.dev/docs/migrations.md): Write and run Kysely database migrations with up and down functions, migration providers, the Migrator API, and the kysely-ctl CLI. ### playground Try Kysely in an interactive playground and share TypeScript query examples for questions, bug reports, and discussions. - [Playground](https://kysely.dev/docs/playground.md): Try Kysely in an interactive playground and share TypeScript query examples for questions, bug reports, and discussions. ### plugins Configure Kysely plugins for camelCase identifiers, duplicate joins, empty IN lists, and null comparisons. - [Plugin system](https://kysely.dev/docs/plugins.md): Configure Kysely plugins for camelCase identifiers, duplicate joins, empty IN lists, and null comparisons. ### recipes #### conditional-selects Select columns conditionally with the Kysely $if method while preserving type inference for optional fields in query results. - [Conditional selects](https://kysely.dev/docs/recipes/conditional-selects.md): Select columns conditionally with the Kysely $if method while preserving type inference for optional fields in query results. #### data-types Understand compile-time and runtime data types in Kysely, and align your TypeScript column types with values returned by your database driver. - [Data types](https://kysely.dev/docs/recipes/data-types.md): Understand compile-time and runtime data types in Kysely, and align your TypeScript column types with values returned by your database driver. #### deduplicate-joins Prevent duplicate joins in dynamic Kysely queries by configuring DeduplicateJoinsPlugin globally or for an individual query. - [Deduplicate joins](https://kysely.dev/docs/recipes/deduplicate-joins.md): Prevent duplicate joins in dynamic Kysely queries by configuring DeduplicateJoinsPlugin globally or for an individual query. #### expressions Compose type-safe SQL expressions with the Kysely expression builder, including function calls, subqueries, and conditional filters. - [Expressions](https://kysely.dev/docs/recipes/expressions.md): Compose type-safe SQL expressions with the Kysely expression builder, including function calls, subqueries, and conditional filters. #### extending-kysely Extend Kysely with custom type-safe expressions and helpers using Expression, AliasedExpression, and the sql template tag. - [Extending kysely](https://kysely.dev/docs/recipes/extending-kysely.md): Extend Kysely with custom type-safe expressions and helpers using Expression, AliasedExpression, and the sql template tag. #### introspecting-relation-metadata Inspect database tables and views at runtime using the Kysely introspection API to retrieve schema metadata. - [Introspecting relation metadata](https://kysely.dev/docs/recipes/introspecting-relation-metadata.md): Inspect database tables and views at runtime using the Kysely introspection API to retrieve schema metadata. #### logging Configure Kysely query and error logging with built-in log levels or a custom callback for SQL, parameters, and execution duration. - [Logging](https://kysely.dev/docs/recipes/logging.md): Configure Kysely query and error logging with built-in log levels or a custom callback for SQL, parameters, and execution duration. #### raw-sql Use Kysely SQL fragments with bound values, checked references, reusable expressions, and inferred selections, or execute a complete raw statement. - [Raw SQL](https://kysely.dev/docs/recipes/raw-sql.md): Use Kysely SQL fragments with bound values, checked references, reusable expressions, and inferred selections, or execute a complete raw statement. #### relations Nest related rows as JSON objects and arrays in Kysely queries using helpers for PostgreSQL, MySQL, SQL Server, and SQLite. - [Relations](https://kysely.dev/docs/recipes/relations.md): Nest related rows as JSON objects and arrays in Kysely queries using helpers for PostgreSQL, MySQL, SQL Server, and SQLite. #### reusable-helpers Build reusable, type-safe Kysely query helpers with expressions, the expression builder, subqueries, and the sql template tag. - [Reusable helpers](https://kysely.dev/docs/recipes/reusable-helpers.md): Build reusable, type-safe Kysely query helpers with expressions, the expression builder, subqueries, and the sql template tag. #### schemas Work with named database schemas in Kysely using qualified table names and withSchema for grouped tables and multitenant applications. - [Working with schemas](https://kysely.dev/docs/recipes/schemas.md): Work with named database schemas in Kysely using qualified table names and withSchema for grouped tables and multitenant applications. #### splitting-query-building-and-execution Compile Kysely queries without a database connection using DummyDriver, infer result types, and execute compiled queries separately. - [Splitting query building and execution](https://kysely.dev/docs/recipes/splitting-query-building-and-execution.md): Compile Kysely queries without a database connection using DummyDriver, infer result types, and execute compiled queries separately. ### runtimes #### browser Use Kysely in the browser to build type-safe queries and compile SQLite SQL with DummyDriver, without a database connection. - [Browser](https://kysely.dev/docs/runtimes/browser.md): Use Kysely in the browser to build type-safe queries and compile SQLite SQL with DummyDriver, without a database connection. ## Optional - [Kysely API reference](https://kysely-org.github.io/kysely-apidoc/): Reference documentation for Kysely classes, methods, and types, with code examples. --- # Full Documentation Content AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. * [](https://kysely.dev/index.md) * Comparisons # Comparisons Compare SQL query builders, ORMs, SQL embedded in TypeScript, and typed SQL files, and explore the tradeoffs between libraries. ## [📄️SQL query builder vs ORM in TypeScript](https://kysely.dev/docs/comparisons/query-builder-vs-orm.md) [Compare SQL query builders and ORMs with TypeScript examples. Learn how Kysely composes typed SQL and when to choose it over a model-based API.](https://kysely.dev/docs/comparisons/query-builder-vs-orm.md) ## [📄️SQL query builder vs raw SQL in TypeScript](https://kysely.dev/docs/comparisons/query-builder-vs-raw-sql.md) [Compare Kysely with raw SQL in TypeScript: SQL templates, SafeQL, and typed SQL files from PgTyped, Prisma TypedSQL, and sqlc. When a query builder earns its place.](https://kysely.dev/docs/comparisons/query-builder-vs-raw-sql.md) ## [📄️Kysely vs Knex](https://kysely.dev/docs/comparisons/kysely-vs-knex.md) [Compare Kysely and Knex SQL query builders: TypeScript inference through joins, aliases, and nested results, immutable query reuse, explicit execution, dialect-specific SQL, plugins, and a gradual migration plan.](https://kysely.dev/docs/comparisons/kysely-vs-knex.md) ## [📄️Kysely vs Drizzle](https://kysely.dev/docs/comparisons/kysely-vs-drizzle.md) [Kysely vs Drizzle ORM for TypeScript: compile-time reference checks, typed JSON and CASE, safe query reuse, and migrating from Drizzle one query at a time.](https://kysely.dev/docs/comparisons/kysely-vs-drizzle.md) ## [📄️Kysely vs TypeORM](https://kysely.dev/docs/comparisons/kysely-vs-typeorm.md) [Kysely vs TypeORM: a TypeORM alternative that type-checks query references, infers result types from the selection, and migrates one query at a time.](https://kysely.dev/docs/comparisons/kysely-vs-typeorm.md) ## [📄️Kysely vs Sequelize](https://kysely.dev/docs/comparisons/kysely-vs-sequelize.md) [Kysely vs Sequelize: a Sequelize alternative that type-checks query references, infers result types from the selection, and migrates one query at a time.](https://kysely.dev/docs/comparisons/kysely-vs-sequelize.md) [Previous](https://kysely.dev/docs/getting-started.md) [Getting started](https://kysely.dev/docs/getting-started.md) [Next](https://kysely.dev/docs/comparisons/query-builder-vs-orm.md) [SQL query builder vs ORM in TypeScript](https://kysely.dev/docs/comparisons/query-builder-vs-orm.md) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. * [](https://kysely.dev/index.md) * [Examples](https://kysely.dev/docs/category/examples.md) * CTE # CTE Short and simple examples of how to use Common Table Expressions (CTE) in queries. ## [📄️Simple selects](https://kysely.dev/docs/examples/cte/simple-selects.md) [Common table expressions (CTE) are a great way to modularize complex queries.](https://kysely.dev/docs/examples/cte/simple-selects.md) ## [📄️Inserts, updates and deletions](https://kysely.dev/docs/examples/cte/inserts-updates-and-deletions.md) [Some databases like postgres also allow you to run other queries than selects](https://kysely.dev/docs/examples/cte/inserts-updates-and-deletions.md) [Previous](https://kysely.dev/docs/examples/transactions/controlled-transaction-w-savepoints.md) [Controlled transaction /w savepoints](https://kysely.dev/docs/examples/transactions/controlled-transaction-w-savepoints.md) [Next](https://kysely.dev/docs/examples/cte/simple-selects.md) [Simple selects](https://kysely.dev/docs/examples/cte/simple-selects.md) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. * [](https://kysely.dev/index.md) * [Examples](https://kysely.dev/docs/category/examples.md) * DELETE # DELETE Short and simple examples of how to write DELETE queries. ## [📄️Single row](https://kysely.dev/docs/examples/delete/single-row.md) [Delete a single row:](https://kysely.dev/docs/examples/delete/single-row.md) [Previous](https://kysely.dev/docs/examples/update/my-sql-joins.md) [MySQL joins](https://kysely.dev/docs/examples/update/my-sql-joins.md) [Next](https://kysely.dev/docs/examples/delete/single-row.md) [Single row](https://kysely.dev/docs/examples/delete/single-row.md) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. * [](https://kysely.dev/index.md) * Examples # Examples Short and simple examples of how to use Kysely to achieve common tasks. ## [🗃SELECT](https://kysely.dev/docs/category/select.md) [14 items](https://kysely.dev/docs/category/select.md) ## [🗃WHERE](https://kysely.dev/docs/category/where.md) [6 items](https://kysely.dev/docs/category/where.md) ## [🗃JOIN](https://kysely.dev/docs/category/join.md) [4 items](https://kysely.dev/docs/category/join.md) ## [🗃INSERT](https://kysely.dev/docs/category/insert.md) [5 items](https://kysely.dev/docs/category/insert.md) ## [🗃UPDATE](https://kysely.dev/docs/category/update.md) [3 items](https://kysely.dev/docs/category/update.md) ## [🗃DELETE](https://kysely.dev/docs/category/delete.md) [1 item](https://kysely.dev/docs/category/delete.md) ## [🗃MERGE](https://kysely.dev/docs/category/merge.md) [2 items](https://kysely.dev/docs/category/merge.md) ## [🗃Transactions](https://kysely.dev/docs/category/transactions.md) [3 items](https://kysely.dev/docs/category/transactions.md) ## [🗃CTE](https://kysely.dev/docs/category/cte.md) [2 items](https://kysely.dev/docs/category/cte.md) [Previous](https://kysely.dev/docs/migrations.md) [Migrations](https://kysely.dev/docs/migrations.md) [Next](https://kysely.dev/docs/category/select.md) [SELECT](https://kysely.dev/docs/category/select.md) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. * [](https://kysely.dev/index.md) * [Examples](https://kysely.dev/docs/category/examples.md) * INSERT # INSERT Short and simple examples of how to write INSERT queries. ## [📄️Single row](https://kysely.dev/docs/examples/insert/single-row.md) [Insert a single row:](https://kysely.dev/docs/examples/insert/single-row.md) ## [📄️Multiple rows](https://kysely.dev/docs/examples/insert/multiple-rows.md) [On dialects that support it (for example PostgreSQL) you can insert multiple](https://kysely.dev/docs/examples/insert/multiple-rows.md) ## [📄️Returning data](https://kysely.dev/docs/examples/insert/returning-data.md) [On supported dialects like PostgreSQL you need to chain returning to the query to get](https://kysely.dev/docs/examples/insert/returning-data.md) ## [📄️Complex values](https://kysely.dev/docs/examples/insert/complex-values.md) [In addition to primitives, the values can also be arbitrary expressions.](https://kysely.dev/docs/examples/insert/complex-values.md) ## [📄️Insert subquery](https://kysely.dev/docs/examples/insert/insert-subquery.md) [You can create an INSERT INTO SELECT FROM query using the expression method.](https://kysely.dev/docs/examples/insert/insert-subquery.md) [Previous](https://kysely.dev/docs/examples/join/subquery-join.md) [Subquery join](https://kysely.dev/docs/examples/join/subquery-join.md) [Next](https://kysely.dev/docs/examples/insert/single-row.md) [Single row](https://kysely.dev/docs/examples/insert/single-row.md) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. * [](https://kysely.dev/index.md) * Integrations # Integrations Kysely integrations with other libraries, ORMs, and AI assistants. ## [📄️LLMs](https://kysely.dev/docs/integrations/llms.md) [Give coding agents version-matched Kysely API docs, type-checked examples, and query feedback, plus llms.txt and llms-full.txt for documentation discovery.](https://kysely.dev/docs/integrations/llms.md) ## [📄️Supabase](https://kysely.dev/docs/integrations/supabase.md) [Use Kysely with Supabase by generating database types with the Supabase CLI and converting them with kysely-supabase.](https://kysely.dev/docs/integrations/supabase.md) [Previous](https://kysely.dev/docs/recipes/logging.md) [Logging](https://kysely.dev/docs/recipes/logging.md) [Next](https://kysely.dev/docs/integrations/llms.md) [LLMs](https://kysely.dev/docs/integrations/llms.md) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. * [](https://kysely.dev/index.md) * [Examples](https://kysely.dev/docs/category/examples.md) * JOIN # JOIN Examples of queries that use JOINs. ## [📄️Simple inner join](https://kysely.dev/docs/examples/join/simple-inner-join.md) [Simple inner joins can be done by providing a table name and two columns to join:](https://kysely.dev/docs/examples/join/simple-inner-join.md) ## [📄️Aliased inner join](https://kysely.dev/docs/examples/join/aliased-inner-join.md) [You can give an alias for the joined table like this:](https://kysely.dev/docs/examples/join/aliased-inner-join.md) ## [📄️Complex join](https://kysely.dev/docs/examples/join/complex-join.md) [You can provide a function as the second argument to get a join](https://kysely.dev/docs/examples/join/complex-join.md) ## [📄️Subquery join](https://kysely.dev/docs/examples/join/subquery-join.md) [You can join a subquery by providing two callbacks:](https://kysely.dev/docs/examples/join/subquery-join.md) [Previous](https://kysely.dev/docs/examples/where/complex-where-clause.md) [Complex where clause](https://kysely.dev/docs/examples/where/complex-where-clause.md) [Next](https://kysely.dev/docs/examples/join/simple-inner-join.md) [Simple inner join](https://kysely.dev/docs/examples/join/simple-inner-join.md) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. * [](https://kysely.dev/index.md) * [Examples](https://kysely.dev/docs/category/examples.md) * MERGE # MERGE Short and simple examples of how to write MERGE queries. ## [📄️Source row existence](https://kysely.dev/docs/examples/merge/source-row-existence.md) [Update a target column based on the existence of a source row:](https://kysely.dev/docs/examples/merge/source-row-existence.md) ## [📄️Temporary changes table](https://kysely.dev/docs/examples/merge/temporary-changes-table.md) [Merge new entries from a temporary changes table:](https://kysely.dev/docs/examples/merge/temporary-changes-table.md) [Previous](https://kysely.dev/docs/examples/delete/single-row.md) [Single row](https://kysely.dev/docs/examples/delete/single-row.md) [Next](https://kysely.dev/docs/examples/merge/source-row-existence.md) [Source row existence](https://kysely.dev/docs/examples/merge/source-row-existence.md) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. * [](https://kysely.dev/index.md) * Other runtimes # Other runtimes Use Kysely in browsers to build type-safe queries and compile SQL without a database connection. ## [📄️Browser](https://kysely.dev/docs/runtimes/browser.md) [Use Kysely in the browser to build type-safe queries and compile SQLite SQL with DummyDriver, without a database connection.](https://kysely.dev/docs/runtimes/browser.md) [Previous](https://kysely.dev/docs/integrations/supabase.md) [Supabase](https://kysely.dev/docs/integrations/supabase.md) [Next](https://kysely.dev/docs/runtimes/browser.md) [Browser](https://kysely.dev/docs/runtimes/browser.md) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. * [](https://kysely.dev/index.md) * Recipes # Recipes Explore Kysely recipes for reusable helpers, expressions, nested relations, database schemas, logging, and advanced TypeScript types. ## [📄️Relations](https://kysely.dev/docs/recipes/relations.md) [Nest related rows as JSON objects and arrays in Kysely queries using helpers for PostgreSQL, MySQL, SQL Server, and SQLite.](https://kysely.dev/docs/recipes/relations.md) ## [📄️Reusable helpers](https://kysely.dev/docs/recipes/reusable-helpers.md) [Build reusable, type-safe Kysely query helpers with expressions, the expression builder, subqueries, and the sql template tag.](https://kysely.dev/docs/recipes/reusable-helpers.md) ## [📄️Data types](https://kysely.dev/docs/recipes/data-types.md) [Understand compile-time and runtime data types in Kysely, and align your TypeScript column types with values returned by your database driver.](https://kysely.dev/docs/recipes/data-types.md) ## [📄️Raw SQL](https://kysely.dev/docs/recipes/raw-sql.md) [Use Kysely SQL fragments with bound values, checked references, reusable expressions, and inferred selections, or execute a complete raw statement.](https://kysely.dev/docs/recipes/raw-sql.md) ## [📄️Splitting query building and execution](https://kysely.dev/docs/recipes/splitting-query-building-and-execution.md) [Compile Kysely queries without a database connection using DummyDriver, infer result types, and execute compiled queries separately.](https://kysely.dev/docs/recipes/splitting-query-building-and-execution.md) ## [📄️Conditional selects](https://kysely.dev/docs/recipes/conditional-selects.md) [Select columns conditionally with the Kysely $if method while preserving type inference for optional fields in query results.](https://kysely.dev/docs/recipes/conditional-selects.md) ## [📄️Expressions](https://kysely.dev/docs/recipes/expressions.md) [Compose type-safe SQL expressions with the Kysely expression builder, including function calls, subqueries, and conditional filters.](https://kysely.dev/docs/recipes/expressions.md) ## [📄️Working with schemas](https://kysely.dev/docs/recipes/schemas.md) [Work with named database schemas in Kysely using qualified table names and withSchema for grouped tables and multitenant applications.](https://kysely.dev/docs/recipes/schemas.md) ## [📄️Deduplicate joins](https://kysely.dev/docs/recipes/deduplicate-joins.md) [Prevent duplicate joins in dynamic Kysely queries by configuring DeduplicateJoinsPlugin globally or for an individual query.](https://kysely.dev/docs/recipes/deduplicate-joins.md) ## [📄️Extending kysely](https://kysely.dev/docs/recipes/extending-kysely.md) [Extend Kysely with custom type-safe expressions and helpers using Expression, AliasedExpression, and the sql template tag.](https://kysely.dev/docs/recipes/extending-kysely.md) ## [📄️Introspecting relation metadata](https://kysely.dev/docs/recipes/introspecting-relation-metadata.md) [Inspect database tables and views at runtime using the Kysely introspection API to retrieve schema metadata.](https://kysely.dev/docs/recipes/introspecting-relation-metadata.md) ## [📄️Logging](https://kysely.dev/docs/recipes/logging.md) [Configure Kysely query and error logging with built-in log levels or a custom callback for SQL, parameters, and execution duration.](https://kysely.dev/docs/recipes/logging.md) [Previous](https://kysely.dev/docs/examples/cte/inserts-updates-and-deletions.md) [Inserts, updates and deletions](https://kysely.dev/docs/examples/cte/inserts-updates-and-deletions.md) [Next](https://kysely.dev/docs/recipes/relations.md) [Relations](https://kysely.dev/docs/recipes/relations.md) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. * [](https://kysely.dev/index.md) * [Examples](https://kysely.dev/docs/category/examples.md) * SELECT # SELECT Short and simple examples of using the SELECT methods. ## [📄️A single column](https://kysely.dev/docs/examples/select/a-single-column.md) [Select a single column:](https://kysely.dev/docs/examples/select/a-single-column.md) ## [📄️Column with a table](https://kysely.dev/docs/examples/select/column-with-a-table.md) [Select a single column and specify a table:](https://kysely.dev/docs/examples/select/column-with-a-table.md) ## [📄️Multiple columns](https://kysely.dev/docs/examples/select/multiple-columns.md) [Select multiple columns:](https://kysely.dev/docs/examples/select/multiple-columns.md) ## [📄️Aliases](https://kysely.dev/docs/examples/select/aliases.md) [You can give an alias for selections and tables by appending as the\_alias to the name:](https://kysely.dev/docs/examples/select/aliases.md) ## [📄️Complex selections](https://kysely.dev/docs/examples/select/complex-selections.md) [You can select arbitrary expression including subqueries and raw sql snippets.](https://kysely.dev/docs/examples/select/complex-selections.md) ## [📄️Not null](https://kysely.dev/docs/examples/select/not-null.md) [Sometimes you can be sure something's not null, but Kysely isn't able to infer](https://kysely.dev/docs/examples/select/not-null.md) ## [📄️Function calls](https://kysely.dev/docs/examples/select/function-calls.md) [This example shows how to create function calls. These examples also work in any](https://kysely.dev/docs/examples/select/function-calls.md) ## [📄️Distinct](https://kysely.dev/docs/examples/select/distinct.md) [The API documentation is packed with examples. The API docs are hosted here,](https://kysely.dev/docs/examples/select/distinct.md) ## [📄️Distinct on](https://kysely.dev/docs/examples/select/distinct-on.md) [The API documentation is packed with examples. The API docs are hosted here,](https://kysely.dev/docs/examples/select/distinct-on.md) ## [📄️All columns](https://kysely.dev/docs/examples/select/all-columns.md) [The selectAll method generates SELECT \*:](https://kysely.dev/docs/examples/select/all-columns.md) ## [📄️All columns of a table](https://kysely.dev/docs/examples/select/all-columns-of-a-table.md) [Select all columns of a table:](https://kysely.dev/docs/examples/select/all-columns-of-a-table.md) ## [📄️Nested array](https://kysely.dev/docs/examples/select/nested-array.md) [While kysely is not an ORM and it doesn't have the concept of relations, we do provide](https://kysely.dev/docs/examples/select/nested-array.md) ## [📄️Nested object](https://kysely.dev/docs/examples/select/nested-object.md) [While kysely is not an ORM and it doesn't have the concept of relations, we do provide](https://kysely.dev/docs/examples/select/nested-object.md) ## [📄️Generic find query](https://kysely.dev/docs/examples/select/generic-find-query.md) [A generic type-safe helper function for finding a row by a column value:](https://kysely.dev/docs/examples/select/generic-find-query.md) [Previous](https://kysely.dev/docs/category/examples.md) [Examples](https://kysely.dev/docs/category/examples.md) [Next](https://kysely.dev/docs/examples/select/a-single-column.md) [A single column](https://kysely.dev/docs/examples/select/a-single-column.md) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. * [](https://kysely.dev/index.md) * [Examples](https://kysely.dev/docs/category/examples.md) * Transactions # Transactions Short and simple examples of how to use transactions. ## [📄️Simple transaction](https://kysely.dev/docs/examples/transactions/simple-transaction.md) [This example inserts two rows in a transaction. If an exception is thrown inside](https://kysely.dev/docs/examples/transactions/simple-transaction.md) ## [📄️Controlled transaction](https://kysely.dev/docs/examples/transactions/controlled-transaction.md) [A controlled transaction allows you to commit and rollback manually, execute](https://kysely.dev/docs/examples/transactions/controlled-transaction.md) ## [📄️Controlled transaction /w savepoints](https://kysely.dev/docs/examples/transactions/controlled-transaction-w-savepoints.md) [A controlled transaction allows you to commit and rollback manually, execute](https://kysely.dev/docs/examples/transactions/controlled-transaction-w-savepoints.md) [Previous](https://kysely.dev/docs/examples/merge/temporary-changes-table.md) [Temporary changes table](https://kysely.dev/docs/examples/merge/temporary-changes-table.md) [Next](https://kysely.dev/docs/examples/transactions/simple-transaction.md) [Simple transaction](https://kysely.dev/docs/examples/transactions/simple-transaction.md) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. * [](https://kysely.dev/index.md) * [Examples](https://kysely.dev/docs/category/examples.md) * UPDATE # UPDATE Short and simple examples of how to write UPDATE queries. ## [📄️Single row](https://kysely.dev/docs/examples/update/single-row.md) [Update a row in person table:](https://kysely.dev/docs/examples/update/single-row.md) ## [📄️Complex values](https://kysely.dev/docs/examples/update/complex-values.md) [As always, you can provide a callback to the set method to get access](https://kysely.dev/docs/examples/update/complex-values.md) ## [📄️MySQL joins](https://kysely.dev/docs/examples/update/my-sql-joins.md) [MySQL allows you to join tables directly to the "main" table and update](https://kysely.dev/docs/examples/update/my-sql-joins.md) [Previous](https://kysely.dev/docs/examples/insert/insert-subquery.md) [Insert subquery](https://kysely.dev/docs/examples/insert/insert-subquery.md) [Next](https://kysely.dev/docs/examples/update/single-row.md) [Single row](https://kysely.dev/docs/examples/update/single-row.md) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. * [](https://kysely.dev/index.md) * [Examples](https://kysely.dev/docs/category/examples.md) * WHERE # WHERE Short and simple examples of how to use the where method to add a WHERE statement. While most of the examples show a SELECT query, the where method works exactly the same in UPDATE and DELETE queries too. ## [📄️Simple where clause](https://kysely.dev/docs/examples/where/simple-where-clause.md) [where method calls are combined with AND:](https://kysely.dev/docs/examples/where/simple-where-clause.md) ## [📄️Where in](https://kysely.dev/docs/examples/where/where-in.md) [Find multiple items using a list of identifiers:](https://kysely.dev/docs/examples/where/where-in.md) ## [📄️Object filter](https://kysely.dev/docs/examples/where/object-filter.md) [You can use the and function to create a simple equality](https://kysely.dev/docs/examples/where/object-filter.md) ## [📄️OR where](https://kysely.dev/docs/examples/where/or-where.md) [To combine conditions using OR, you can use the expression builder.](https://kysely.dev/docs/examples/where/or-where.md) ## [📄️Conditional where calls](https://kysely.dev/docs/examples/where/conditional-where-calls.md) [You can add expressions conditionally like this:](https://kysely.dev/docs/examples/where/conditional-where-calls.md) ## [📄️Complex where clause](https://kysely.dev/docs/examples/where/complex-where-clause.md) [For complex where expressions you can pass in a single callback and](https://kysely.dev/docs/examples/where/complex-where-clause.md) [Previous](https://kysely.dev/docs/examples/select/generic-find-query.md) [Generic find query](https://kysely.dev/docs/examples/select/generic-find-query.md) [Next](https://kysely.dev/docs/examples/where/simple-where-clause.md) [Simple where clause](https://kysely.dev/docs/examples/where/simple-where-clause.md) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Kysely vs Drizzle ORM Kysely and Drizzle ORM start from the same premise: SQL is the interface, and TypeScript should check it. Both compose statements through a typed API and bind values as parameters, with no generated client. **Both infer the result of a query. Drizzle knows what each column is, and Kysely also knows whether the query can see it.** Both are [well adopted](https://npmx.dev/compare?packages=kysely,drizzle-orm,@prisma/client,typeorm,knex,sequelize,@mikro-orm/core\&facets=downloads), maintained, and lead their category: Drizzle is the most downloaded ORM on npm, and Kysely the most downloaded SQL query builder. **Drizzle brought SQL-first TypeScript to the mainstream, and every SQL-first library, Kysely included, has a bigger audience for it.** Drizzle's builder is SQL-like in clause order and JavaScript in the rest: columns are objects, operators are imported functions, and aliases are variables. Kysely writes SQL's own operators and aliases, and carries the tables in scope through every step, so a reference is checked where it is written. The differences that cost most are the quiet ones. A JSON or CASE expression that Drizzle writes as an annotated template can return a wrong value under a type that still compiles, and in Drizzle's dynamic mode [a second `where()` replaces the first](#shared-queries-branch-without-mutation) with no error, even when the first was a tenant filter. Kysely is a type-safe SQL query builder. Drizzle calls itself [a headless TypeScript ORM](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/overview.mdx#L8). In this site's terms it is a [data framework](https://kysely.dev/docs/comparisons/query-builder-vs-orm.md#orms-data-frameworks-and-plain-objects), the familiar stack: models, which Drizzle calls tables, migrations generated from them, a model API, which Drizzle calls a relational query builder, and a SQL-style query builder. This page compares that builder with Kysely. Drizzle here means 0.45.4 and 1.0.0-rc.5, its stable release and its release candidate in November 2026. Its behavior below is the same in both unless stated. ## Both infer the result of a join[​](#both-infer-the-result-of-a-join "Direct link to Both infer the result of a join") Assume configured Kysely (`db`) and Drizzle (`drizzleDb`) clients over the same two tables: Database interface and Drizzle table objects Kysely's `Database` interface is types only, handwritten or [generated](https://kysely.dev/docs/generating-types.md) from the database: ```ts interface Database { person: { id: number; first_name: string; age: number | null } pet: { id: number; name: string; owner_id: number } } ``` Drizzle's tables are runtime objects, which Drizzle Kit also reads to generate migrations: ```ts import { integer, pgTable, text } from 'drizzle-orm/pg-core' const person = pgTable('person', { id: integer().notNull(), first_name: text().notNull(), age: integer(), }) const pet = pgTable('pet', { id: integer().notNull(), name: text().notNull(), owner_id: integer().notNull(), }) ``` Select adults with their pets' names, keeping people who have no pet. With Drizzle: ```ts import { eq, gte } from 'drizzle-orm' const rows = await drizzleDb .select({ first_name: person.first_name, pet_name: pet.name }) .from(person) .leftJoin(pet, eq(pet.owner_id, person.id)) .where(gte(person.age, 18)) .orderBy(person.first_name) ``` With Kysely: ```ts const rows = await db .selectFrom('person') .leftJoin('pet', 'pet.owner_id', 'person.id') .select(['person.first_name', 'pet.name as pet_name']) .where('person.age', '>=', 18) .orderBy('person.first_name') .execute() ``` The rows match, and so do the inferred types: `{ first_name: string; pet_name: string | null }[]`. Both libraries make `pet_name` nullable because the join is a left join. Drizzle can also [return the pet's columns as a nested object](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/pg/joins.mdx#L278-L279): the statement stays flat, and Drizzle's result mapper groups the columns after the rows arrive, as `null` when every column of the join is. Kysely returns the row as the database shaped it, each joined column nullable on its own, and [nests in SQL](#nested-results-stay-in-the-same-builder) when a nested object is wanted. **Written correctly, the two queries are equivalent. The libraries differ in what the compiler says when a query is wrong.** ## Both check each column, and Kysely also checks the query[​](#both-check-each-column-and-kysely-also-checks-the-query "Direct link to Both check each column, and Kysely also checks the query") Production queries collect their filters. Put the query above in a function with an optional pet name, collecting conditions the way [Drizzle's guide](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/guides/conditional-filters-in-query.mdx#L76-L93) does. Then a later change drops the pet's name from the result, and the join with it: ```ts import { and, eq, gte } from 'drizzle-orm' function matchingPeople(options: { petName?: string }) { const filters = [gte(person.age, 18)] if (options.petName) filters.push(eq(pet.name, options.petName)) return drizzleDb .select({ first_name: person.first_name }) .from(person) .where(and(...filters)) } ``` It compiles, and it runs for every request without a pet name. A request with one fails in PostgreSQL: the filter still reads `pet`, and the change never touched that line. The same function after the same change in Kysely: ```ts function matchingPeople(options: { petName?: string }) { let query = db .selectFrom('person') .select('person.first_name') .where('person.age', '>=', 18) if (options.petName) { // TypeScript error: pet is not available in this query. query = query.where('pet.name', '=', options.petName) // Argument of type '"pet.name"' is not assignable to parameter of type 'ReferenceExpression'. } return query } ``` A Drizzle column is a value. `pet.name` has one type wherever it is passed, `eq()` returns a condition that records no table, and `select()` is called before `from()`, so a selection is typed before the query has a table. Kysely's `selectFrom` comes first, and every later method is typed against the tables and aliases accumulated so far. **With Drizzle, TypeScript accepts a column object in any query. With Kysely, it checks every reference written on the query's own builder.** ### The gap is a design choice[​](#the-gap-is-a-design-choice "Direct link to The gap is a design choice") The gap is structural, not a missing feature, and it is a choice. Asked in 2024 for [a fully type-safe query builder](https://github.com/drizzle-team/drizzle-orm/discussions/2409), Drizzle's team [answered](https://github.com/drizzle-team/drizzle-orm/discussions/2409#discussioncomment-9614641) that it had "deliberately switched to our current API" because "it will provide better DX than huge type errors that are quite hard to understand for average TS developers", and that full type safety would need joins to come before the selection, "deviating the API from SQL even more". By that account, closing the gap means changing the order every query is written in. Kysely's order is the one PostgreSQL [processes a query in](https://www.postgresql.org/docs/current/sql-select.html): the `FROM` list first, the output expressions after it. **Kysely puts `from` first for the reason SQL evaluates it first: a query's inputs have to be known before its outputs can be checked.** Its bet is that a mistake reported at compile time costs less than the same mistake at runtime, for a developer and for a coding agent alike. ### Aliases and CTEs are declared inside the statement[​](#aliases-and-ctes-are-declared-inside-the-statement "Direct link to Aliases and CTEs are declared inside the statement") The same design decides where a name is declared. SQL writes an alias where the table is used, `join person as other`, and so does Kysely: `.innerJoin('person as other', 'other.age', 'person.age')`. In Drizzle a column has to hang off an object before a selection or a join condition can name it, so an alias, a derived table, and a CTE are each declared in a variable ahead of the query. A Drizzle CTE then takes three steps: `$with('adults').as(...)` declares it, `.with(adults)` attaches it, and `.from(adults)` uses it. A query that skips the middle step compiles and fails in PostgreSQL. Kysely's `.with('adults', ...)` declares the CTE and puts it in scope in one call, and `selectFrom('adults')` without it is a type error. **Drizzle keeps SQL's clause order and builds the rest from JavaScript values. Kysely keeps SQL's words, scope, and single statement, and moves one clause to check them.** ### The same split in every clause[​](#the-same-split-in-every-clause "Direct link to The same split in every clause") The split is the same wherever a reference lands. That includes ORDER BY, GROUP BY, HAVING, an update's SET, a delete's WHERE, and these: | Invalid reference | Kysely | Drizzle | | ------------------------------------------------------------------- | ----------------------------------- | ----------------------------------------------------------- | | Select `pet.name` without joining `pet` | TypeScript error. | Passes TypeScript; Drizzle throws while generating the SQL. | | Filter on `pet.name` without joining `pet` | TypeScript error. | Passes TypeScript; PostgreSQL rejects the query. | | Join a subquery aliased `pets`, then compare `pet.owner_id` in `on` | TypeScript error. | Passes TypeScript; PostgreSQL rejects the query. | | Partition a window by a column of a table the query never joined | TypeScript error. | Passes TypeScript; PostgreSQL rejects the query. | | Reference a table the query never joined inside a `sql` fragment | TypeScript error, through `eb.ref`. | Passes TypeScript; PostgreSQL rejects the query. | Drizzle catches the first of these itself, with an error that names the table and asks whether you forgot to join it. The check exists, and it runs while generating the SQL, after the compiler has passed the code. Harminder Virk, the creator of AdonisJS, [documented the first three rows in December 2023](https://github.com/thetutlage/meta/discussions/8), and all three still pass TypeScript in 0.45.4 and 1.0.0-rc.5. **Every row in that table is a failed run with Drizzle and a compile error with Kysely.** PostgreSQL [stops at the first error](https://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY), so unchecked mistakes surface one execution at a time, against a database. The compiler reports them together, before a connection is opened, which is also the loop a coding agent can run on every edit. Operand types, select alias scope, and RETURNING Operands follow the same split. Drizzle's operators are imported functions, `inArray` for `IN` and `ne` for `<>`, and each checks a literal against its column: `eq(person.id, 'one')` is a type error, while `eq(person.first_name, person.id)`, a text column compared with an integer column, compiles and PostgreSQL rejects it. So does `where(and(person.id))`, a column that is not a condition. Kysely takes SQL's operators as strings and completes them in place, and an expression past a plain comparison is written inside an `(eb) => ...` callback. Its expression builder checks an expression against an expression, so `eb('first_name', '=', eb.ref('id'))` is a type error, and so is a condition that is not boolean. PostgreSQL computes `WHERE` and `HAVING` before the selection, so a select alias is not visible to them: Kysely's `where` and `having` reject one at compile time, and `groupBy` and `orderBy` accept it. Drizzle compiles all four. An expression named with `.as('name')` and passed to `where()` is sent as `where "name" = $1`, and PostgreSQL rejects it. Reached through the `where` callback, Drizzle repeats the expression and the query runs. One reference failure is quiet: `returning({ id: pet.id })` on an insert into `person` compiles and returns the person's `id`, because Drizzle writes the column without its table. ### Loud failures and quiet ones[​](#loud-failures-and-quiet-ones "Direct link to Loud failures and quiet ones") Most of these failures are loud once a test runs the branch that builds the reference. The `matchingPeople` function above passes every test that leaves the pet name out. The failures further down this page are quiet: [a misspelled JSON key](#json-traversal) returns `null`, [a CASE without an ELSE](#case-expressions) returns `null` under a `string` type, a `limit()` on one branch of [a shared query](#shared-queries-branch-without-mutation) applies to the other, and a second `where()` drops the first. An unchecked template or a mutated builder returns the wrong result with no error at all. **No query builder is perfectly type-safe, and Kysely is no exception. Type safety is what it is built around, and every gap is treated as work to do.** TypeScript's native compiler widens what that work can afford, and Kysely's direction is to spend that headroom on stricter and more ambitious checks. Where Kysely's checks stop Kysely's check is made where a reference is written, on a builder that knows the query, and it stops there. A reference written with `sql.ref` or as template text, a [dynamic reference](https://kysely-org.github.io/kysely-apidoc/classes/DynamicModule.html), an expression built ahead of time on a standalone `expressionBuilder`, and a helper whose builder parameter declares more tables than the caller's query has are all taken on trust. The reference shorthands `whereRef`, `onRef`, and the three-argument join take two column names without comparing their types. Its scope rules are PostgreSQL's on every dialect. It rejects a select alias in `where` and `having`. MySQL accepts one in `HAVING` and SQLite in `WHERE` as well, and Kysely makes you repeat the expression there. Column objects pay Drizzle back here. An editor can rename one and jump to its declaration, and Drizzle qualifies it with its table in a join. Kysely's references are strings read by the type system: completed and checked, yet an unqualified `id` after joining two tables that both have one compiles, and PostgreSQL rejects it as ambiguous. `where('age', '=', null)` compiles and matches no rows, where Drizzle's `eq(person.age, null)` is a type error. That is by design: Kysely builds the comparison as written, and `= null` is valid SQL. Code that filters on a nullable variable adds the built-in [`SafeNullComparisonPlugin`](https://kysely.dev/docs/plugins.md#safe-null-comparison-plugin), which rewrites `=` to `IS` when the value is null, and nothing is rewritten without it. One Kysely gap is quiet: a `union` whose sides list the same columns in a different order returns values under the wrong keys, where Drizzle throws before sending it. ## Kysely builds the expressions Drizzle writes as templates[​](#kysely-builds-the-expressions-drizzle-writes-as-templates "Direct link to Kysely builds the expressions Drizzle writes as templates") Past selections, joins, filters, and plain aggregates, Drizzle's builder hands over to its [`sql` template](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/pg/sql.mdx#L25). JSON traversal, CASE, aggregate FILTER, and window clauses are SQL text with a result type declared by hand. Kysely has a builder for each, so the references are checked, and for JSON and CASE the type is inferred. ### JSON traversal[​](#json-traversal "Direct link to JSON traversal") A `user_settings.profile` column holds JSON typed as `Profile`, which is `{ addresses: { city: string }[] }`, in both libraries: in Kysely's `Database` interface, and through `jsonb().$type()` on Drizzle's `settings` table object. Read the first address's city. With Drizzle: ```ts import { sql } from 'drizzle-orm' const rows = await drizzleDb .select({ id: settings.id, first_city: sql` ${settings.profile}->'addresses'->0->'city' `.as('first_city'), }) .from(settings) // The string | null type is supplied by hand. ``` With Kysely: ```ts const rows = await db .selectFrom('user_settings') .select('id') .select((eb) => eb.ref('profile', '->').key('addresses').at(0).key('city').as('first_city'), ) .execute() // Inferred: { id: number; first_city: string | null }[] ``` Kysely infers `string | null` because the array may be empty. Now misspell `city` as `ctiy`: ```ts // Drizzle: compiles, runs, and returns null for every row. sql`${settings.profile}->'addresses'->0->'ctiy'` // Kysely: TypeScript error, ctiy is not a key of an address. eb.ref('profile', '->').key('addresses').at(0).key('ctiy') // Argument of type '"ctiy"' is not assignable to parameter of type '"city"'. ``` **A misspelled JSON key is a silent `null` in Drizzle and a compile error in Kysely.** Kysely also rejects reading `city` before indexing `addresses`. Both libraries trust the declared `Profile` type, and neither validates the stored JSON. ### CASE expressions[​](#case-expressions "Direct link to CASE expressions") Label each person by age, including people whose age is unknown. With Drizzle: ```ts import { gte, lt, sql } from 'drizzle-orm' const query = drizzleDb .select({ id: person.id, age_group: sql`case when ${gte(person.age, 18)} then ${'adult'} when ${lt(person.age, 18)} then ${'minor'} else ${'unknown'} end`.as('age_group'), }) .from(person) ``` With Kysely: ```ts const query = db .selectFrom('person') .select('id') .select((eb) => eb .case() .when('age', '>=', 18) .then('adult') .when('age', '<', 18) .then('minor') .else('unknown') .end() .as('age_group'), ) // Inferred: { id: number; age_group: string }[] ``` Both return the same labels. Now remove the `else`. Kysely infers `string | null`, and a caller's `.toUpperCase()` stops compiling until it handles the null. Drizzle's `sql` is unchanged, still claims a string, and a person with no age returns `null`. Drizzle's [own guide](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/guides/update-many-with-different-value.mdx#L17) writes CASE as a template, and the request for [native CASE support](https://github.com/drizzle-team/drizzle-orm/issues/1065) has been open since August 2023. **A `sql` annotation is a claim about the expression. Kysely's inferred type is derived from it.** ### Aggregate filters and windows[​](#aggregate-filters-and-windows "Direct link to Aggregate filters and windows") Count images and videos in one row, the shape [Immich](https://immich.app/) builds with Kysely. Each count is one selection: ```ts // Drizzle: a template. sql`count(*) filter (where ${eq(asset.kind, 'image')})` // Kysely: a builder. eb.fn.countAll().filterWhere('kind', '=', 'image') ``` Both declare `string` here, as `pg` returns a PostgreSQL `bigint` by default, and Kysely's `countAll` takes the type as a parameter and converts nothing. Drizzle's [`count()` with `.where()`](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/guides/count-rows.mdx#L127-L140) and [`db.$count(table, filter)`](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/mdx/%24count-pg.mdx#L3-L15) cover a single conditional count and return it as a `number`. Its `count()` has no FILTER or OVER methods, so several filtered aggregates in one row, or any window, are templates. In Kysely a window is `.over()` on the aggregate, and a partition by a table the query never joined is the fourth row of the table above. **A filtered or windowed aggregate is a template in Drizzle and a builder in Kysely: both declare its result type, and only the builder checks its references against the query.** ## Kysely covers more of SQL's statements[​](#kysely-covers-more-of-sqls-statements "Direct link to Kysely covers more of SQL's statements") Whole statements and clauses follow the same line. Each row below is a method in Kysely, with no builder for it in Drizzle 0.45.4 or 1.0.0-rc.5, and most are requests in Drizzle's issue tracker: | Statement or clause | Kysely | Drizzle | | ----------------------------------------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `WITH RECURSIVE` | `db.withRecursive('tree', ...)` | Requested in [March 2023](https://github.com/drizzle-team/drizzle-orm/issues/209). | | `MATERIALIZED` and `NOT MATERIALIZED` on a CTE | `cte('adults').materialized()` | Requested in [May 2024](https://github.com/drizzle-team/drizzle-orm/issues/2318). | | `MERGE` | `db.mergeInto('person as target')` | Requested in [September 2023](https://github.com/drizzle-team/drizzle-orm/issues/1298). | | `DELETE ... USING`, and `DELETE` with a join on MySQL | `deleteFrom('pet').using('person')`, `.innerJoin(...)` | Requested in [June 2023](https://github.com/drizzle-team/drizzle-orm/issues/793) and [October 2024](https://github.com/drizzle-team/drizzle-orm/issues/3100). | | Row-value `IN`: `(id, owner_id) in ((1, 1), (3, 1))` | `eb(eb.refTuple('id', 'owner_id'), 'in', [eb.tuple(1, 1)])` | Requested in [November 2024](https://github.com/drizzle-team/drizzle-orm/issues/3575); an [earlier request](https://github.com/drizzle-team/drizzle-orm/issues/534) was closed as not planned. | | `NULLS FIRST` and `NULLS LAST` | `orderBy('age', (ob) => ob.desc().nullsLast())` | Requested in [December 2023](https://github.com/drizzle-team/drizzle-orm/issues/1699). | | `IS DISTINCT FROM` | `where('age', 'is distinct from', 40)` | Requested in [December 2023](https://github.com/drizzle-team/drizzle-orm/issues/1733). | | `ON CONFLICT ON CONSTRAINT` | `oc.constraint('pet_pkey').doNothing()` | The conflict target takes columns only. | | `excluded` in `ON CONFLICT DO UPDATE` | `doUpdateSet((eb) => ({ name: eb.ref('excluded.name') }))` | Written as `sql.raw` in the [upsert guide](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/guides/upsert.mdx#L80); a typed form was requested in [December 2023](https://github.com/drizzle-team/drizzle-orm/issues/1728). | | `coalesce` | `eb.fn.coalesce('age', eb.lit(0))` | Requested in [December 2024](https://github.com/drizzle-team/drizzle-orm/issues/3708). | Each of them is a `sql` template in Drizzle today, with the references in it unchecked. The row-value request was closed with the note that `inArray` "shouldn't be used for this purpose according to the Postgres, MySQL and SQLite docs"; PostgreSQL documents the comparison as a [row constructor comparison](https://www.postgresql.org/docs/current/functions-comparisons.html#ROW-WISE-COMPARISON), and Kysely's `refTuple` writes it. Drizzle's builder does cover `exists`, lateral joins, `DISTINCT ON`, and row locks, so the gaps sit at the edges of the language. **Statement coverage is the same difference again: a clause Drizzle writes as text, Kysely writes as a method with its references checked.** ## Kysely's escape hatch keeps references checked[​](#kyselys-escape-hatch-keeps-references-checked "Direct link to Kysely's escape hatch keeps references checked") Kysely does not cover all of SQL either. It covers what applications write most, extends that coverage release by release, and types the escape hatch for the rest. Neither library's `like` takes an `ESCAPE` clause, so both write one in a `sql` template that binds its values as parameters. They differ in what an interpolated reference is: ```ts // Drizzle: compiles. pet is not in the query, and PostgreSQL rejects it. drizzleDb .select({ id: person.id }) .from(person) .where(sql`${pet.name} like ${pattern} escape '!'`) // Kysely: eb.ref is checked against the tables in scope. db.selectFrom('person') .select('id') .where( (eb) => sql`${eb.ref('first_name')} like ${pattern} escape '!'`, ) // Replace first_name with pet.name: TypeScript error, pet is not joined. ``` Neither library checks a fragment's grammar or its declared result type. **Drizzle's `sql` template carries SQL text, bound values, and a declared type, and Kysely's also carries the references `eb.ref` checked.** Wrap repeated fragments in [reusable helpers](https://kysely.dev/docs/recipes/reusable-helpers.md) that take `Expression`. See the [`sql` API](https://kysely-org.github.io/kysely-apidoc/interfaces/Sql.html) for more. For whole queries written as templates, see [query builder vs raw SQL](https://kysely.dev/docs/comparisons/query-builder-vs-raw-sql.md). ## Nested results stay in the same builder[​](#nested-results-stay-in-the-same-builder "Direct link to Nested results stay in the same builder") Return each person with their first two pets by name, as one nested array per row. Drizzle's SQL builder has no JSON helper. Its [joins guide](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/pg/joins.mdx#L358-L393) groups joined rows into nested objects in JavaScript with `reduce`, after they arrive, and nesting in SQL is a `sql` template around a subquery: ```ts import { asc, eq, sql } from 'drizzle-orm' const pets = drizzleDb .select({ name: pet.name }) .from(pet) .where(eq(pet.owner_id, person.id)) .orderBy(asc(pet.name)) .limit(2) const rows = await drizzleDb .select({ first_name: person.first_name, pets: sql<{ name: string }[]>` (select coalesce(json_agg(pet_rows), '[]'::json) from ${pets.as('pet_rows')}) `.as('pets'), }) .from(person) // The { name: string }[] type is supplied by hand. ``` Kysely has a helper for it, `jsonArrayFrom` from `kysely/helpers/postgres`: ```ts import { jsonArrayFrom } from 'kysely/helpers/postgres' const rows = await db .selectFrom('person') .select((eb) => [ 'person.first_name', jsonArrayFrom( eb .selectFrom('pet') .select('pet.name') .whereRef('pet.owner_id', '=', 'person.id') .orderBy('pet.name') .limit(2), ).as('pets'), ]) .execute() // Inferred: { first_name: string; pets: { name: string }[] }[] ``` Both send one statement and return the same rows, `[]` included for a person with no pets. The helper infers its type from the subquery, and the template declares one. Leave out the `coalesce` and the template still claims an array while a person with no pets gets `null`. Rename a key in the subquery, `{ pet_name: pet.name }`, and Drizzle still writes `select "name"`: its selection keys are applied by the result mapper, which never sees the inside of `json_agg`, so the JSON arrives keyed `name` under a type that says `pet_name`. Kysely's `'pet.name as pet_name'` is a SQL alias, and the key and the type change together. The nested subquery is an ordinary Kysely query: join inside it, aggregate it, filter it, with the same methods and the same checks, and `jsonObjectFrom` returns one row as an object, `null` when there is none. **A nested result is a template with a declared type in Drizzle's SQL builder, and a helper with an inferred type in Kysely's.** The helpers are per dialect, and a driver that returns JSON as text needs [`ParseJSONResultsPlugin`](https://kysely.dev/docs/recipes/relations.md#the-json-data-type-and-functions). See [nested relations](https://kysely.dev/docs/recipes/relations.md). A request to [port `jsonArrayFrom` to Drizzle](https://github.com/drizzle-team/drizzle-orm/issues/1338) has been open since October 2023. Drizzle's [relational queries](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/pg/rqb.mdx#L7-L12) are the shorter way to read a declared relation: `findMany` with a `with` clause returns the same nested type in one statement, from a model API beside the SQL builder. A read that needs a join outside the declared relations, a GROUP BY, or an aggregate other than a per-parent count goes back to the SQL builder, as [the docs](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/pg/rqb.mdx#L822) say: "As of now aggregations are not supported in extras, please use core queries for that." There the nesting is the template above. [SQL query builder vs ORM](https://kysely.dev/docs/comparisons/query-builder-vs-orm.md) compares that kind of API with a query builder. ## Shared queries branch without mutation[​](#shared-queries-branch-without-mutation "Direct link to Shared queries branch without mutation") Drizzle mutates the shared base: ```ts import { gte } from 'drizzle-orm' const base = drizzleDb .select({ id: person.id }) .from(person) .where(gte(person.age, 18)) const preview = base.limit(1) const everyone = base // Both now have LIMIT 1. ``` Kysely branches independently: ```ts const base = db.selectFrom('person').select('id').where('age', '>=', 18) const preview = base.limit(1) const everyone = base // everyone has no limit. ``` Drizzle's types assume a query written in one go. Outside [dynamic mode](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/pg/dynamic-query-building.mdx#L19), its types remove a method once it has been called, which the docs say "becomes a problem" for "a shared function that takes a query builder and enhances it". `$dynamic()` lifts that restriction and keeps the mutation, and a second `where()` replaces the first: ```ts import { eq } from 'drizzle-orm' const ownedPets = drizzleDb .select({ id: pet.id }) .from(pet) .where(eq(pet.owner_id, ownerId)) .$dynamic() const named = ownedPets.where(eq(pet.name, 'Catto')) // select "id" from "pet" where "pet"."name" = $1 // The owner filter is gone, from ownedPets too. ``` The query now returns every owner's pets named Catto, with no error. When the first filter is an owner or a tenant scope, that is a data leak. A Drizzle maintainer called this [expected behavior](https://github.com/drizzle-team/drizzle-orm/issues/2321#issuecomment-2429838380) and closed the request to [merge the calls](https://github.com/drizzle-team/drizzle-orm/issues/1644) as not planned. The documented pattern is to [collect conditions](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/guides/conditional-filters-in-query.mdx#L76-L93) and call `where(and(...))` once, with a function that builds a fresh query for each branch. In Kysely each `where()` adds to the last with AND and returns a new builder, so a shared function can add a filter, a join, or a limit without knowing what its caller added. **Sharing a Drizzle builder means building it again. In Kysely, every builder is a value you can share.** Immutability has one trap of its own: a returned builder that is not kept is a change that never happened. Keep each returned builder, and use [`$if`](https://kysely.dev/docs/recipes/conditional-selects.md) when conditional selections change the result type. ## Building a query never executes it[​](#building-a-query-never-executes-it "Direct link to Building a query never executes it") A Drizzle builder is thenable: awaiting it runs the query. That keeps simple calls short, and it means an `async` helper executes a query it meant to return for further composition: ```ts import { gte } from 'drizzle-orm' async function adultQuery() { return drizzleDb .select({ id: person.id }) .from(person) .where(gte(person.age, 18)) } const rows = await adultQuery() // Already executed. These are rows, not a builder to extend. ``` Keep the helper synchronous, or return an object containing the builder to avoid promise assimilation. With Kysely, even an async helper returns a composable builder: ```ts async function adultQuery() { return db.selectFrom('person').select('id').where('age', '>=', 18) } const query = await adultQuery() const rows = await query.where('first_name', '=', 'Jennifer').execute() ``` **A Drizzle builder runs when it is awaited, and a Kysely builder runs when you call `.execute()`.** ### Cancellation, streaming, and controlled transactions are calls on the builder[​](#cancellation-streaming-and-controlled-transactions-are-calls-on-the-builder "Direct link to Cancellation, streaming, and controlled transactions are calls on the builder") Execution also takes a signal. Every query's `execute()` and `stream()` accepts a web-standard [`AbortSignal`](https://kysely-org.github.io/kysely-apidoc/interfaces/AbortableQueryOptions.html), and an option chooses what happens to a query already running: stop waiting, cancel it on the database, or kill its session. The PostgreSQL, MySQL, and MSSQL dialects implement the database side. Drizzle's query API takes no signal in 0.45.4 or 1.0.0-rc.5, and the request for one has been [open since December 2023](https://github.com/drizzle-team/drizzle-orm/issues/1602). Two more execution shapes are calls on the builder. `stream()` returns a select's rows as an async iterable through the PostgreSQL, MySQL, MSSQL, and SQLite dialects, where Drizzle has an `iterator()` for MySQL only and a request [open since April 2023](https://github.com/drizzle-team/drizzle-orm/issues/456). `db.startTransaction().execute()` returns a transaction controlled by `commit()`, `rollback()`, and savepoints, beside the callback form both libraries have and [requested in Drizzle since August 2023](https://github.com/drizzle-team/drizzle-orm/issues/966). Drizzle's callback form nests: a `tx.transaction()` inside another [runs as a savepoint](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/pg/transactions.mdx#L18-L30). Kysely's callback transaction does not nest, and savepoints are calls on the controlled form. Kysely's log event also carries each query's duration, [requested in Drizzle since July 2024](https://github.com/drizzle-team/drizzle-orm/issues/2605). **Cancellation, streaming, and a controlled transaction are methods in Kysely, and each is an open request in Drizzle's issue tracker.** ### One handle type for the database and a transaction[​](#one-handle-type-for-the-database-and-a-transaction "Direct link to One handle type for the database and a transaction") Reusable helpers take a handle. A Kysely helper typed `Kysely` serves the regular instance and a transaction alike, because [`Transaction`](https://kysely-org.github.io/kysely-apidoc/classes/Transaction.html) extends `Kysely`: the same `insertPerson(db, person)` runs as `insertPerson(trx, person)` inside `db.transaction().execute()`, with no second signature. The handle `drizzle()` returns carries a `$client` property that Drizzle's transaction type lacks, so a helper parameter typed `typeof db` rejects `tx` with "Property '$client' is missing". The maintainers [closed the report](https://github.com/drizzle-team/drizzle-orm/issues/3175#issuecomment-5339950219) as not a bug, since "the transaction and database types are different", and the helper is typed with the exported `NodePgDatabase` type instead. **One `Kysely` parameter serves the database and every transaction on it, so a helper is written once.** ## Kysely is extended through its query tree, not its builders[​](#kysely-is-extended-through-its-query-tree-not-its-builders "Direct link to Kysely is extended through its query tree, not its builders") Neither library has a public API for adding methods to its builders, and both are extended with functions. Kysely's `$call` applies a function that takes and returns a builder in the middle of a chain, and anything that implements [`Expression`](https://kysely-org.github.io/kysely-apidoc/interfaces/Expression.html) is accepted wherever Kysely takes an expression, which is how [your own helpers](https://kysely.dev/docs/recipes/extending-kysely.md) add what the builder lacks. Drizzle's helpers do the same by returning `sql`. What only Kysely opens is the query underneath. Before it is SQL, every Kysely query is an immutable tree of [operation nodes](https://kysely-org.github.io/kysely-apidoc/interfaces/OperationNode.html): a select node that holds its joins, its `where`, and its limit as nodes of their own. `toOperationNode()` returns it from any builder, the node types and [`OperationNodeTransformer`](https://kysely-org.github.io/kysely-apidoc/classes/OperationNodeTransformer.html) are exported, and plugins and dialects are interfaces built on it. ### Plugins see the query[​](#plugins-see-the-query "Direct link to Plugins see the query") A [Kysely plugin](https://kysely-org.github.io/kysely-apidoc/interfaces/KyselyPlugin.html) receives that tree before it compiles, and the result after it runs. The [built-in plugins](https://kysely.dev/docs/plugins.md) are written against that interface: they convert camelCase, qualify tables with a schema, deduplicate joins, handle empty `in` lists, make null comparisons safe, and parse JSON results. `withPlugin` scopes one to a query or a derived instance and leaves the original unchanged. Drizzle's extension points are per concern: a [logger](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/pg/goodies.mdx#L23-L24) that receives the SQL text and its parameters, a [cache](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/pg/cache.mdx#L4), [casing](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/pg/sql-schema-declaration.mdx#L203-L207) in the schema declaration, and [custom column types](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/pg/custom-types.mdx#L3) that convert values. A Drizzle builder keeps its clauses in a protected field, and its dialect writes them out as chunks of text, names, columns, and parameters. Neither Drizzle version has an interface that receives the query in between. A custom plugin: a read-only instance A plugin is a class with two methods. This one makes an instance read-only, for a reporting endpoint or a coding agent, by refusing any statement that is not a select: ```ts import { SelectQueryNode, type KyselyPlugin, type PluginTransformQueryArgs, type PluginTransformResultArgs, } from 'kysely' class ReadOnlyPlugin implements KyselyPlugin { transformQuery({ node }: PluginTransformQueryArgs) { if (!SelectQueryNode.is(node)) { throw new Error('This instance is read-only.') } return node } async transformResult({ result }: PluginTransformResultArgs) { return result } } const reports = db.withPlugin(new ReadOnlyPlugin()) ``` The plugin reads the statement itself, so an insert, update, delete, or merge is refused whichever helper built it, before anything is sent. So is a statement written whole as a `sql` template, which reaches it as a raw node. It is a runtime check, not a type error, and it reads the root node: a select that wraps a data-modifying CTE passes, and finding one takes the exported transformer. A read-only database role is still the boundary, and the plugin reports the mistake earlier, in application code. Schema-per-tenant shows the difference. A Drizzle table is bound to its schema when it is declared, and the issue titled "working with dynamic schemas is practically impossible" has been [open since April 2023](https://github.com/drizzle-team/drizzle-orm/issues/423). The [workaround a maintainer gave there](https://github.com/drizzle-team/drizzle-orm/issues/423#issuecomment-1501232679) is a factory that declares each table again for a schema name, `pgSchema(name).table(...)`, with every query built from the tables it returns. In Kysely the schema is chosen per query, by a plugin: ```ts const tenantDb = db.withSchema('tenant_1') // tenantDb.selectFrom('person') compiles to: from "tenant_1"."person" ``` **Drizzle's options cover the cases it names, and Kysely's plugins see the whole query.** ### Dialects are a public interface[​](#dialects-are-a-public-interface "Direct link to Dialects are a public interface") A Kysely [dialect](https://kysely-org.github.io/kysely-apidoc/interfaces/Dialect.html) is four exported factories: a driver, a query compiler, an adapter, and an introspector. A new database implements that interface, and the [community dialects](https://kysely.dev/docs/dialects.md) for BigQuery, ClickHouse, Oracle, and Firebird are built that way. The `Database` interface and the query API are the same types on every dialect, and do not know which one they target: `returning()` compiles on a MySQL instance, and MySQL rejects the statement. Drizzle's dialects ship inside Drizzle, one per database family, each with its own table function, column builders, query builder, and dialect class, and with no shared interface to implement. **A new database implements Kysely's dialect interface. In Drizzle it extends a database Drizzle already ships.** Drizzle's dialect families and third-party databases The families are PostgreSQL, MySQL, SQLite, and SingleStore, plus Gel in 0.45 and MSSQL and CockroachDB in 1.0. Because each has its own builder, its MySQL builder has no `returning()` to call, and a schema is written per family. A [proxy driver](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/pg/connect-drizzle-proxy.mdx#L8) lets you supply the transport for a database Drizzle supports, and does not add one. A third-party database starts from one of the shipped families instead: [drizzle-duckdb](https://www.npmjs.com/package/@duckdbfan/drizzle-duckdb), "based on drizzle's Postgres client", subclasses Drizzle's `PgDialect`, `PgSession`, and `PgDatabase`. ## Migrate from Drizzle to Kysely one query at a time[​](#migrate-from-drizzle-to-kysely-one-query-at-a-time "Direct link to Migrate from Drizzle to Kysely one query at a time") A move from Drizzle to Kysely does not have to happen at once, or at all for the schema. ### Can Kysely and Drizzle be used together?[​](#can-kysely-and-drizzle-be-used-together "Direct link to Can Kysely and Drizzle be used together?") Yes. Keep [Drizzle Kit](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/pg/migrations.mdx#L12) for schema and migrations, and write queries in Kysely against the same database: 1. [Generate Kysely's types](https://kysely.dev/docs/generating-types.md) from the migrated database, in the migration step or in CI. 2. Give both clients the same `pg` pool: `drizzle({ client: pool })` and `new PostgresDialect({ pool })`. 3. Start with a query that shared functions extend, that traverses JSON, or that declares its types through `sql`. Move it, inspect `.compile()`, and compare rows, nulls, ordering, and empty results. 4. Keep each transaction on one client. The two share a pool, not a transaction. On Drizzle 0.45.4, the `Kyselify` type from `drizzle-orm/kysely` also derives Kysely's table types from the Drizzle table objects, with no generation step. 1.0.0-rc.5 no longer ships that export, so generated types are the path that survives the upgrade. ## Other practical considerations[​](#other-practical-considerations "Direct link to Other practical considerations") Schema, migrations, and value conversion One Drizzle declaration is the source for types and for migrations: Drizzle Kit diffs the tables and generates SQL migrations, and can push to or pull from a database. Kysely has no migration generator. Its [migrations](https://kysely.dev/docs/migrations.md) are written by hand through the schema builder or any migration tool, and its types are declared or [generated](https://kysely.dev/docs/generating-types.md) from the database, so a migration applied without regenerating them is drift the compiler cannot see. It also makes the database the source of truth: Kysely queries a schema that another service or migration tool owns, with nothing declared a second time. Drizzle reaches one through [`drizzle-kit pull`](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/pg/drizzle-kit-pull.mdx#L13), which writes the declarations to keep in step with it. Drizzle's columns also convert values, through date modes and [custom types](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/pg/custom-types.mdx#L3), and the same tables derive validation schemas through a package per library: [Zod](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/zod.mdx#L10), [Valibot](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/valibot.mdx#L10), [TypeBox](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/typebox.mdx#L12), and [ArkType](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/arktype.mdx#L10). Each returns that library's own schema object, and Drizzle has no Standard Schema output of its own. Kysely does neither: its types describe what the driver returns, conversion belongs to the driver's configuration or a plugin, and a validator is written separately. The table objects also carry runtime behavior. [`$defaultFn`](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/pg/sql-schema-declaration.mdx#L971-L985) runs when an insert leaves the column out and [`$onUpdateFn`](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/pg/sql-schema-declaration.mdx#L989-L1006) on every update, so an `updated_at` is set by the builder, and [`.mapWith()`](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/pg/sql.mdx#L75-L77) converts one expression's result, which is how `count()` returns a `number`. [`getTableColumns`](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/pg/goodies.mdx#L129-L139) returns a table's columns as a typed object, so a helper can read any table's columns at runtime, and Drizzle's docs spread it to select every column but `password`. That selection widens with each column added to the table, the overfetching and drift of `select *`. Kysely's schema is types only: a default belongs to the database or the caller, a conversion to the driver or a plugin, and a selection names its columns, or `selectAll()` takes them all, with no exclusion form. Drivers, runtimes, and caching Both have zero runtime dependencies and run on Node.js, Deno, Bun, and edge runtimes. Drizzle ships its driver adapters, including Neon, PlanetScale, Cloudflare D1, libSQL, and Bun SQL, inside one package. Kysely's core dialects are PostgreSQL, MySQL, MSSQL, SQLite, and PGlite, and the rest are [organization and community dialects](https://kysely.dev/docs/dialects.md), installed separately. Drizzle also ships a [query cache](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/pg/cache.mdx#L9-L11): `.$withCache()` on one select, or `global: true` for every select, with an [Upstash adapter](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/pg/cache.mdx#L15-L17) and an interface for others, and [a write invalidates](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/pg/cache.mdx#L86-L96) the cached queries that read its tables. Kysely ships no cache. A plugin receives each query and its result, which is where one would be built. Measured package sizes, bundle sizes, and dependency trees | Published package | Compressed download | Unpacked size | Direct dependencies | | ------------------ | ------------------- | ------------- | ------------------- | | Kysely 0.29.8 | 319.6 KiB | 1.66 MiB | 0 | | Drizzle 0.45.4 | 1,205.7 KiB | 10.03 MiB | 0 | | Drizzle 1.0.0-rc.5 | 2,989.0 KiB | 17.02 MiB | 0 | With `pg` 8.23.1, all three resolve to 14 production packages. Drizzle's package includes every driver adapter and database family, and Kysely's includes its five core dialects. A bundler keeps only what an application imports. One PostgreSQL `select * from person`, over the table at the top of this page, bundled and minified with Vite 8.3.6 and leaving `pg` out: | Bundled query | Minified | Gzip | | ------------------ | --------- | -------- | | Kysely 0.29.8 | 156.3 KiB | 30.2 KiB | | Drizzle 0.45.4 | 79.6 KiB | 20.1 KiB | | Drizzle 1.0.0-rc.5 | 137.0 KiB | 36.4 KiB | Drizzle 1.0.0-rc.5 bundles larger than Kysely, and 0.45.4 makes the smallest bundle. Kysely's includes its query tree, query compiler, and schema builder. Measured **November 9, 2026**. Package sizes exclude dependencies, and trees exclude optional dependencies and peer auto-installation. The bundle is one query, not an application, and none of these are install benchmarks. ## Choosing Drizzle or Kysely[​](#choosing-drizzle-or-kysely "Direct link to Choosing Drizzle or Kysely") Drizzle vs Kysely is a choice between two libraries that both put SQL first. What differs is how much of the query the compiler checks, and what else the library does. ### Why use Kysely instead of Drizzle?[​](#why-use-kysely-instead-of-drizzle "Direct link to Why use Kysely instead of Drizzle?") **Choose Kysely when queries are composed, shared, and changed, and you want TypeScript to check each change.** * References are [checked against the query](#both-check-each-column-and-kysely-also-checks-the-query) in every clause, with aliases and CTEs written inside the statement. * JSON and CASE expressions are [built, and their types inferred](#kysely-builds-the-expressions-drizzle-writes-as-templates), and [nested results](#nested-results-stay-in-the-same-builder), filtered aggregates, windows, and [recursive CTEs, `MERGE`, and row-value `IN`](#kysely-covers-more-of-sqls-statements) are built instead of templated. * Builders behave like values: [shared without rebuilding](#shared-queries-branch-without-mutation), [executed only when asked](#building-a-query-never-executes-it), and [cancelled with an `AbortSignal`](#cancellation-streaming-and-controlled-transactions-are-calls-on-the-builder). * Helpers take [one handle type](#one-handle-type-for-the-database-and-a-transaction) for the database and a transaction. * The [query tree is public](#kysely-is-extended-through-its-query-tree-not-its-builders), and plugins and dialects build on it. Its types come from the database itself, so it fits a schema that another tool, service, or team migrates. Immich, Open Collective, and Docmost [compose production queries with it](https://kysely.dev/docs/comparisons/query-builder-vs-raw-sql.md#production-code-draws-the-same-line). ### When is Drizzle the better choice?[​](#when-is-drizzle-the-better-choice "Direct link to When is Drizzle the better choice?") **Keep Drizzle when a person writes the schema and the queries, one TypeScript declaration should drive types, migrations, validation schemas, and relational reads, and the queries are mostly written whole, in one place.** A schema change is one edit there: [`drizzle-kit push`](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/pg/drizzle-kit-push.mdx#L14) applies it to the database without a migration file, and the types, validators, and relational queries follow with no generation step. Chosen for its builder alone, Drizzle trades the checks on this page for column objects an editor can rename, a query cache, and nested callback transactions. That value is priced for a person writing the code. When an agent writes most of it, it writes a migration as SQL as readily as a query, inspects the database through `psql` or a script instead of a GUI, and already knows SQL, where a model API's options are a second vocabulary per library. [OpenClaw's contributor guide](https://github.com/openclaw/openclaw/blob/28340c41f8b88ae6d11488e523808315319747b5/AGENTS.md#L71), written for agents, draws that line: schema and migrations as SQL, queries in Kysely. Drizzle Kit can stay either way, and Kysely can run beside it for the queries that are composed. ### Is Drizzle an ORM or a query builder?[​](#is-drizzle-an-orm-or-a-query-builder "Direct link to Is Drizzle an ORM or a query builder?") **Drizzle is an ORM in the data framework sense: models, generated migrations, relational reads, and a query builder.** Its tables are models under another name: each maps property names to columns and converts values, with relations declared beside it. This page compares its builder with Kysely, which is a query builder only. [SQL query builder vs ORM](https://kysely.dev/docs/comparisons/query-builder-vs-orm.md) covers model APIs like Drizzle's relational queries. ### Is Drizzle type-safe?[​](#is-drizzle-type-safe "Direct link to Is Drizzle type-safe?") **Yes for values and results, and no for scope.** Drizzle infers each row and checks a literal against its column. It does not check that a column belongs to the query: [a column object is accepted in any query](#both-check-each-column-and-kysely-also-checks-the-query). Kysely checks that too, with [gaps of its own](#where-kyselys-checks-stop). ### Is Kysely faster than Drizzle?[​](#is-kysely-faster-than-drizzle "Direct link to Is Kysely faster than Drizzle?") **The database cannot tell them apart: both send one parameterized statement, and [performance belongs to the statement](https://kysely.dev/docs/comparisons/query-builder-vs-raw-sql.md#performance-belongs-to-the-statement-not-the-authoring-tool).** Drizzle describes itself as ["a thin TypeScript layer on top of SQL with almost 0 overhead"](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/pg/perf-queries.mdx#L2-L3), and its [prepared statements](https://github.com/drizzle-team/drizzle-orm-docs/blob/7f7f847a41005aabd08b22fbb3d36030ef968479/src/content/docs/pg/perf-queries.mdx#L14) build the SQL once, with `sql.placeholder()` for the values that change, and reuse it on every call. Kysely has no placeholder API: it builds the statement on each call, and [`.compile()`](https://kysely.dev/docs/recipes/splitting-query-building-and-execution.md) splits building from execution only for a query whose values are fixed. Neither library is benchmarked here. ### Is Kysely smaller than Drizzle?[​](#is-kysely-smaller-than-drizzle "Direct link to Is Kysely smaller than Drizzle?") **Smaller than Drizzle 1.0 in the bundle and as a package, and smaller than stable Drizzle as a package only.** One PostgreSQL query bundles to 36.4 KiB gzipped with Drizzle 1.0.0-rc.5 and 30.2 KiB with Kysely 0.29.8, and Drizzle 0.45.4 bundles to 20.1 KiB. Kysely's published package is a 319.6 KiB download, against 2,989.0 KiB for the release candidate, more than nine times the size, and 1,205.7 KiB for 0.45.4. The [measurements](#measured-sizes) and what they exclude are above. ### Which is easier for a coding agent to use?[​](#which-is-easier-for-a-coding-agent-to-use "Direct link to Which is easier for a coding agent to use?") **Both ship examples where an agent reads them, and Kysely checks more of what the agent writes.** An agent works by editing and running the compiler again, and the checks on this page sit inside that loop: a wrong reference or a misspelled JSON key is a compile error it can read and fix without a database, where Drizzle gives it a failed run or a silent `null`. Drizzle's team [kept its API order](https://github.com/drizzle-team/drizzle-orm/discussions/2409#discussioncomment-9614641) to spare developers "huge type errors that are quite hard to understand", a trade priced for a person reading the error. An agent reads a long type error in the same loop as a short one, and before any query runs. What no loop reports is a `null` that arrives under a `string` type. Each library documents its methods in the type declarations it installs, and each site publishes an `llms.txt`. Kysely's inline examples are [type-checked in CI](https://kysely.dev/docs/integrations/llms.md) against the release they ship with. Try one shared query in each library: a filter that a second function extends, a JSON key it reads, and a join it later drops. Compare what the compiler reports before anything runs, and what the first request reports after. **Both put SQL first. Drizzle types the columns a query uses, and Kysely types the columns and the query.** [Get started with Kysely](https://kysely.dev/docs/getting-started.md), find equivalents in the [query examples](https://kysely.dev/docs/category/examples.md), or compare [query builders with ORMs](https://kysely.dev/docs/comparisons/query-builder-vs-orm.md), [Kysely with TypeORM](https://kysely.dev/docs/comparisons/kysely-vs-typeorm.md), and [Kysely with Sequelize](https://kysely.dev/docs/comparisons/kysely-vs-sequelize.md). Adoption: replacing Drizzle with Kysely OpenClaw's creator, Peter Steinberger, [described replacing Drizzle with Kysely in one of his projects](https://x.com/steipete/status/2005692454553673900). OpenClaw's [contributor guide](https://github.com/openclaw/openclaw/blob/28340c41f8b88ae6d11488e523808315319747b5/AGENTS.md#L71) requires Kysely for ordinary SQLite access, reserving raw SQL for schema, migrations, bootstrap, and justified primitives. --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Kysely vs Knex Kysely comes from the Knex community. Its author, [Sami Koskimäki](https://github.com/koskimas), contributed to Knex [from 2013](https://github.com/knex/knex/issues/39): his [tarn.js](https://github.com/Vincit/tarn.js) became [Knex's connection pool](https://github.com/knex/knex/pull/2450) and still ships with it. He also built [Objection.js](https://github.com/Vincit/objection.js), an ORM [built on Knex](https://github.com/Vincit/objection.js/blob/7297ea886fa41703268c6b766b15cc58fc02497f/README.md#L10). **Kysely was [inspired by Knex](https://github.com/kysely-org/kysely/blob/fe483ef5d7dce62cb99aea17bec20567c986ca16/README.md#L29).** **Both compose SQL through method chains; Knex's types describe your tables, and Kysely's describe your query.** Kysely checks joined references, infers aliased and nested results, lets callers extend a shared query without changing it, and executes only when asked. Knex grew up before TypeScript could type a query builder; Kysely was designed once it could. Knex began in December 2012, three months after [TypeScript's announcement](https://learn.microsoft.com/en-us/archive/blogs/somasegar/typescript-javascript-development-at-application-scale), and took shape in JavaScript. Its [own declarations](https://github.com/knex/knex/issues/2845) arrived in November 2018, eight months after [conditional types and `infer`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#conditional-types) let one type be computed from another, and have improved since, including [registered table types](https://github.com/knex/knex/pull/4071) in 2020, within an API that already existed. Kysely's first commit came in February 2021, three months after [template literal types](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-1.html#template-literal-types) let the compiler read strings like `'pet.name as pet_name'`, and already used them to parse aliases. ## Both start from typed tables[​](#both-start-from-typed-tables "Direct link to Both start from typed tables") Assume configured Kysely and Knex clients with matching table types: Database interface and Knex table registration Use these table shapes for Kysely's `Kysely` instance: ```ts interface Database { person: { id: number; first_name: string; age: number | null } pet: { id: number; name: string; owner_id: number } } ``` Register the same shapes with Knex's [table declarations](https://knexjs.org/guide/#typescript): ```ts declare module 'knex/types/tables.js' { interface Tables { person: Database['person'] pet: Database['pet'] } } ``` `knex('person').select('id', 'first_name')` infers the selected fields correctly with these registered types. ## Kysely's result types follow joins and aliases[​](#kyselys-result-types-follow-joins-and-aliases "Direct link to Kysely's result types follow joins and aliases") Select adults and return each person's name alongside their pet's name. With Knex: ```ts const rows = await knex('person') .innerJoin('pet', 'pet.owner_id', 'person.id') .select('person.first_name', 'pet.name as pet_name') .where('person.age', '>=', 18) .orderBy('person.first_name') ``` With Kysely: ```ts const rows = await db .selectFrom('person') .innerJoin('pet', 'pet.owner_id', 'person.id') .select(['person.first_name', 'pet.name as pet_name']) .where('person.age', '>=', 18) .orderBy('person.first_name') .execute() ``` The rows match; the inferred types differ: | Result | Kysely | Knex 3.3.0 with the registered table types | | ------------------------------------------------------- | -------------------------------------------- | ------------------------------------------ | | The qualified, aliased join above | `{ first_name: string; pet_name: string }[]` | `any[]` | | A simple unqualified selection of `id` and `first_name` | `{ id: number; first_name: string }[]` | `{ id: number; first_name: string }[]` | Knex documents [qualified-column and alias limitations](https://knexjs.org/guide/query-builder.html#select) and offers `knex.ref` for some cases. Kysely parses those strings in its types, so the join's tables and the alias reach the result. **Knex infers the simple selection; Kysely infers the query it grows into.** ## Invalid references fail in TypeScript, not in PostgreSQL[​](#invalid-references-fail-in-typescript-not-in-postgresql "Direct link to Invalid references fail in TypeScript, not in PostgreSQL") With the registered table types, Knex accepts a filter on a table the query never joined: ```ts knex('person').select('id').where('pet.name', '=', 'Catto') ``` PostgreSQL rejects it when it runs. Kysely rejects it as you type: ```ts db.selectFrom('person').select('id').where('pet.name', '=', 'Catto') // Argument of type '"pet.name"' is not assignable to parameter of type 'ReferenceExpression'. // TypeScript error: pet is not available in this query. ``` Other checked failures: | Invalid reference | Kysely | Knex 3.3.0 | | --------------------------------------------------------- | ----------------- | ------------------------------------------------ | | Filter on `pet.name` without joining `pet` | TypeScript error. | Passes TypeScript; PostgreSQL rejects the query. | | Filter on the misspelled `first_nam` | TypeScript error. | Passes TypeScript; PostgreSQL rejects the query. | | Alias `person` as `p`, then filter on `person.first_name` | TypeScript error. | Passes TypeScript; PostgreSQL rejects the query. | **Every row in that table is a round trip with Knex and a compile error with Kysely.** PostgreSQL [stops at the first error](https://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY), so unchecked mistakes surface one execution at a time, against a database. The compiler reports them together, before a connection is opened, which is also the loop a coding agent can run on every edit. ## Nested results keep their shape[​](#nested-results-keep-their-shape "Direct link to Nested results keep their shape") Return each person with an array of their pets' names. With Kysely's `jsonArrayFrom` helper, from `kysely/helpers/postgres`, the subquery's selection becomes the nested type: ```ts const rows = await db .selectFrom('person') .select((eb) => [ 'person.first_name', jsonArrayFrom( eb .selectFrom('pet') .select('pet.name') .whereRef('pet.owner_id', '=', 'person.id') .orderBy('pet.name'), ).as('pets'), ]) .execute() // { first_name: string; pets: { name: string }[] }[] ``` Knex has no JSON aggregation helper, so the aggregate is raw SQL, and the row type is declared by hand: ```ts type PersonWithPets = { first_name: string; pets: { name: string }[] } const rows = await knex('person').select( 'first_name', knex.raw( "(select coalesce(json_agg(json_build_object('name', pet.name) order by pet.name), '[]') from pet where pet.owner_id = person.id) as pets", ), ) ``` The declaration compiles, and so does `pets: number`: nothing compares it with the SQL. Written as a subquery instead, the aggregate is missing from the inferred row either way: a `function () { this.select(...) }` callback drops `pets`, and a `knex('pet')` builder drops it and adds the builder's members to the row. **A declared row type is a claim about the query; Kysely's inferred type is derived from it.** See [nested relations](https://kysely.dev/docs/recipes/relations.md). ## Shared queries branch without mutation[​](#shared-queries-branch-without-mutation "Direct link to Shared queries branch without mutation") Knex mutates the shared base: ```ts const base = knex('person').where('age', '>=', 18) const named = base.where('first_name', '=', 'Jennifer') const everyone = base.select('id', 'first_name') // everyone now includes the Jennifer filter too. ``` Branch with `.clone()`: ```ts const base = knex('person').where('age', '>=', 18) const named = base.clone().where('first_name', '=', 'Jennifer') const everyone = base.clone().select('id', 'first_name') ``` Kysely branches independently: ```ts const base = db.selectFrom('person').where('age', '>=', 18) const named = base.where('first_name', '=', 'Jennifer') const everyone = base.select(['id', 'first_name']) ``` **In Knex, sharing a builder means remembering to clone it; in Kysely, every builder is a value you can share.** Keep each returned Kysely builder, and use [`$if`](https://kysely.dev/docs/recipes/conditional-selects.md) when conditional selections change the result type. ## Building a query never executes it[​](#building-a-query-never-executes-it "Direct link to Building a query never executes it") Knex builders are [thenable](https://knexjs.org/guide/interfaces.html#promises): resolving one as a promise executes the query. An `async` helper can therefore execute a query it intended to return for further composition: ```ts async function adultQuery() { return knex('person').select('id').where('age', '>=', 18) } const rows = await adultQuery() // Already executed. These are rows, not a builder to extend. ``` Keep the helper synchronous, or return an object containing the builder to avoid promise assimilation. With Kysely, even an async helper returns a composable builder: ```ts async function adultQuery() { return db.selectFrom('person').select('id').where('age', '>=', 18) } const query = await adultQuery() const rows = await query.where('first_name', '=', 'Jennifer').execute() ``` **A Knex builder runs when it is awaited; a Kysely builder runs when you call `.execute()`.** `.execute()` returns rows, `.executeTakeFirst()` returns a row or `undefined`, and `.executeTakeFirstOrThrow()` requires a row. Check write-result objects separately when no rows are returned. ## Kysely exposes each database's SQL instead of choosing it for you[​](#kysely-exposes-each-databases-sql-instead-of-choosing-it-for-you "Direct link to Kysely exposes each database's SQL instead of choosing it for you") Kysely's API follows [what you see is what you get](https://kysely.dev/docs/examples/insert/insert-subquery.md): each method writes the SQL its name says, dialects differ in spelling such as quotes and parameter markers rather than in the operation chosen, and the docs flag the rare exception. **Kysely's abstraction is the SQL itself, so there is nothing underneath it to leak.** Knex is a portability layer in places, not a one-to-one SQL API: its upsert and JSON helpers choose different SQL operations for different databases behind one method name. ### One upsert method, two conflict semantics[​](#one-upsert-method-two-conflict-semantics "Direct link to One upsert method, two conflict semantics") ```ts knex('person') .insert({ id: 1, first_name: 'Jennifer' }) .onConflict('id') .merge(['first_name']) ``` Knex 3.3.0 compiles that same chain to: | Database | Upsert clause | | ---------- | ----------------------------------------------------------------------- | | PostgreSQL | `ON CONFLICT ("id") DO UPDATE SET "first_name" = excluded."first_name"` | | MySQL | `ON DUPLICATE KEY UPDATE first_name = values(first_name)` | MySQL has no conflict target, for any library: a duplicate on any unique key triggers the update. Knex [documents this](https://knexjs.org/guide/query-builder.html#onconflict), but the code still reads `.onConflict('id')`. Kysely exposes the two operations separately: ```ts // PostgreSQL / SQLite: explicitly target the id constraint. const pgUpsert = pgDb .insertInto('person') .values({ id: 1, first_name: 'Jennifer' }) .onConflict((oc) => oc .column('id') .doUpdateSet((eb) => ({ first_name: eb.ref('excluded.first_name') })), ) // MySQL: explicitly use its duplicate-key operation. const mysqlUpsert = mysqlDb .insertInto('person') .values({ id: 1, first_name: 'Jennifer' }) .onDuplicateKeyUpdate((eb) => ({ first_name: eb.fn('values', [eb.ref('first_name')]), })) ``` ### One JSON method, three database functions[​](#one-json-method-three-database-functions "Direct link to One JSON method, three database functions") Knex's [`jsonExtract`](https://knexjs.org/guide/query-builder.html#jsonextract) also hides different operations behind one method: ```ts knex('person').jsonExtract('profile', '$.name', 'name') ``` For a JSON `profile` column, Knex 3.3.0 emits these expressions: | Database | Generated expression (path bound as a parameter) | | ---------- | ------------------------------------------------ | | PostgreSQL | `jsonb_path_query("profile", ?)` | | MySQL | `json_unquote(json_extract(profile, ?))` | | SQLite | `json_extract(profile, ?)` | PostgreSQL's `jsonb_path_query` is set-returning; this is more than changing identifier quotes or parameter markers. With `profile` typed `{ name: string }`, Kysely writes the operator you choose and types the result: ```ts // PostgreSQL: "profile"->>'name' const pgName = pgDb .selectFrom('person') .select((eb) => eb.ref('profile', '->>').key('name').as('name')) // MySQL / SQLite: ->>'$."name"' const mysqlName = mysqlDb .selectFrom('person') .select((eb) => eb.ref('profile', '->>$').key('name').as('name')) ``` **Knex picks the SQL for each database behind one method name; Kysely puts the choice in your code, where review can see it.** For an application that targets one database, that is the SQL you meant. For one codebase shipped on several databases, Knex's helpers are the feature, and their dialect differences are the cost to test. ## Kysely's escape hatch keeps references checked[​](#kyselys-escape-hatch-keeps-references-checked "Direct link to Kysely's escape hatch keeps references checked") Both cover [CTEs, set operations, ranking, and locks](https://knexjs.org/guide/query-builder.html). For filtered aggregate counts, which [Immich](https://immich.app/) builds with Kysely, Kysely provides `fn.countAll().filterWhere(...)`, and aggregate builders also support `.over(...)`. Knex needs `raw` for `FILTER`, alongside dedicated ranking APIs. Kysely does not cover all of SQL either; it covers what applications write most, extends that coverage release by release, and types the escape hatch for the rest. Knex's raw fragments use MySQL-style `?` value placeholders and `??` [identifier bindings](https://knexjs.org/guide/raw.html#raw-parameter-binding), even when targeting PostgreSQL: ```ts knex.raw('?? = ?', ['person.first_name', 'Jennifer']) // PostgreSQL: "person"."first_name" = $1 // Bindings: ['Jennifer'] ``` The bindings live in a separate array from the placeholders they fill, and literal question marks need escaping. Kysely puts references and values where they belong in the expression: ```ts import { sql, type SqlBool } from 'kysely' db.selectFrom('person') .select('id') .where((eb) => sql`${eb.ref('person.first_name')} = ${'Jennifer'}`) ``` `eb.ref` is checked against the tables in scope, the value binds as a parameter, and the declared type flows into the query. **Knex's raw fragment carries SQL text and bindings; Kysely's `sql` template also carries checked references and a result type.** Wrap repeated fragments in [reusable helpers](https://kysely.dev/docs/recipes/reusable-helpers.md) that take `Expression`; see the [`sql` API](https://kysely-org.github.io/kysely-apidoc/interfaces/Sql.html) for more. ## Kysely's plugins transform the query, not its strings[​](#kyselys-plugins-transform-the-query-not-its-strings "Direct link to Kysely's plugins transform the query, not its strings") Knex's extension points are hooks on each instance. [`wrapIdentifier`](https://knexjs.org/guide/#wrapidentifier) receives each identifier as a string, and [`postProcessResponse`](https://knexjs.org/guide/#postprocessresponse) receives each raw result. Together they cover the common case, camelCase properties over snake\_case columns, with conversion functions you supply: ```ts const knex = knexFactory({ client: 'pg', connection, wrapIdentifier: (value, origImpl) => origImpl(toSnakeCase(value)), postProcessResponse: (result) => toCamelCaseKeys(result), }) ``` Kysely ships that conversion as [`CamelCasePlugin`](https://kysely-org.github.io/kysely-apidoc/classes/CamelCasePlugin.html), with the database interface written in camelCase: ```ts const camelDb = new Kysely({ dialect, plugins: [new CamelCasePlugin()], }) ``` A [Kysely plugin](https://kysely-org.github.io/kysely-apidoc/interfaces/KyselyPlugin.html) receives the query as a tree of operation nodes before it compiles, and the result after it runs, so it can rewrite tables, joins, and expressions, not only identifier text. The [built-in plugins](https://kysely.dev/docs/plugins.md) also qualify tables with a schema, deduplicate joins, handle empty `in` lists, make null comparisons safe, and parse JSON results. `withPlugin` scopes a plugin to one query or a derived instance and leaves the original unchanged: ```ts const tenantDb = db.withPlugin(new WithSchemaPlugin('tenant_1')) ``` Knex's hooks are fixed per instance, with [`queryContext`](https://knexjs.org/guide/query-builder.html#querycontext) to pass per-query data into them. **Knex's hooks see strings and rows; Kysely's plugins see the query.** Custom methods differ the same way. Knex's [`QueryBuilder.extend`](https://knexjs.org/guide/query-builder.html#extending-query-builder), documented as experimental, adds a method to every query builder in the process, typed through module augmentation. Kysely adds behavior through functions that take and return builders, applied with `$call` or as [reusable helpers](https://kysely.dev/docs/recipes/reusable-helpers.md), with nothing registered globally. ## Kysely's dialects are a public interface[​](#kyselys-dialects-are-a-public-interface "Direct link to Kysely's dialects are a public interface") A Kysely [dialect](https://kysely-org.github.io/kysely-apidoc/interfaces/Dialect.html) is four exported factories: a driver, a query compiler, an adapter, and an introspector. A new database implements that interface, often extending the exported `DefaultQueryCompiler` or a built-in dialect's compiler and overriding what its SQL spells differently. The [21 community dialects](https://kysely.dev/docs/dialects.md) are built that way, with no internals to reach into. Knex accepts a custom client class through its `client` option, but its query compilers, schema compilers, and formatter are not part of its public API or its type declarations. Third-party dialects build on them anyway. [knex-firebird-dialect](https://www.npmjs.com/package/knex-firebird-dialect) imports `knex/lib/client`, `knex/lib/formatter`, and `knex/lib/schema/tablecompiler`, then assigns its overrides onto their prototypes; [Beekeeper Studio](https://www.beekeeperstudio.io/)'s DuckDB client extends `knex/lib/client` and builds its query compiler on Knex's internal SQLite one. **Kysely's dialects plug into its public interface; Knex's patch its internals.** ## Kysely has zero dependencies and runs wherever JavaScript does[​](#kysely-has-zero-dependencies-and-runs-wherever-javascript-does "Direct link to Kysely has zero dependencies and runs wherever JavaScript does") **Kysely has no runtime dependencies; Knex 3.3.0 has 14.** Knex's count includes its bundled migration CLI and connection pool; Kysely's CLI is a separate package, and its pool comes from the driver. Kysely's core requires no Node.js-specific APIs, so the same package runs on [Node.js, Deno, Bun, Cloudflare Workers, and in browsers](https://github.com/kysely-org/kysely/blob/fe483ef5d7dce62cb99aea17bec20567c986ca16/README.md#L29-L31) wherever a dialect can reach the database. Knex describes itself as a query builder [for Node.js](https://github.com/knex/knex/blob/e25d54bcb707714a17f5a5744eba5c4246bb4d1d/README.md#L12-L13), and its library loads Node.js modules such as `fs` and `path`. ## Migrate one query at a time[​](#migrate-one-query-at-a-time "Direct link to Migrate one query at a time") Start with a query whose joined aliases lose inference, or a base query that several callers extend. [kysely-knex](https://github.com/kysely-org/kysely-knex) reuses a Knex instance, translates table types, and integrates migrations, so both builders can share one pool during the move. 1. Start with `Kysely` or [generated](https://kysely.dev/docs/generating-types.md)/handwritten types matching driver values and nullability. 2. Reuse Knex through the bridge, or configure a [native dialect](https://kysely.dev/docs/dialects.md). A second pool needs connection capacity. 3. Translate one read, add `.execute()`, inspect `.compile()`, and compare rows, ordering, and empty results. 4. Replace `wrapIdentifier` and `postProcessResponse` with `CamelCasePlugin` or a custom plugin, and `QueryBuilder.extend` methods with helper functions. 5. Check write results, conflict handling, and dialect differences. Keep each transaction on one client/connection. 6. Once Knex queries and tooling are retired, switch the bridge to a native dialect and close the unused pool. ### Start with Kysely\[​](#start-with-kyselyany "Direct link to Start with Kysely") Schema types can come later, as queries migrate: ```ts import { Kysely } from 'kysely' const untypedDb = new Kysely({ dialect }) const rows = await untypedDb .selectFrom('person') .select(['id', 'first_name']) .where('age', '>=', 18) .execute() ``` `Kysely` keeps composition, immutability, binding, and explicit execution. It gives up schema checks, schema-aware completion, and inferred column types until the types arrive. JavaScript works too; the compile-time checks require TypeScript. ### Keep migration history intact[​](#keep-migration-history-intact "Direct link to Keep migration history intact") Existing Knex migrations can stay where they are. kysely-knex's [`KyselyFsMigrationSource`](https://github.com/kysely-org/kysely-knex/blob/32cfe182cf2ed660df765e8416d5605739fded56/README.md#L85-L90) is a Knex [custom migration source](https://knexjs.org/guide/migrations.html#custom-migration-sources) that passes a Kysely instance to each migration, so new migrations can use Kysely's [schema builder](https://kysely.dev/docs/migrations.md) while `knex migrate:latest` and the `knex_migrations` history keep working. To leave the Knex CLI later, kysely-ctl's `migrate` and `seed` commands [mirror Knex's](https://github.com/kysely-org/kysely-ctl/blob/1fa8c6fae8ada0e6b67bdbf49bc5174a68aeba0f/README.md#L23), and its `getKnexTimestampPrefix` keeps Knex's file naming. Kysely's migrator records history in its own `kysely_migration` table and does not translate Knex migration files, so the switch is a one-time cutover, not a configuration change. ## Other practical considerations[​](#other-practical-considerations "Direct link to Other practical considerations") Dialects and bundled tooling Knex ships [PostgreSQL, MariaDB, MySQL, CockroachDB, MSSQL, SQLite, and Oracle](https://github.com/knex/knex/blob/e25d54bcb707714a17f5a5744eba5c4246bb4d1d/README.md#L12-L13) in one package, with a migration and seed CLI. Kysely's core dialects are PostgreSQL, MySQL, MSSQL, SQLite, and PGlite; others, including Oracle, are [community dialects](https://kysely.dev/docs/dialects.md). Its CLI, kysely-ctl, is a separate package. Measured package sizes and dependency trees PostgreSQL production trees, including transitive dependencies: | PostgreSQL setup | Unique production packages | | ------------------------- | -------------------------- | | Kysely 0.29.7 + pg 8.23.1 | **14** | | Knex 3.3.0 + pg 8.23.1 | 36 | Knex's own download is smaller: **215.3 KiB vs 318.3 KiB**. Kysely's edge is fewer dependencies. The [kysely-knex bridge](https://github.com/kysely-org/kysely-knex) retains Knex's tree. Measured **October 24, 2026**. Package sizes exclude dependencies; trees exclude optional dependencies and peer auto-installation. These are not bundle sizes or install benchmarks. ## Choosing Knex or Kysely[​](#choosing-knex-or-kysely "Direct link to Choosing Knex or Kysely") **Choose Kysely when your queries change and you want TypeScript to check each change: types that follow the query through joins, aliases, nested results, and references; builders that behave like values, shared without cloning and executed only when asked; and an open, dependency-free core for plugins, dialects, and runtimes.** Its method docs and examples are version-matched in the package, so editors and coding agents read the API you installed. **Keep Knex when one codebase must run unchanged on several databases and its portability helpers do that work, or when its queries already work and rarely change.** Its migrations can stay either way. Kysely is also the more downloaded of the two: npm counted [28.8 million Kysely downloads](https://api.npmjs.org/downloads/point/2026-10-31:2026-11-06/kysely) and [6.8 million Knex downloads](https://api.npmjs.org/downloads/point/2026-10-31:2026-11-06/knex) in the week of October 31, 2026. Both counts include installs pulled in by other packages. **Kysely is Knex's idea, SQL composed through method chains, with TypeScript checking every link.** [Get started with Kysely](https://kysely.dev/docs/getting-started.md), find equivalents in the [query examples](https://kysely.dev/docs/category/examples.md), or compare [query builders with raw SQL](https://kysely.dev/docs/comparisons/query-builder-vs-raw-sql.md), [Kysely with Drizzle](https://kysely.dev/docs/comparisons/kysely-vs-drizzle.md), [Kysely with TypeORM](https://kysely.dev/docs/comparisons/kysely-vs-typeorm.md), and [Kysely with Sequelize](https://kysely.dev/docs/comparisons/kysely-vs-sequelize.md). --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Kysely vs Sequelize Kysely and Sequelize both build SQL from TypeScript. Sequelize describes a query as an options object on a model, such as `findAll({ attributes, include, where, group })`, and types it through the model. Its `where` keys are checked, and the strings in `col()`, `order`, `group`, and `'$pets.name$'` are passed through. Kysely describes the query as SQL's clauses and derives the result type from the selection. **Kysely's types describe the query itself, from each reference it names to the rows it returns.** Both are [well adopted](https://npmx.dev/compare?packages=kysely,drizzle-orm,@prisma/client,typeorm,knex,sequelize,@mikro-orm/core\&facets=downloads) and maintained. Sequelize has been on npm since 2011, and by its own description it is an ORM for [PostgreSQL, MySQL, MariaDB, SQLite, SQL Server, Oracle, Db2, Db2 for IBM i, and Snowflake](https://github.com/sequelize/sequelize/blob/53d1e8a6199fff85a8d6cd7d9bf0f3487f0cf798/README.md#L13), with transactions, relations, eager and lazy loading, and read replication. **Sequelize is one of the longest-running ORMs in JavaScript, and still one of the most installed.** The differences that cost most are the quiet ones. On Sequelize 6, a caller's `where` on a scope's attribute [replaces the scope's filter](#kysely-keeps-every-filter-a-caller-adds). An attribute renamed in `attributes` is still [typed under its old name](#result-types-come-from-the-selection), `findAndCountAll()` with an include [counts joined rows](#kysely-pages-parents-in-one-statement), and every finder [writes its values into the SQL text](#kysely-sends-values-as-parameters), where a log or an error report picks them up. Each happens with no error. ## This page compares Sequelize's finders[​](#this-page-compares-sequelizes-finders "Direct link to This page compares Sequelize's finders") Kysely is a type-safe SQL query builder. In this site's terms Sequelize is a [data framework](https://kysely.dev/docs/comparisons/query-builder-vs-orm.md#orms-data-frameworks-and-plain-objects): models, a model API, migrations, and hooks. It has no SQL query builder, by design. The request for [a query builder](https://github.com/sequelize/sequelize/issues/394) has been open since January 2013, and asked to support `MERGE`, a maintainer [answered](https://github.com/sequelize/sequelize/issues/15547#issuecomment-1382268336) "For better or worse, this library is not a query builder, so we don't provide APIs to generate specific queries. We're on a higher abstraction layer". Sequelize code composes its queries in the finders, `findAll()`, `findOne()`, `count()`, and the rest, configured by an options object, so this page sets those against Kysely. [SQL query builder vs ORM](https://kysely.dev/docs/comparisons/query-builder-vs-orm.md) covers model instances and persistence. Sequelize here means 6.37.8, the release npm installs, and 7.0.0-alpha.48, the latest prerelease of its next major, in November 2026. The behavior below holds on both unless a sentence says otherwise, and [waiting for Sequelize 7 or moving to Kysely](#should-i-wait-for-sequelize-7-or-move-to-kysely) covers what 7 changes. ## Both build the same grouped count[​](#both-build-the-same-grouped-count "Direct link to Both build the same grouped count") Assume configured Kysely (`db`) and Sequelize clients over the same two tables: Database interface and Sequelize models Kysely's `Database` interface is types only, handwritten or [generated](https://kysely.dev/docs/generating-types.md) from the database: ```ts interface Database { person: { id: number first_name: string age: number | null pet_target: number } pet: { id: number; name: string; owner_id: number } } ``` Sequelize's models are classes typed with its inference helpers and initialized with their attributes: ```ts import { DataTypes, Model, type InferAttributes, type InferCreationAttributes, type NonAttribute, } from 'sequelize' class Person extends Model< InferAttributes, InferCreationAttributes > { declare id: number declare first_name: string declare age: number | null declare pet_target: number declare pets?: NonAttribute } class Pet extends Model, InferCreationAttributes> { declare id: number declare name: string declare owner_id: number } Person.init( { id: { type: DataTypes.INTEGER, primaryKey: true }, first_name: { type: DataTypes.TEXT, allowNull: false }, age: { type: DataTypes.INTEGER, allowNull: true }, pet_target: { type: DataTypes.INTEGER, allowNull: false }, }, { sequelize, modelName: 'Person', tableName: 'person', timestamps: false }, ) Pet.init( { id: { type: DataTypes.INTEGER, primaryKey: true }, name: { type: DataTypes.TEXT, allowNull: false }, owner_id: { type: DataTypes.INTEGER, allowNull: false }, }, { sequelize, modelName: 'Pet', tableName: 'pet', timestamps: false }, ) Person.hasMany(Pet, { as: 'pets', foreignKey: 'owner_id' }) ``` Sequelize 7 imports the same names from `@sequelize/core`. Count each person's pets, keeping people who have none. With Sequelize: ```ts const rows = await Person.findAll({ attributes: ['id', 'first_name', [fn('COUNT', col('pets.id')), 'pet_count']], include: [{ model: Pet, as: 'pets', attributes: [] }], group: ['Person.id'], order: [['id', 'ASC']], raw: true, }) // Typed as the model: no pet_count. ``` With Kysely: ```ts const rows = await db .selectFrom('person') .leftJoin('pet', 'pet.owner_id', 'person.id') .select(['person.id', 'person.first_name']) .select((eb) => eb.fn.count('pet.id').as('pet_count')) .groupBy('person.id') .orderBy('person.id') .execute() // Inferred: { id: number; first_name: string; pet_count: string | number | bigint }[] ``` The rows match. Sequelize types raw results as the model, `Person[]` on 6 and its attributes on 7, so `pet_count` is missing from the type and the selected attributes do not narrow it. Kysely derives the row from the selection, and types `count` as every type a driver can return for it until you declare one with `count()` or a cast. **Written correctly, the two queries are equivalent, and only Kysely's has a result type derived from the query.** ## Kysely checks the references Sequelize takes as strings[​](#kysely-checks-the-references-sequelize-takes-as-strings "Direct link to Kysely checks the references Sequelize takes as strings") Sequelize's `where` object is typed when the model declares its attributes, as the classes above do: `where: { first_nam: 'Jennifer' }` is a type error, and so are the values `update()` and `create()` take for a model. Sequelize 7 also checks the attribute names in `attributes`. [sequelize-typescript](https://github.com/sequelize/sequelize-typescript), whose decorators declare the same `Model` classes, writes [`class Person extends Model {}`](https://github.com/sequelize/sequelize-typescript/blob/8ded61aa26e192b455c682377d45cef0582e11e2/README.md#L96-L103) as its default form. That form types the attributes as `any`, so the misspelled `where` key compiles, until the class passes an attributes interface to `Model`. The rest of a finder names columns as strings. `col()` and `fn()` take any text, `order` and `group` take column names, `'$pets.name$'` filters on an included table, and an include names its association by alias. A join without a declared association, a computed column, a subquery, a CTE, a set operation, or a window function leaves the options object for `literal()`, which inserts [arbitrary content without escaping](https://github.com/sequelize/website/blob/843c76173ebd444c58706da53ed8c006a7b4f6d5/versioned_docs/version-6.x.x/other-topics/sub-queries.md#L114) and, in Sequelize's own words, "may be a source of (major) security vulnerabilities". Sequelize 7's `sql` tag escapes its values, and its row type is still declared by hand. That is where a [model API runs out into SQL](https://kysely.dev/docs/comparisons/query-builder-vs-orm.md#query-builder-composition-survives-changing-requirements). In Kysely each of them is a method on the same builder, with its references checked like the rest of the query. Production queries collect their filters. Write a lookup with an optional pet name, and later drop the include that loaded the pets: ```ts function matchingPeople(options: { petName?: string }) { const where: WhereOptions = { age: { [Op.gte]: 18 } } if (options.petName) { where['$pets.name$'] = options.petName } return Person.findAll({ attributes: ['first_name'], where, raw: true }) } ``` It compiles, and it runs for every request without a pet name. A request with one fails in PostgreSQL: the filter still reads `pets`, and the change never touched that line. The same function after the same change in Kysely: ```ts function matchingPeople(options: { petName?: string }) { let query = db .selectFrom('person') .select('person.first_name') .where('person.age', '>=', 18) if (options.petName) { // TypeScript error: pet is not available in this query. query = query.where('pet.name', '=', options.petName) // Argument of type '"pet.name"' is not assignable to parameter of type 'ReferenceExpression'. } return query } ``` Kysely's `selectFrom` comes first, and every later method is typed against the tables and aliases accumulated so far. **Kysely checks every reference written on the query's own builder, in each place Sequelize takes a string.** ### The same split in every option[​](#the-same-split-in-every-option "Direct link to The same split in every option") | Invalid reference | Kysely | Sequelize | | -------------------------------------------------- | ----------------- | ------------------------------------------------------------------ | | Select `col('pets.name')` without including `pets` | TypeScript error. | Passes TypeScript, fails in PostgreSQL. | | Filter on `'$pets.name$'` without including `pets` | TypeScript error. | Passes TypeScript, fails in PostgreSQL. | | Order or group by the misspelled `first_nam` | TypeScript error. | Passes TypeScript, fails in PostgreSQL. | | Select the misspelled attribute `first_nam` | TypeScript error. | Passes TypeScript and fails in PostgreSQL on 6. A type error on 7. | | Include the misspelled association `petz` | TypeScript error. | Passes TypeScript, and Sequelize throws before sending it. | | Compare the integer column `age` with `'old'` | TypeScript error. | Passes TypeScript, fails in PostgreSQL on 6 and in Sequelize on 7. | **Every row in that table is a compile error with Kysely, and on Sequelize 6 a failed request.** PostgreSQL [stops at the first error](https://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY), so unchecked mistakes surface one execution at a time, against a database. The compiler reports them together, before a connection is opened, which is also the loop a coding agent can run on every edit. ### Loud failures and quiet ones[​](#loud-failures-and-quiet-ones "Direct link to Loud failures and quiet ones") Every failure in the table is loud once a test runs the branch that builds the reference, and `matchingPeople` passes every test that leaves the pet name out. The failures further down this page are quiet: four the introduction names, a [raw result with an include](#kysely-nests-results-in-sql) typed as the parent, an include filter that drops the parents it does not match, and a [paranoid include](#kysely-sends-the-statement-you-wrote) that reads a soft-deleted parent as `null`, each with no error. **No query builder is perfectly type-safe, and Kysely is no exception. Type safety is what it is built around, and every gap is treated as work to do.** TypeScript's native compiler widens what that work can afford, and Kysely's direction is to spend that headroom on stricter and more ambitious checks. Where Kysely's checks stop Kysely's check is made where a reference is written, on a builder that knows the query, and it stops there. A reference written with `sql.ref` or as template text, a [dynamic reference](https://kysely-org.github.io/kysely-apidoc/classes/DynamicModule.html), an expression built ahead of time on a standalone `expressionBuilder`, and a helper whose builder parameter declares more tables than the caller's query has are all taken on trust. The reference shorthands `whereRef`, `onRef`, and the three-argument join take two column names without comparing their types. Kysely's references are strings read by the type system: completed and checked, yet an unqualified `id` after joining two tables that both have one compiles, and PostgreSQL rejects it as ambiguous. A column renamed in the database is a compile error in every Kysely query that names it. Sequelize's `field` option maps an attribute to a column, so the rename is one edit in the model, and every finder that names the attribute still compiles to the new column. `where('age', '=', null)` compiles and matches no rows. That is by design: Kysely builds the comparison as written, and `= null` is valid SQL. Code that filters on a nullable variable adds the built-in [`SafeNullComparisonPlugin`](https://kysely.dev/docs/plugins.md#safe-null-comparison-plugin), which rewrites `=` to `IS` when the value is null, and nothing is rewritten without it. Sequelize writes `IS NULL` for a `null` in a `where` object. One Kysely gap is quiet: a `union` whose sides list the same columns in a different order returns values under the wrong keys. The checks also cost compile time. Kysely's types are computed by the compiler, and a schema with hundreds of tables or a deeply composed query can slow type-checking and the editor. ## Result types come from the selection[​](#result-types-come-from-the-selection "Direct link to Result types come from the selection") A finder returns model instances typed as the model, or with `raw: true`, plain objects typed as the model on 6 and as its attributes on 7. Neither is derived from `attributes`. Rename an attribute: ```ts const person = await Person.findOne({ attributes: [['first_name', 'name']], where: { id: 1 }, raw: true, }) person?.first_name // Typed string. undefined at runtime: the row has name. ``` Select one attribute and read another: ```ts const person = await Person.findByPk(1, { attributes: ['id'], rejectOnEmpty: true, }) person.first_name // Typed string. undefined at runtime: it was not selected. ``` A computed attribute such as `pet_count` goes the other way: it reaches the row and never the type, so on an instance it takes `get('pet_count')`, and on a raw row a cast. Sequelize 7 accepts a row type for raw results, `findAll()`, which you write and maintain beside the query, and a stale one still compiles. In Kysely the same queries are typed `{ name: string }` and `{ id: number }`, the count is a column on the row, and a caller reading a column that is no longer selected stops compiling. **A Kysely result is typed as the selection you made, so changing the selection changes the type every caller sees.** ## Kysely nests results in SQL[​](#kysely-nests-results-in-sql "Direct link to Kysely nests results in SQL") Return each person with their pets. `findAll({ include: [{ model: Pet, as: 'pets' }] })` reads the association and returns `Person` instances with `pets` loaded, typed through the model's `NonAttribute`. That is the shape most Sequelize code wants, and it is where model hydration earns its keep. A `where` inside the include filters the pets, and Sequelize also [sets `required: true`](https://github.com/sequelize/website/blob/843c76173ebd444c58706da53ed8c006a7b4f6d5/versioned_docs/version-6.x.x/advanced-association-concepts/eager-loading.md#L180) for it, so the join becomes an `INNER JOIN` and a person with no matching pet drops out of the result. `required: false` keeps them, under the same `Pet[]` type. The statement behind it is a flat join. PostgreSQL returns one row per pet, and Sequelize groups the rows into instances after they arrive. With `raw: true` it skips the grouping: Jennifer, with two pets, comes back as two rows with keys such as `'pets.name'`, typed as `Person`. A hasMany include can also load with [`separate: true`](https://github.com/sequelize/website/blob/843c76173ebd444c58706da53ed8c006a7b4f6d5/docs/querying/select-in-depth.md#L353-L358), one statement per association, so no parent is repeated. Kysely nests in SQL, with `jsonArrayFrom` from `kysely/helpers/postgres`: ```ts import { jsonArrayFrom } from 'kysely/helpers/postgres' const rows = await db .selectFrom('person') .select((eb) => [ 'person.first_name', jsonArrayFrom( eb .selectFrom('pet') .select('pet.name') .whereRef('pet.owner_id', '=', 'person.id') .orderBy('pet.name'), ).as('pets'), ]) .execute() // Inferred: { first_name: string; pets: { name: string }[] }[] ``` One statement, one row per person, `[]` for a person with no pets, and `limit()` counts people. A `where` inside the subquery filters the pets, and every person stays. The nested subquery is an ordinary Kysely query: join inside it, aggregate it, filter it, with the same methods and the same checks. **Kysely asks PostgreSQL for the nested object and types it, so the rows arrive already shaped.** The helpers are per dialect, and a driver that returns JSON as text needs [`ParseJSONResultsPlugin`](https://kysely.dev/docs/recipes/relations.md#the-json-data-type-and-functions). See [nested relations](https://kysely.dev/docs/recipes/relations.md). ### Kysely pages parents in one statement[​](#kysely-pages-parents-in-one-statement "Direct link to Kysely pages parents in one statement") The join also decides pagination. A `limit` on a finder with an include pages parents: Sequelize moves the parent's part of the query into a subquery and joins the children to it. Options that read the included table can end up inside that subquery. A `'$pets.name$'` filter with a `limit` fails in PostgreSQL. So does the grouped count above once it adds a `having` that compares the count with `pet_target` and a `limit`. Both run once `subQuery: false` keeps the join and the aggregate in one query. `findAndCountAll()` sends the page and its total as separate statements. With an include, the count counts joined rows: four people, one of them without pets, count as five, until `distinct: true` is set. The [issue about it](https://github.com/sequelize/sequelize/issues/9481) has been open since May 2018. **Kysely reads a page of parents and its total in one statement, with `eb.fn.countAll().over()` as a column.** A page past the last row returns no rows, and so no total. ## Kysely keeps every filter a caller adds[​](#kysely-keeps-every-filter-a-caller-adds "Direct link to Kysely keeps every filter a caller adds") Scopes are Sequelize's reusable queries: a named options object a model applies before the finder's own. On Sequelize 6, the finder's `where` is [merged with the scope's shallowly](https://github.com/sequelize/website/blob/843c76173ebd444c58706da53ed8c006a7b4f6d5/versioned_docs/version-6.x.x/other-topics/scopes.md#L173), "meaning that identical keys will be overwritten": ```ts Pet.addScope('ownedBy', (ownerId: number) => ({ where: { owner_id: ownerId } })) const pets = await Pet.scope({ method: ['ownedBy', 1] }).findAll({ where: { owner_id: 2 }, }) // WHERE "Pet"."owner_id" = 2: the scope's owner filter is gone. ``` The query returns another owner's pets, with no error. When the scope is a tenant or an owner filter, that is a data leak, and a [2023 report](https://github.com/sequelize/sequelize/issues/16582) called it "an unsafe scene when the user can escape a predefined scope". [Sequelize's docs](https://github.com/sequelize/website/blob/843c76173ebd444c58706da53ed8c006a7b4f6d5/versioned_docs/version-6.x.x/other-topics/scopes.md#L195-L211) describe it, and since March 2022 a model or an instance can opt into `whereMergeStrategy: 'and'`. Sequelize 7 joins the two with AND by default. In Kysely each `where()` adds its condition with AND, and every method returns a new builder, so a shared function can add a filter, a join, or a limit without knowing what its caller added: ```ts const ownedBy = (ownerId: number) => db.selectFrom('pet').select('name').where('owner_id', '=', ownerId) const pets = await ownedBy(1).where('owner_id', '=', 2).execute() // where "owner_id" = $1 and "owner_id" = $2: no rows. ``` **Every Kysely builder is a value you can share, and a filter added to it can only narrow it.** Immutability has one trap of its own: a returned builder that is not kept is a change that never happened. Keep each returned builder, and use [`$if`](https://kysely.dev/docs/recipes/conditional-selects.md) when conditional selections change the result type. ## Kysely sends values as parameters[​](#kysely-sends-values-as-parameters "Direct link to Kysely sends values as parameters") Sequelize's finders write each value into the statement as an escaped literal. `findAll({ where: { first_name: 'Jennifer' } })` sends `WHERE "Person"."first_name" = 'Jennifer'` as text, on both releases, and so does `destroy()`. The escaping keeps it safe from injection, and the values still travel with the text. `create()` and `update()` bind their values, and a raw query binds only with the `bind` option. Sequelize's docs call the inlined form [replacements](https://github.com/sequelize/website/blob/843c76173ebd444c58706da53ed8c006a7b4f6d5/docs/querying/raw-queries.mdx#L48-L49): "escaped and inserted into the query by Sequelize before the query is sent to the database". Bind parameters for every query were [requested in October 2019](https://github.com/sequelize/sequelize/issues/11586) and are still open. Kysely sends a placeholder in the text and `'Jennifer'` beside it as a parameter, for every value a query takes, its `sql` templates included, unless it is written with `sql.lit`. ### A failed Sequelize query puts its values in the error[​](#a-failed-sequelize-query-puts-its-values-in-the-error "Direct link to A failed Sequelize query puts its values in the error") Sequelize 6 [logs every statement with `console.log` by default](https://github.com/sequelize/website/blob/843c76173ebd444c58706da53ed8c006a7b4f6d5/versioned_docs/version-6.x.x/getting-started.md#L102), so an application that never set `logging` prints each finder's values to standard output. Sequelize 7 logs nothing by default. On both releases, a failed query throws an error with the statement as an enumerable `sql` property. The text makes a failure easy to reproduce, and a logger or an error reporter that serializes the error records it too, so a password hash, an API token, an email address, or any other credential or personal data in a failed finder's `where` reaches the log. Kysely passes the driver's error through, and node-postgres adds no statement or parameters to it. Kysely's `log` option receives the compiled query on an error, so recording the values is the logger's choice. PostgreSQL's own `detail` still names the conflicting key of a unique violation, in both libraries. **Kysely's errors carry no bound values of their own, so what reaches an error reporter is what the database said.** ## Kysely sends the statement you wrote[​](#kysely-sends-the-statement-you-wrote "Direct link to Kysely sends the statement you wrote") Sequelize's finders add to a statement from the model's options. Make `Person` [paranoid](https://github.com/sequelize/website/blob/843c76173ebd444c58706da53ed8c006a7b4f6d5/docs/models/paranoid.mdx) with a `deleted_at` column, and its `destroy()` becomes an `UPDATE` that sets the delete date, and every finder on it gets `"deleted_at" IS NULL`. So does the join condition of an include, here through a `Pet.belongsTo(Person, { as: 'owner' })` association: ```ts const pets = await Pet.findAll({ include: [{ model: Person, as: 'owner' }], }) // LEFT OUTER JOIN "person" AS "owner" // ON "Pet"."owner_id" = "owner"."id" AND "owner"."deleted_at" IS NULL // A pet whose owner was soft-deleted is returned with owner: null. ``` The pet stays in the result, and its owner reads `null`, as if it had none. The docs show [`include.paranoid: false`](https://github.com/sequelize/website/blob/843c76173ebd444c58706da53ed8c006a7b4f6d5/docs/models/paranoid.mdx#L136-L148) to load soft-deleted records, and a raw query gets no filter at all. The filter itself is a feature that keeps soft-deleted rows out of every finder, and default scopes add their options the same way. In Kysely a soft-delete filter is a condition you write once, in a helper every query calls or in a [plugin](https://kysely.dev/docs/plugins.md) that rewrites the query tree. **Kysely sends the statement you wrote, and changes it only through plugins you install.** ## Migrate from Sequelize to Kysely one query at a time[​](#migrate-from-sequelize-to-kysely-one-query-at-a-time "Direct link to Migrate from Sequelize to Kysely one query at a time") A move from Sequelize to Kysely does not have to happen at once, or at all for the models. ### Can Kysely and Sequelize be used together?[​](#can-kysely-and-sequelize-be-used-together "Direct link to Can Kysely and Sequelize be used together?") Yes. [kysely-sequelize](https://github.com/kysely-org/kysely-sequelize) runs Kysely over an existing Sequelize 6 instance: its [`KyselySequelizeDialect`](https://github.com/kysely-org/kysely-sequelize/blob/c86004253c1341d6aa1b61908684a629ba470053/README.md#L367-L403) reuses Sequelize's connections, and its [`KyselifyModel`](https://github.com/kysely-org/kysely-sequelize/blob/c86004253c1341d6aa1b61908684a629ba470053/README.md#L157-L175) type derives Kysely's table types from the model classes, with no generation step. ```ts import { Kysely, PostgresAdapter, PostgresIntrospector, PostgresQueryCompiler, } from 'kysely' import { KyselySequelizeDialect, type KyselifyModel } from 'kysely-sequelize' interface Database { person: KyselifyModel pet: KyselifyModel } const db = new Kysely({ dialect: new KyselySequelizeDialect({ kyselySubDialect: { createAdapter: () => new PostgresAdapter(), createIntrospector: (db) => new PostgresIntrospector(db), createQueryCompiler: () => new PostgresQueryCompiler(), }, sequelize, }), }) ``` `KyselifyModel` leaves `NonAttribute` properties such as `pets` out, and a key declared `CreationOptional` becomes optional on insert. The classes stay Sequelize models. 1. Keep the models, the migrations, and the hooks and validations that run on instances. 2. Derive Kysely's types with `KyselifyModel`, or [generate them](https://kysely.dev/docs/generating-types.md) from the migrated database, which also catches a column the model does not declare. 3. Start with a finder that reads computed attributes, uses `literal()`, or shares a scope with callers. Move it, inspect `.compile()`, and compare rows, nulls, ordering, and empty results. 4. Keep each transaction on one client. The bridge shares connections, not a transaction in progress. ## Other practical considerations[​](#other-practical-considerations "Direct link to Other practical considerations") Measured package sizes and dependency trees | Published package | Compressed download | Unpacked size | Direct dependencies | | ------------------------------ | ------------------- | ------------- | ------------------- | | Kysely 0.29.8 | 319.6 KiB | 1.66 MiB | 0 | | Sequelize 6.37.8 | 594.1 KiB | 2.77 MiB | 16 | | @sequelize/core 7.0.0-alpha.48 | 668.0 KiB | 3.02 MiB | 18 | PostgreSQL production trees, including transitive dependencies: | PostgreSQL setup | Unique production packages | | ---------------------------------------------------- | -------------------------- | | Kysely 0.29.8 + pg 8.23.1 | **14** | | Sequelize 6.37.8 + pg 8.23.1 + pg-hstore 2.3.4 | 35 | | @sequelize/core + @sequelize/postgres 7.0.0-alpha.48 | 67 | Sequelize 6 includes every dialect's code and asks for `pg` and `pg-hstore` beside it. Sequelize 7 moves each dialect into its own package, `@sequelize/postgres` bringing `pg`. Kysely's package includes its five core dialects. Measured **November 13, 2026**. Package sizes exclude dependencies, and trees exclude optional dependencies and peer auto-installation. These are not bundle sizes or install benchmarks. ## Choosing Sequelize or Kysely[​](#choosing-sequelize-or-kysely "Direct link to Choosing Sequelize or Kysely") Sequelize vs Kysely is a choice between a data framework whose finders take an options object typed through the model, and a query builder whose types follow the query. ### Why use Kysely instead of Sequelize?[​](#why-use-kysely-instead-of-sequelize "Direct link to Why use Kysely instead of Sequelize?") **Choose Kysely when queries are composed, shared, and changed, and you want TypeScript to check each change.** * References are [checked against the query](#kysely-checks-the-references-sequelize-takes-as-strings) in every clause, where a finder passes `col()`, `order`, `group`, and `'$pets.name$'` strings to the database, and subqueries, CTEs, set operations, and window functions are methods, where a finder takes `literal()` text. * Result types [come from the selection](#result-types-come-from-the-selection), not from the model. * [Nested results and pages](#kysely-nests-results-in-sql) are one statement and one row per parent. * A filter [only narrows a shared query](#kysely-keeps-every-filter-a-caller-adds), values are [sent as parameters](#kysely-sends-values-as-parameters), and statements are [sent as written](#kysely-sends-the-statement-you-wrote). * Queries can be cancelled with an [`AbortSignal`](https://kysely-org.github.io/kysely-apidoc/interfaces/AbortableQueryOptions.html), which Sequelize's finders do not take ([requested in March 2022](https://github.com/sequelize/sequelize/issues/14247)). Its types can come from the database itself, so it fits a schema that another tool, service, or team migrates. Immich, Open Collective, and Docmost [compose production queries with it](https://kysely.dev/docs/comparisons/query-builder-vs-raw-sql.md#production-code-draws-the-same-line). ### When is Sequelize the better choice?[​](#when-is-sequelize-the-better-choice "Direct link to When is Sequelize the better choice?") **Keep Sequelize when a person writes the models and the queries, and the model is the unit the code thinks in: hooks and validations on instances, associations loaded into them, and scopes that name the common finders.** It is also the choice when the database is one Kysely has no dialect for, Db2 or Snowflake among them. Its finders can stay for the queries that already work, and Kysely can run beside them for the ones that are composed. Chosen for its finders alone, Sequelize trades the checks on this page for attribute names that absorb a column rename and, on 7, queries that join the surrounding transaction [without passing it](https://github.com/sequelize/website/blob/843c76173ebd444c58706da53ed8c006a7b4f6d5/docs/querying/transactions.md#L189-L190), where a Kysely query runs on the transaction handle it is built from. ### Is Sequelize still maintained?[​](#is-sequelize-still-maintained "Direct link to Is Sequelize still maintained?") **Yes, on 6.** 6.37.8 shipped in March 2026, and the repository is active. Sequelize 7 has been in alpha since December 2021, with 7.0.0-alpha.48 the latest, from February 2026, and Sequelize's README is [seeking new maintainers](https://github.com/sequelize/sequelize/blob/53d1e8a6199fff85a8d6cd7d9bf0f3487f0cf798/README.md#L17-L29) "to help finalize and release the next major version", with funding for them. ### Should I wait for Sequelize 7 or move to Kysely?[​](#should-i-wait-for-sequelize-7-or-move-to-kysely "Direct link to Should I wait for Sequelize 7 or move to Kysely?") **Sequelize 7 closes some of the gaps on this page and keeps the finder model that leaves the rest.** On 7, a scope's `where` and the finder's join with AND, attribute names are checked, a string compared with an integer is refused before it is sent, transactions follow the callback through AsyncLocalStorage, and the default logger is off. `col()`, `order`, `group`, and `'$pets.name$'` are still unchecked strings, results are still typed as the model, values are still written into the text, and subqueries are still raw SQL. 7 is also a new package, `@sequelize/core`, with its dialects in packages of their own and [a list of breaking changes](https://github.com/sequelize/website/blob/843c76173ebd444c58706da53ed8c006a7b4f6d5/docs/other-topics/upgrade.md), and it has no release date. The two moves can be combined: queries moved to Kysely use none of the finder APIs that 7 changes, so a team on 6 can move its composed queries first, [through kysely-sequelize](#can-kysely-and-sequelize-be-used-together), and keep the models on 6 until 7 ships. ### Is Sequelize type-safe?[​](#is-sequelize-type-safe "Direct link to Is Sequelize type-safe?") **For model attributes, `where` keys, and the values it writes, yes, when the model declares its attributes. For the rest of a finder and its results, no.** A `where` object and the values `create()` and `update()` take are [checked against the model](#kysely-checks-the-references-sequelize-takes-as-strings), and 7 checks attribute names too. The strings in `col()`, `order`, `group`, and `'$pets.name$'` are not checked, and a result is typed as the model whatever was selected. Kysely checks the references and infers the result, with [gaps of its own](#where-kyselys-checks-stop). ### Is there a type-safe query builder for Sequelize?[​](#is-there-a-type-safe-query-builder-for-sequelize "Direct link to Is there a type-safe query builder for Sequelize?") **Kysely, through [kysely-sequelize](#can-kysely-and-sequelize-be-used-together).** It runs over the existing Sequelize 6 instance and derives its table types from the models, so queries move to checked references and inferred results one at a time while the models, migrations, and hooks stay. ### Is Kysely faster than Sequelize?[​](#is-kysely-faster-than-sequelize "Direct link to Is Kysely faster than Sequelize?") **The database cannot tell them apart when the statements match, and [performance belongs to the statement](https://kysely.dev/docs/comparisons/query-builder-vs-raw-sql.md#performance-belongs-to-the-statement-not-the-authoring-tool).** The statements do not always match. Sequelize hydrates instances from expanded join rows, pages an include through a subquery, and sends `findAndCountAll()` as two statements. Kysely returns rows as the database shaped them and nests in SQL. Neither library is benchmarked here. ### Is Kysely smaller than Sequelize?[​](#is-kysely-smaller-than-sequelize "Direct link to Is Kysely smaller than Sequelize?") **Yes, as a package and as a dependency tree.** Kysely's published package is a 319.6 KiB download with no dependencies, against 594.1 KiB and 16 dependencies for Sequelize 6.37.8, and with `pg` the production trees are 14 and 35 packages. The [measurements](#measured-sizes) and what they exclude are above. ### Which is easier for a coding agent to use?[​](#which-is-easier-for-a-coding-agent-to-use "Direct link to Which is easier for a coding agent to use?") **Kysely checks more of what the agent writes, before the query runs.** An agent works by editing and running the compiler again, and the checks on this page sit inside that loop: a wrong reference, a stale result type, or a misspelled column is a compile error it can read and fix without a database, where a finder gives it a failed request or an `undefined`. Each library documents its methods in the type declarations it installs, and Kysely's inline examples are [type-checked in CI](https://kysely.dev/docs/integrations/llms.md) against the release they ship with. **Kysely types the query you write, in every clause, before it runs.** [Get started with Kysely](https://kysely.dev/docs/getting-started.md), find equivalents in the [query examples](https://kysely.dev/docs/category/examples.md), or compare [query builders with ORMs](https://kysely.dev/docs/comparisons/query-builder-vs-orm.md), [query builders with raw SQL](https://kysely.dev/docs/comparisons/query-builder-vs-raw-sql.md), [Kysely with Drizzle](https://kysely.dev/docs/comparisons/kysely-vs-drizzle.md), [Kysely with TypeORM](https://kysely.dev/docs/comparisons/kysely-vs-typeorm.md), and [Kysely with Knex](https://kysely.dev/docs/comparisons/kysely-vs-knex.md). Adoption: replacing Sequelize with Kysely [Coop](https://github.com/roostorg/coop), ROOST's open source review and moderation tool, moved its server from Sequelize to Kysely in spring 2026, one area per pull request. [The last of them](https://github.com/roostorg/coop/pull/420), "Final server-side step of the Sequelize -> Kysely migration", deleted the server's models and its `sequelize` dependency in May, and Sequelize remains in the package that runs its migrations. --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Kysely vs TypeORM Kysely and TypeORM both have a query builder that keeps SQL's clause order. TypeORM's takes selections, joins, filters, and ordering as strings or untyped objects, such as `where('person.age >= :minAge')`, `select('pet.name', 'pet_name')`, or `'pet.owner_id = person.id'` in a join, and returns entity instances or raw rows typed `any`. Kysely takes references and values as typed arguments and derives the result type from the selection. **Kysely's types describe the query itself, from each reference it names to the rows it returns.** Both are [well adopted](https://npmx.dev/compare?packages=kysely,drizzle-orm,@prisma/client,typeorm,knex,sequelize,@mikro-orm/core\&facets=downloads) and maintained. Since 2016, TypeORM has given TypeScript developers entities as classes, repositories, relations, and migrations generated from the entities. It offers both [Active Record and Data Mapper](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/README.md#L23), follows [Hibernate, Doctrine, and Entity Framework](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/README.md#L25-L26), and, by its own count, supports [more databases than any other JavaScript ORM](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/README.md#L21), MongoDB, Oracle, SAP HANA, and Spanner among them. A [new team took over its maintenance in October 2024](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/blog/2024-10-01-future-of-typeorm/index.md#L8-L12), and [1.0 shipped in May 2026](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/releases/1.0/01-release-notes.md#L7) after a decade of 0.x releases. NestJS ships an official integration, `@nestjs/typeorm`, and its docs call TypeORM [one of the most mature ORMs available for TypeScript](https://github.com/nestjs/docs.nestjs.com/blob/3c9dc71f93c350245210075fc634980df1caa3dd/content/data/typeorm.md#L3). **TypeORM was the first widely adopted ORM written for TypeScript, and a generation of Node.js services learned relational data through it.** The differences that cost most are the quiet ones. A `getRawMany()` annotation outlives the selection it described, a partial selection is typed as the whole entity, a second `where()` [replaces an owner filter](#shared-queries-branch-without-mutation), and a repeated parameter name [overrides the earlier value](#each-value-is-bound-where-it-is-written), each with no error. ## This page compares TypeORM's query builder[​](#this-page-compares-typeorms-query-builder "Direct link to This page compares TypeORM's query builder") Kysely is a type-safe SQL query builder. In this site's terms TypeORM is a [data framework](https://kysely.dev/docs/comparisons/query-builder-vs-orm.md#orms-data-frameworks-and-plain-objects), the familiar stack of models, migrations generated from them, a model API, and a SQL-style query builder. Its models are entities, and its model API is repositories and the find API. The sections below set its query builder against Kysely, and [SQL query builder vs ORM](https://kysely.dev/docs/comparisons/query-builder-vs-orm.md) covers the model API and entity persistence. TypeORM here means 1.1.2 and 0.3.31, its current and legacy releases in November 2026. [Most installs still run 0.3.x](https://npmx.dev/package/typeorm/versions), so the behavior below holds on both unless a sentence says otherwise. [Upgrading to 1.0 or moving to Kysely](#should-i-upgrade-to-typeorm-10-or-move-to-kysely) covers what 1.0 changes. ## Both build the same left join[​](#both-build-the-same-left-join "Direct link to Both build the same left join") Assume configured Kysely (`db`) and TypeORM (`dataSource`) clients over the same two tables: Database interface and TypeORM entities Kysely's `Database` interface is types only, handwritten or [generated](https://kysely.dev/docs/generating-types.md) from the database: ```ts interface Database { person: { id: number; first_name: string; age: number | null } pet: { id: number; name: string; owner_id: number } } ``` TypeORM's entities are classes with metadata, declared here through `EntitySchema` instead of decorators, which TypeORM also reads to generate migrations: ```ts import { EntitySchema } from 'typeorm' class Person { declare id: number declare first_name: string declare age: number | null declare pets: Pet[] } class Pet { declare id: number declare name: string declare owner_id: number declare owner: Person } const PersonSchema = new EntitySchema({ name: 'Person', target: Person, tableName: 'person', columns: { id: { type: Number, primary: true }, first_name: { type: String }, age: { type: Number, nullable: true }, }, relations: { pets: { type: 'one-to-many', target: 'Pet', inverseSide: 'owner' }, }, }) const PetSchema = new EntitySchema({ name: 'Pet', target: Pet, tableName: 'pet', columns: { id: { type: Number, primary: true }, name: { type: String }, owner_id: { type: Number }, }, relations: { owner: { type: 'many-to-one', target: 'Person', joinColumn: { name: 'owner_id' }, inverseSide: 'pets', }, }, }) ``` Select adults with their pets' names, keeping people who have no pet. With TypeORM: ```ts const rows = await dataSource .getRepository(Person) .createQueryBuilder('person') .leftJoin(Pet, 'pet', 'pet.owner_id = person.id') .select('person.first_name', 'first_name') .addSelect('pet.name', 'pet_name') .where('person.age >= :minAge', { minAge: 18 }) .orderBy('person.first_name') .getRawMany() // any[] ``` With Kysely: ```ts const rows = await db .selectFrom('person') .leftJoin('pet', 'pet.owner_id', 'person.id') .select(['person.first_name', 'pet.name as pet_name']) .where('person.age', '>=', 18) .orderBy('person.first_name') .execute() // Inferred: { first_name: string; pet_name: string | null }[] ``` The rows match. TypeORM's [raw results](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/query-builder/1-select-query-builder.md#L826-L833) are `any[]`, and `getRawMany()` takes a row type you write and maintain beside the query. Kysely infers the row, and makes `pet_name` nullable because the join is a left join. **Written correctly, the two queries are equivalent, and only Kysely's has a result type the compiler derived.** ## Kysely checks the references TypeORM takes as strings[​](#kysely-checks-the-references-typeorm-takes-as-strings "Direct link to Kysely checks the references TypeORM takes as strings") TypeORM's find API is typed: `find()` checks the properties named in `where`, `order`, and `relations` against the entity, and the query builder's `values()` and `set()` check an insert's or an update's values the same way, with [one exception on 0.3.x](#should-i-upgrade-to-typeorm-10-or-move-to-kysely). `setFindOptions()` brings typed find options into the builder. The find API covers what an entity and its declared relations express, through a [fixed set of operators](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/working-with-entity-manager/3-find-options.md#L304-L306) such as `In`, `Like`, `Between`, and `IsNull`. Any other comparison, a regular expression match among them, is [`Raw()`](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/working-with-entity-manager/3-find-options.md#L598-L606): a callback that receives the column name and returns SQL text, so the rest of the comparison is unchecked. Kysely's `where()` takes SQL's comparison operators by name, `~` included, and any other operator as a `sql` template, such as `` sql`my_operator` ``, with the column and the value still checked. A join without a declared relation, a computed column, a grouped aggregate, or a subquery moves the code to the query builder. That is where a [model API runs out into SQL](https://kysely.dev/docs/comparisons/query-builder-vs-orm.md#query-builder-composition-survives-changing-requirements), so the builder holds a TypeORM codebase's hardest queries, and it is the part this page compares. Production queries collect their filters. Put the query above in a function with an optional pet name, and later drop the pet's name from the result, and the join with it: ```ts function matchingPeople(options: { petName?: string }) { const query = dataSource .getRepository(Person) .createQueryBuilder('person') .select('person.first_name', 'first_name') .where('person.age >= :minAge', { minAge: 18 }) if (options.petName) { query.andWhere('pet.name = :petName', { petName: options.petName }) } return query } ``` It compiles, and it runs for every request without a pet name. A request with one fails in PostgreSQL: the filter still reads `pet`, and the change never touched that line. The same function after the same change in Kysely: ```ts function matchingPeople(options: { petName?: string }) { let query = db .selectFrom('person') .select('person.first_name') .where('person.age', '>=', 18) if (options.petName) { // TypeScript error: pet is not available in this query. query = query.where('pet.name', '=', options.petName) // Argument of type '"pet.name"' is not assignable to parameter of type 'ReferenceExpression'. } return query } ``` TypeORM reads `alias.property` inside its strings and maps the property to its column name, so a column renamed in the database is one edit in the entity. An alias is [a regular SQL alias](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/query-builder/1-select-query-builder.md#L246-L250), not checked against the query's joins, and a property it does not recognize is passed through as written. Kysely's `selectFrom` comes first, and every later method is typed against the tables and aliases accumulated so far. **Kysely checks every reference written on the query's own builder, in each clause where TypeORM takes a string.** ### The same split in every clause[​](#the-same-split-in-every-clause "Direct link to The same split in every clause") | Invalid reference | Kysely | TypeORM | | --------------------------------------------------- | ----------------- | ----------------------------------------- | | Select `pet.name` without joining `pet` | TypeScript error. | Passes TypeScript; PostgreSQL rejects it. | | Filter or order on `pet.name` without joining `pet` | TypeScript error. | Passes TypeScript; PostgreSQL rejects it. | | Select the misspelled `person.first_nam` | TypeScript error. | Passes TypeScript; PostgreSQL rejects it. | | Alias `person` as `p`, then filter on `person.age` | TypeScript error. | Passes TypeScript; PostgreSQL rejects it. | | Compare the integer column `age` with `'old'` | TypeScript error. | Passes TypeScript; PostgreSQL rejects it. | **Every row in that table is a failed request with TypeORM and a compile error with Kysely.** PostgreSQL [stops at the first error](https://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY), so unchecked mistakes surface one execution at a time, against a database. The compiler reports them together, before a connection is opened, which is also the loop a coding agent can run on every edit. ### The gap is a design choice made in 2016[​](#the-gap-is-a-design-choice-made-in-2016 "Direct link to The gap is a design choice made in 2016") Asked in December 2016 for [a query builder that is not string-based](https://github.com/typeorm/typeorm/issues/128), TypeORM's author [answered](https://github.com/typeorm/typeorm/issues/128#issuecomment-267405343): "I also wish to make query builder typesafe (not string based)", and "the problem in the design and its proposal". By June 2017 the conclusion was that it is ["impossible to do same type safe style things in query builder because of flexibility sql has"](https://github.com/typeorm/typeorm/issues/128#issuecomment-311356628), and the issue was [closed](https://github.com/typeorm/typeorm/issues/128#issuecomment-318355830) because "there is no clear way of implementing linq in typescript". In 2017 that was a fair reading of the language. [String literal types](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-8.html#string-literal-types) and [`keyof`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html#keyof-and-lookup-types) already let a type name a column, which is how find options are checked. [Conditional types and `infer`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#conditional-types), which let one type be computed from another, such as a result row from a selection, arrived in March 2018. [Template literal types](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-1.html#template-literal-types), which let the compiler read strings like `'pet.name as pet_name'`, followed in November 2020, and Kysely's first commit came three months later. TypeORM's builder kept the API its users already had. **TypeORM's builder was designed before TypeScript could type a query builder. Kysely was designed once it could.** ### Loud failures and quiet ones[​](#loud-failures-and-quiet-ones "Direct link to Loud failures and quiet ones") Every failure in the table is loud once a test runs the branch that builds the reference. The `matchingPeople` function above passes every test that leaves the pet name out. The failures further down this page are quiet. Besides the four the introduction names, [a misspelled JSON key](#kysely-builds-the-expressions-typeorm-writes-as-text) returns `null`, [an `OR` added to a scoped query](#kysely-groups-the-conditions-it-builds) returns another owner's rows, and [a page ordered by a joined column](#kysely-pages-parents-in-one-statement) repeats a person, each with no error. **No query builder is perfectly type-safe, and Kysely is no exception. Type safety is what it is built around, and every gap is treated as work to do.** TypeScript's native compiler widens what that work can afford, and Kysely's direction is to spend that headroom on stricter and more ambitious checks. Where Kysely's checks stop Kysely's check is made where a reference is written, on a builder that knows the query, and it stops there. A reference written with `sql.ref` or as template text, a [dynamic reference](https://kysely-org.github.io/kysely-apidoc/classes/DynamicModule.html), an expression built ahead of time on a standalone `expressionBuilder`, and a helper whose builder parameter declares more tables than the caller's query has are all taken on trust. The reference shorthands `whereRef`, `onRef`, and the three-argument join take two column names without comparing their types. Kysely's references are strings read by the type system: completed and checked, yet an unqualified `id` after joining two tables that both have one compiles, and PostgreSQL rejects it as ambiguous. A column renamed in the database is a compile error in every Kysely query that names it. TypeORM's property mapping absorbs the rename in the entity's column options, and every query string that names the property still compiles to the new name. `where('age', '=', null)` compiles and matches no rows. That is by design: Kysely builds the comparison as written, and `= null` is valid SQL. Code that filters on a nullable variable adds the built-in [`SafeNullComparisonPlugin`](https://kysely.dev/docs/plugins.md#safe-null-comparison-plugin), which rewrites `=` to `IS` when the value is null, and nothing is rewritten without it. One Kysely gap is quiet: a `union` whose sides list the same columns in a different order returns values under the wrong keys. The checks also cost compile time. Kysely's types are computed by the compiler, and a schema with hundreds of tables or a deeply composed query can slow type-checking and the editor. ## Result types come from the selection[​](#result-types-come-from-the-selection "Direct link to Result types come from the selection") TypeORM has two result shapes. `getMany()` and `getOne()` return entity instances, typed as the entity class whatever was selected. `getRawMany()` and `getRawOne()` return rows typed `any`, or as the type argument you pass. Neither is derived from the selection. Rename the alias and leave the annotation: ```ts const rows = await dataSource .getRepository(Person) .createQueryBuilder('person') .select('person.first_name', 'name') .getRawMany<{ first_name: string }>() rows[0].first_name // Compiles. undefined at runtime: the row has name. ``` Select one property and read another: ```ts const person = await dataSource .getRepository(Person) .createQueryBuilder('person') .select(['person.id']) .where('person.id = :id', { id: 1 }) .getOneOrFail() person.first_name // Typed string. undefined at runtime: it was not selected. ``` TypeORM's docs describe the second as [partial selection](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/query-builder/1-select-query-builder.md#L1046-L1057). The entity type does not narrow with it. A computed column goes the other way: `addSelect('person.age >= 18', 'is_adult')` reaches raw rows and never the entity, and the request to [map a computed column onto the entity](https://github.com/typeorm/typeorm/issues/296) has been open since February 2017. In Kysely the same two queries are typed `{ name: string }[]` and `{ id: number }`, a computed `eb('age', '>=', 18).as('is_adult')` is a boolean on the row, and a caller reading a column that is no longer selected stops compiling. **A Kysely result is typed as the selection you made, so changing the selection changes the type every caller sees.** ## Kysely builds the expressions TypeORM writes as text[​](#kysely-builds-the-expressions-typeorm-writes-as-text "Direct link to Kysely builds the expressions TypeORM writes as text") JSON traversal, CASE, filtered aggregates, and window clauses are SQL text in `select()` or `addSelect()`, with a result type declared by hand on `getRawMany()`. Kysely has a builder for each, so the references are checked, and for JSON and CASE the type is inferred. A `user_settings.profile` column holds JSON typed as `Profile`, which is `{ addresses: { city: string }[] }`. Read the first address's city. With TypeORM: ```ts const rows = await dataSource .getRepository(Settings) .createQueryBuilder('settings') .select('settings.id', 'id') .addSelect("settings.profile->'addresses'->0->'city'", 'first_city') .getRawMany<{ id: number; first_city: string | null }>() // The row type is supplied by hand. ``` With Kysely: ```ts const rows = await db .selectFrom('user_settings') .select('id') .select((eb) => eb.ref('profile', '->').key('addresses').at(0).key('city').as('first_city'), ) .execute() // Inferred: { id: number; first_city: string | null }[] ``` Kysely infers `string | null` because the array may be empty. Misspell `city` as `ctiy`: TypeORM compiles, runs, and returns `null` for every row under a type that still says `string | null`. Kysely reports that `ctiy` is not a key of an address. **A misspelled JSON key is a silent `null` in TypeORM and a compile error in Kysely.** Both libraries trust the declared `Profile` type, and neither validates the stored JSON. CASE follows the same line. A `case when ... end` string without an `ELSE` returns `null` for a person whose age is unknown, under whatever type the annotation claims. Kysely's `eb.case()` infers `string | null` when the `else` is left out, and a caller's `.toUpperCase()` stops compiling until it handles the null. `getCount()` is the one aggregate TypeORM's builder types, as a `number`. Every other aggregate in the builder is a string in `select()`, returned as `pg` returns it. Repositories also have `sum()`, `average()`, `minimum()`, and `maximum()`, typed `number | null` over a numeric column and an optional find `where`. ## Kysely covers more of SQL's statements[​](#kysely-covers-more-of-sqls-statements "Direct link to Kysely covers more of SQL's statements") Whole statements and clauses follow the line the expressions do. Each row below is a method in Kysely, with no builder for it in TypeORM 1.1.2 or 0.3.31: | Statement or clause | Kysely | TypeORM | | ---------------------------------------------------- | ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `UNION`, `INTERSECT`, `EXCEPT` | `.union(...)`, `.intersect(...)`, `.except(...)` | Requested in [January 2022](https://github.com/typeorm/typeorm/issues/8584); a maintainer's [workaround](https://github.com/typeorm/typeorm/issues/8584#issuecomment-2602856562) writes the union inside a CTE as text. | | `MERGE` | `db.mergeInto('person as target')` | Written as a raw query. | | `DELETE ... USING` | `deleteFrom('pet').using('person')` | The delete builder has no join or `using`. | | Aggregate `FILTER (WHERE ...)` | `eb.fn.countAll().filterWhere('kind', '=', 'image')` | A string in `select()`. | | Window functions | `eb.fn.agg('row_number').over((ob) => ob.partitionBy(...))` | A string in `select()`. | | Row-value `IN`: `(id, owner_id) in ((1, 1), (3, 1))` | `eb(eb.refTuple('id', 'owner_id'), 'in', [eb.tuple(1, 1)])` | A string in `where()`. | | `IS DISTINCT FROM` | `where('age', 'is distinct from', 40)` | A string in `where()`. | TypeORM's builder does cover a lot of PostgreSQL: [common table expressions](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/query-builder/1-select-query-builder.md#L1242-L1245), recursive and materialized ones included, `DISTINCT ON`, `NULLS FIRST` and `NULLS LAST`, row locks with `SKIP LOCKED`, [optimistic locking](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/query-builder/1-select-query-builder.md#L960-L970) against a version column, `RETURNING`, [`ON CONFLICT`](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/query-builder/2-insert-query-builder.md#L39-L41) by columns or constraint name with `EXCLUDED` written for you, and, since 1.0, [`INSERT ... SELECT`](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/releases/1.0/01-release-notes.md#L79). **Each of these clauses is a Kysely method, and its references are checked like the rest of the query.** ## Kysely's escape hatch keeps references checked[​](#kyselys-escape-hatch-keeps-references-checked "Direct link to Kysely's escape hatch keeps references checked") Kysely does not cover all of SQL either. It covers what applications write most, extends that coverage release by release, and types the escape hatch for the rest. TypeORM's escape hatch is the string its selections and filters already take. Kysely's is a [`sql` template](https://kysely-org.github.io/kysely-apidoc/interfaces/Sql.html) that binds its values as parameters and declares its result type. **Inside Kysely's `sql` template, a reference written with `eb.ref` is still checked against the tables in scope.** Wrap repeated fragments in [reusable helpers](https://kysely.dev/docs/recipes/reusable-helpers.md) that take `Expression`. For whole queries written as templates, see [query builder vs raw SQL](https://kysely.dev/docs/comparisons/query-builder-vs-raw-sql.md). ## Nested results stay in the same builder[​](#nested-results-stay-in-the-same-builder "Direct link to Nested results stay in the same builder") Return each person with their pets. TypeORM's `leftJoinAndSelect('person.pets', 'pet')` reads the declared relation and returns `Person` instances with `pets: Pet[]`, typed through the entity class. That is the shape most TypeORM code wants, and it is where entity hydration earns its keep. A filter on the joined alias trims that collection: `.where('pet.name = :name', { name: 'Catto' })` returns Jennifer with `pets` holding Catto alone, under the same `Pet[]` type as an unfiltered load. The statement behind it is a flat join. PostgreSQL returns one row per pet, and TypeORM groups the rows into objects after they arrive: a person with two pets is two rows on the wire and one entity in memory. That expansion is the subject of [a performance issue open since March 2019](https://github.com/typeorm/typeorm/issues/3857), and of a [2026 request](https://github.com/typeorm/typeorm/issues/12699) to aggregate relations as JSON instead. The find API can load relations without the join. With [`relationLoadStrategy: 'query'`](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/relations/5-eager-and-lazy-relations.md#L71-L79), per query or as the data source's default, each relation is read by statements of its own, so no parent is repeated. On both releases, one relation takes three statements: the people, their pets, and a second lookup of pet ids by owner. `setFindOptions()` brings the strategy into the builder. Kysely nests in SQL, with `jsonArrayFrom` from `kysely/helpers/postgres`: ```ts import { jsonArrayFrom } from 'kysely/helpers/postgres' const rows = await db .selectFrom('person') .select((eb) => [ 'person.first_name', jsonArrayFrom( eb .selectFrom('pet') .select('pet.name') .whereRef('pet.owner_id', '=', 'person.id') .orderBy('pet.name'), ).as('pets'), ]) .execute() // Inferred: { first_name: string; pets: { name: string }[] }[] ``` One statement, one row per person, `[]` for a person with no pets, and `limit()` counts people. The nested subquery is an ordinary Kysely query: join inside it, aggregate it, filter it, with the same methods and the same checks. **Kysely asks PostgreSQL for the nested object and types it, so the rows arrive already shaped.** The helpers are per dialect, and a driver that returns JSON as text needs [`ParseJSONResultsPlugin`](https://kysely.dev/docs/recipes/relations.md#the-json-data-type-and-functions). See [nested relations](https://kysely.dev/docs/recipes/relations.md). ### Kysely pages parents in one statement[​](#kysely-pages-parents-in-one-statement "Direct link to Kysely pages parents in one statement") The join also decides pagination. TypeORM's [`take()` and `skip()`](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/query-builder/1-select-query-builder.md#L907-L911) exist because `limit()` cuts joined rows rather than parents, and `take()` with a join runs two statements, one to pick the parents and one to load them. The query strategy pages parents too, across its three statements. Ordered by a joined column, the join's first statement picks distinct pairs of the parent's key and that column. Ordered by pet name, with one person per page, Jennifer appears on two pages, once per pet, while `getCount()` still counts four people. `getManyAndCount()` sends the page and its total as separate statements, three with a join, so a write between them can make the two disagree. **Kysely reads a page of parents and its total in one statement, with `eb.fn.countAll().over()` as a column.** ## Shared queries branch without mutation[​](#shared-queries-branch-without-mutation "Direct link to Shared queries branch without mutation") TypeORM mutates the shared base: ```ts const base = dataSource .getRepository(Person) .createQueryBuilder('person') .select('person.id', 'id') .where('person.age >= :minAge', { minAge: 18 }) const preview = base.limit(1) const everyone = await base.getRawMany() // One row: limit() changed base. base.clone().limit(1) avoids it. ``` Kysely branches independently: ```ts const base = db.selectFrom('person').select('id').where('age', '>=', 18) const preview = base.limit(1) const everyone = await base.execute() // Every adult: limit() returned a new builder. ``` The same mutation decides what `where()` means. TypeORM's docs say that [using `.where` more than once overrides all previous `WHERE` expressions](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/query-builder/1-select-query-builder.md#L418), and `andWhere()` is the method that adds: ```ts const ownedPets = dataSource .getRepository(Pet) .createQueryBuilder('pet') .select('pet.name', 'name') .where('pet.owner_id = :ownerId', { ownerId }) const named = ownedPets.where('pet.name = :name', { name: 'Kitty' }) // SELECT "pet"."name" AS "name" FROM "pet" "pet" WHERE "pet"."name" = $1 // The owner filter is gone, from ownedPets too. ``` The query returns every owner's pets named Kitty, with no error. When the first filter is an owner or a tenant scope, that is a data leak. A second [`orderBy()`](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/query-builder/1-select-query-builder.md#L506) or [`groupBy()`](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/query-builder/1-select-query-builder.md#L545) replaces the first the same way, and so does a second `select()`; `addOrderBy()`, `addGroupBy()`, and `addSelect()` are the methods that add. The docs say a second `having()` [overrides](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/query-builder/1-select-query-builder.md#L467) too, and it is appended to the first with no `AND`, so PostgreSQL rejects the statement. In Kysely all of these methods add: each `where()` adds its condition with AND, and `select()`, `orderBy()`, `groupBy()`, and `having()` append. Each returns a new builder, so a shared function can add a filter, a join, or a limit without knowing what its caller added. **Every Kysely builder is a value you can share without cloning it first.** Immutability has one trap of its own: a returned builder that is not kept is a change that never happened. Keep each returned builder, and use [`$if`](https://kysely.dev/docs/recipes/conditional-selects.md) when conditional selections change the result type. ### Kysely groups the conditions it builds[​](#kysely-groups-the-conditions-it-builds "Direct link to Kysely groups the conditions it builds") TypeORM joins conditions as text. A shared function that adds `andWhere("pet.name = 'Kitty' OR pet.name = 'Parrot'")` to `ownedPets` gets `pet.owner_id = :ownerId AND pet.name = 'Kitty' OR pet.name = 'Parrot'`, with no parentheses added. `AND` binds first, so PostgreSQL returns the owner's Kitty or any owner's Parrot. Mixing `orWhere()` with `andWhere()` stacks the same way, as the docs [warn](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/query-builder/1-select-query-builder.md#L420-L422), and `Brackets` is the grouping you add by hand. Kysely's `eb.or()` and `eb.and()` put their conditions in parentheses, so `where((eb) => eb.or([...]))` keeps the owner filter whole. A condition written as a `sql` template is spliced as written, in Kysely too. **A Kysely condition built with `eb.or()` stays inside its parentheses, whatever the query around it.** ## Each value is bound where it is written[​](#each-value-is-bound-where-it-is-written "Direct link to Each value is bound where it is written") TypeORM binds values through named parameters in the SQL string, and the names share one namespace per query. The docs open the query builder page with [a note on it](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/query-builder/1-select-query-builder.md#L40-L42), and repeat it: [values will be overridden](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/query-builder/1-select-query-builder.md#L308) if a name is set twice. ```ts const peopleWithPets = () => dataSource .getRepository(Person) .createQueryBuilder('person') .innerJoin(Pet, 'pet', 'pet.owner_id = person.id') .select('person.first_name', 'first_name') .addSelect('pet.name', 'pet_name') const rows = await peopleWithPets() .where('person.first_name = :name', { name: 'Jennifer' }) .andWhere('pet.name = :name', { name: 'Catto' }) .getRawMany() // Both conditions compare with 'Catto'. The Jennifer and Catto row is gone. ``` Two helpers that each bind `:id` collide the same way. Kysely takes each value where the condition is written and numbers the placeholders as it compiles, so `where('person.first_name', '=', 'Jennifer').where('pet.name', '=', 'Catto')` sends two parameters and returns the row. **Kysely numbers its parameters as it compiles the statement, so no two values can share a name.** ## Kysely queries can be cancelled[​](#kysely-queries-can-be-cancelled "Direct link to Kysely queries can be cancelled") Every Kysely query's `execute()` and `stream()` accepts a web-standard [`AbortSignal`](https://kysely-org.github.io/kysely-apidoc/interfaces/AbortableQueryOptions.html), and an option chooses what happens to a query already running: stop waiting, cancel it on the database, or kill its session. TypeORM's `getMany()`, `getRawMany()`, and `stream()` take no arguments on either release, and its [`maxExecutionTime()`](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/query-builder/1-select-query-builder.md#L1034-L1036) is written into the statement as a MySQL optimizer hint. **A Kysely query can be stopped with an `AbortSignal`, before it is sent or while it runs.** ## A failed TypeORM query puts its values in the error[​](#a-failed-typeorm-query-puts-its-values-in-the-error "Direct link to A failed TypeORM query puts its values in the error") TypeORM throws a failed query as `QueryFailedError`, with the statement and every bound parameter as enumerable properties, on both releases. The values make a failure easy to reproduce, and a logger or an error reporter that serializes the error records them too, so a password hash, an API token, an email address, or any other credential or personal data bound to a failed query reaches the log. Kysely passes the driver's error through, and node-postgres adds no parameters to it. Kysely's `log` option receives the compiled query and its parameters on an error, and the default logger prints the SQL text only, so recording the values is the logger's choice. PostgreSQL's own `detail` still names the conflicting key of a unique violation, in both libraries. **Kysely's errors carry no bound values of their own, so what reaches an error reporter is what the database said.** ## Kysely sends the statement you wrote[​](#kysely-sends-the-statement-you-wrote "Direct link to Kysely sends the statement you wrote") TypeORM's builder adds to a statement from the entity's metadata. Give `person` a `deleted_at` column declared as its [delete date](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/entity/1-entities.md#L177) (`deleteDate: true` in `EntitySchema`, `@DeleteDateColumn()` with decorators), and every select and count on it gets `"deleted_at" IS NULL`. So does the `ON` condition of a join written by hand: ```ts const rows = await dataSource .getRepository(Pet) .createQueryBuilder('pet') .leftJoin(Person, 'person', 'person.id = pet.owner_id') .select('pet.name', 'name') .addSelect('person.first_name', 'owner') .withDeleted() .getRawMany() // LEFT JOIN "person" "person" // ON "person"."id" = "pet"."owner_id" AND "person"."deleted_at" IS NULL // A pet whose owner was soft-deleted is returned with owner: null. ``` The pet stays in the result, and its owner reads `null`, as if it had none. [`withDeleted()`](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/query-builder/1-select-query-builder.md#L1229-L1237) lifts the filter only from joins added after it, so called last it reaches the main table alone. The [issue about it](https://github.com/typeorm/typeorm/issues/11906) has been open since January 2026, a TypeORM collaborator [wrote](https://github.com/typeorm/typeorm/issues/11906#issuecomment-3779516272) "The current behavior looks strange to me for sure", and other users rely on the position to choose which joins keep the filter. It dates from [a 2021 fix](https://github.com/typeorm/typeorm/pull/7296) that kept soft-deleted relations out of `find`. The filter itself is a feature that keeps soft-deleted rows out of every query, and the other additions are conveniences: `getMany()` adds the primary key it needs to build entities, an insert gets `RETURNING` for generated and default columns, an update sets the update-date column, and `getRawMany()` names an unaliased column `person_first_name`. Kysely compiles the join above to the statement written, with no condition added. Both show a statement before it runs, TypeORM through `getSql()` and Kysely through `.compile()`. A soft-delete scope is a condition you write once, in a helper every query calls or in a [plugin](#kysely-is-extended-through-its-query-tree) that rewrites the query tree. **Kysely sends the statement you wrote, and changes it only through plugins you install.** ## Kysely is extended through its query tree[​](#kysely-is-extended-through-its-query-tree "Direct link to Kysely is extended through its query tree") TypeORM's extension points are its entity lifecycle: [listeners and subscribers](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/listeners-and-subscribers.md) on insert, update, and remove, custom repositories, naming strategies, column transformers, a [logger](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/logging.md) and subscribers' `beforeQuery` and `afterQuery` events, which receive the SQL text and its parameters, and a built-in [query result cache](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/query-builder/6-caching.md#L3) with Redis and database stores. The query builder keeps its clauses in an expression map and writes SQL from it, and no hook between building and running receives the query as a structure. Before it is SQL, every Kysely query is an immutable tree of [operation nodes](https://kysely-org.github.io/kysely-apidoc/interfaces/OperationNode.html), and `toOperationNode()` returns it from any builder. A [plugin](https://kysely-org.github.io/kysely-apidoc/interfaces/KyselyPlugin.html) receives that tree before it compiles and the result after it runs. The [built-in plugins](https://kysely.dev/docs/plugins.md) convert camelCase, qualify tables with a schema, deduplicate joins, handle empty `in` lists, make null comparisons safe, and parse JSON results, and `withPlugin` scopes one to a query or a derived instance. A [Kysely dialect](https://kysely-org.github.io/kysely-apidoc/interfaces/Dialect.html) is four exported factories, which is how the [community dialects](https://kysely.dev/docs/dialects.md) for BigQuery, ClickHouse, Oracle, and Firebird exist. TypeORM's drivers ship inside TypeORM, selected by the data source's `type` option, and a type it does not know is an error. **Kysely ships the interface a database implements and the tree a plugin rewrites, so new databases and rewrites live outside the library.** ## Migrate from TypeORM to Kysely one query at a time[​](#migrate-from-typeorm-to-kysely-one-query-at-a-time "Direct link to Migrate from TypeORM to Kysely one query at a time") A move from TypeORM to Kysely does not have to happen at once, or at all for the entities. ### Can Kysely and TypeORM be used together?[​](#can-kysely-and-typeorm-be-used-together "Direct link to Can Kysely and TypeORM be used together?") Yes. [kysely-typeorm](https://github.com/kysely-org/kysely-typeorm) runs Kysely over an existing `DataSource`: its [`KyselyTypeORMDialect`](https://github.com/kysely-org/kysely-typeorm/blob/f4789777c56b291666ff8f873a8fafbac9184cbd/README.md#L207-L233) reuses TypeORM's connections, and its [`KyselifyEntity`](https://github.com/kysely-org/kysely-typeorm/blob/f4789777c56b291666ff8f873a8fafbac9184cbd/README.md#L185-L198) type derives Kysely's table types from the entity classes, with no generation step. ```ts import { Kysely, PostgresAdapter, PostgresIntrospector, PostgresQueryCompiler, } from 'kysely' import { KyselyTypeORMDialect, type KyselifyEntity } from 'kysely-typeorm' interface Database { person: KyselifyEntity pet: KyselifyEntity } const db = new Kysely({ dialect: new KyselyTypeORMDialect({ kyselySubDialect: { createAdapter: () => new PostgresAdapter(), createIntrospector: (db) => new PostgresIntrospector(db), createQueryCompiler: () => new PostgresQueryCompiler(), }, typeORMDataSource: dataSource, }), }) ``` For the bridge, declare the relations in the classes above as `pets: NonAttribute` and `owner: NonAttribute`, since `KyselifyEntity` leaves `NonAttribute` properties out, and a generated key as `Generated`, which makes it optional on insert. The classes stay TypeORM entities. 1. Keep the entities, the generated migrations, and the repositories that persist entity graphs. 2. Derive Kysely's types with `KyselifyEntity`, or [generate them](https://kysely.dev/docs/generating-types.md) from the migrated database, which also catches a column the entity does not declare. 3. Start with a query that carries a `getRawMany()` annotation, that shared functions extend, or that reads JSON. Move it, inspect `.compile()`, and compare rows, nulls, ordering, and empty results. 4. Keep each transaction on one client. The bridge shares connections, not a transaction in progress. ### Can I use Kysely in a NestJS app?[​](#can-i-use-kysely-in-a-nestjs-app "Direct link to Can I use Kysely in a NestJS app?") **Yes.** Kysely needs no framework integration: a provider that returns a `Kysely` instance makes it injectable like any other service. Beside TypeORM, `KyselyTypeORMDialect` takes the `DataSource` that `@nestjs/typeorm` already [injects](https://github.com/nestjs/docs.nestjs.com/blob/3c9dc71f93c350245210075fc634980df1caa3dd/content/data/typeorm.md#L68), so both clients share its connections. Nest's own outbox, workflows, and webhooks packages also take a Kysely instance through [`fromKysely(db)`](https://github.com/nestjs/docs.nestjs.com/blob/3c9dc71f93c350245210075fc634980df1caa3dd/content/reliability/outbox.md#L1300) and join the transaction its callback receives. ## Other practical considerations[​](#other-practical-considerations "Direct link to Other practical considerations") Schema, migrations, and value conversion One TypeORM entity is the source for types, for [generated migrations](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/migrations/04-generating.md), and for `synchronize` in development. Kysely has no migration generator. Its [migrations](https://kysely.dev/docs/migrations.md) are written by hand through the schema builder or any migration tool, and its types are declared or [generated](https://kysely.dev/docs/generating-types.md) from the database, so a migration applied without regenerating them is drift the compiler cannot see. It also makes the database the source of truth: Kysely queries a schema that another service or migration tool owns, with nothing declared a second time. TypeORM's column transformers and date handling convert values on the way in and out. Kysely's types describe what the driver returns, and conversion belongs to the driver's configuration or a plugin. Decorators and the toolchain TypeORM's decorators are TypeScript's legacy decorators. Its [getting started guide](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/getting-started.md#L155-L177) asks for `experimentalDecorators`, `emitDecoratorMetadata`, and the `reflect-metadata` shim, and on TypeScript 6 and 7 its column decorators do not type-check as standard decorators. That constrains the toolchain. Node's built-in type stripping refuses a decorated class. esbuild emits no decorator metadata, so `@Column()` without a type leaves TypeORM nothing to read, and it throws when the class is defined. An explicit type on every column, or `EntitySchema` as on this page, avoids both. Kysely's `Database` interface is a type, erased like any other, and needs no compiler option. Measured package sizes and dependency trees | Published package | Compressed download | Unpacked size | Direct dependencies | | ----------------- | ------------------- | ------------- | ------------------- | | Kysely 0.29.8 | 319.6 KiB | 1.66 MiB | 0 | | TypeORM 1.1.2 | 3,137.3 KiB | 20.74 MiB | 10 | | TypeORM 0.3.31 | 2,998.6 KiB | 19.87 MiB | 15 | PostgreSQL production trees with `pg` 8.23.1, including transitive dependencies: | PostgreSQL setup | Unique production packages | | -------------------------- | -------------------------- | | Kysely 0.29.8 + pg 8.23.1 | **14** | | TypeORM 1.1.2 + pg 8.23.1 | 41 | | TypeORM 0.3.31 + pg 8.23.1 | 116 | TypeORM's package includes every driver adapter, its CLI, and its migration tooling; 1.0 [cut the tree](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/releases/1.0/01-release-notes.md#L15-L18) by replacing `glob`, `uuid`, and `sha.js` with native modules. Kysely's includes its five core dialects. Measured **November 11, 2026**. Package sizes exclude dependencies, and trees exclude optional dependencies and peer auto-installation. These are not bundle sizes or install benchmarks. ## Choosing TypeORM or Kysely[​](#choosing-typeorm-or-kysely "Direct link to Choosing TypeORM or Kysely") TypeORM vs Kysely is a choice between a data framework whose query builder takes selections and filters as strings or untyped objects, and a query builder whose types follow the query. What differs is how much of a query the compiler checks, and what else the library does. ### Why use Kysely instead of TypeORM?[​](#why-use-kysely-instead-of-typeorm "Direct link to Why use Kysely instead of TypeORM?") **Choose Kysely when queries are composed, shared, and changed, and you want TypeScript to check each change.** * References are [checked against the query](#kysely-checks-the-references-typeorm-takes-as-strings) in every clause, where TypeORM passes the string to the database. * Result types [come from the selection](#result-types-come-from-the-selection), not from the entity or an annotation you maintain. * JSON, CASE, filtered aggregates, windows, and [set operations and `MERGE`](#kysely-covers-more-of-sqls-statements) are built with checked references, and JSON and CASE results are inferred where TypeORM's are declared by hand. * [Nested results](#nested-results-stay-in-the-same-builder) are one statement and one row per parent. * Builders behave like values: [shared without cloning](#shared-queries-branch-without-mutation), [bound where each value is written](#each-value-is-bound-where-it-is-written), [grouped by `eb.or()`](#kysely-groups-the-conditions-it-builds), [sent as written](#kysely-sends-the-statement-you-wrote), and [cancelled with an `AbortSignal`](#kysely-queries-can-be-cancelled). * The [query tree is public](#kysely-is-extended-through-its-query-tree), and plugins and dialects build on it. Its types can come from the database itself, so it fits a schema that another tool, service, or team migrates, and they are plain interfaces that need no [decorator options](#decorators-and-the-toolchain). Immich, Open Collective, and Docmost [compose production queries with it](https://kysely.dev/docs/comparisons/query-builder-vs-raw-sql.md#production-code-draws-the-same-line). ### When is TypeORM the better choice?[​](#when-is-typeorm-the-better-choice "Direct link to When is TypeORM the better choice?") **Keep TypeORM when a person writes the entities and the queries, and the entity class is the unit the code thinks in: decorated classes that drive types, generated migrations, and relations hydrated into instances, with Active Record or repositories persisting the graph.** It is also the choice when the database is one Kysely has no dialect for, MongoDB or SAP HANA among them. Its query builder can stay for the queries that already work, and Kysely can run beside it for the ones that are composed. Chosen for its query builder alone, TypeORM trades the checks on this page for property names that absorb a column rename, a built-in result cache, and nested callback transactions. ### Is TypeORM still maintained?[​](#is-typeorm-still-maintained "Direct link to Is TypeORM still maintained?") **Yes.** In October 2024, after years in which, in the new maintainers' words, ["maintenance has slowed significantly"](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/blog/2024-10-01-future-of-typeorm/index.md#L8), a team from Elevantiq, the company behind Vendure, [took over from TypeORM's original maintainers](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/blog/2024-10-01-future-of-typeorm/index.md#L12-L19). 1.0 shipped in May 2026, followed by 1.1.0 in July, 1.1.1 in September, and 1.1.2 in October, with nightly builds between them. ### Should I upgrade to TypeORM 1.0 or move to Kysely?[​](#should-i-upgrade-to-typeorm-10-or-move-to-kysely "Direct link to Should I upgrade to TypeORM 1.0 or move to Kysely?") **Upgrading to 1.0 changes TypeORM's platform, APIs, and defaults, and leaves its query builder's strings as they are.** 1.0 requires [Node.js 20](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/releases/1.0/01-release-notes.md#L15), [removes long-deprecated APIs](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/releases/1.0/01-release-notes.md#L34-L66) with a [codemod](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/releases/1.0/02-upgrading-from-0.3.md#L9-L17) for most of them, and takes find options' `select` and `relations` as objects only. Apart from the two gaps below, every check on this page behaves the same on 0.3.31 and 1.1.2: references in the builder are unchecked strings, raw results are `any`, and a second `where()` and a repeated parameter name behave as they did. One typing gap closed only in 1.0. On 0.3.x, `dataSource.createQueryBuilder().update(User)`, the [first example in TypeORM's update docs](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/query-builder/3-update-query-builder.md#L6-L13), resolves to the overload that takes the values to set, so the builder's entity is `any` and `set()` accepts any key and any value. The overload dates from 0.3.0 in March 2022. The gap was [reported in January 2024](https://github.com/typeorm/typeorm/issues/10604), the issue was closed in a backlog cleanup in September 2025, and [the fix](https://github.com/typeorm/typeorm/pull/11296) merged in April 2026 for 1.0. 0.3.31, released in July 2026, still has it. 1.0 also closed a quiet gap in the find API. On 0.3.31, `find({ where: { age: undefined } })` drops the condition and returns every row, so an unset variable in a lookup reads the whole table. 1.1.2 throws, because [1.0 defaults `invalidWhereValuesBehavior` to `throw`](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/releases/1.0/01-release-notes.md#L71-L72). In Kysely, `where('age', '=', undefined)` is a type error. The two moves can also be combined. Queries moved to Kysely use none of the APIs 1.0 removes, so a team on 0.3 can move its composed queries first, [through kysely-typeorm](#can-kysely-and-typeorm-be-used-together), and upgrade the entities on its own schedule. ### Is TypeORM type-safe?[​](#is-typeorm-type-safe "Direct link to Is TypeORM type-safe?") **For entities, find options, and the values it writes, yes. For the references in its query builder, no.** The find API, `setFindOptions()`, and the builder's `values()` and `set()` are [checked against the entity](#kysely-checks-the-references-typeorm-takes-as-strings), though a find `select` still returns the whole entity type. The builder's selections, joins, filters, and ordering are strings or untyped objects the compiler does not check, and a raw result is `any` or whatever you declare. Kysely checks the references and infers the result, with [gaps of its own](#where-kyselys-checks-stop). ### Is there a type-safe query builder for TypeORM?[​](#is-there-a-type-safe-query-builder-for-typeorm "Direct link to Is there a type-safe query builder for TypeORM?") **Kysely, through [kysely-typeorm](#can-kysely-and-typeorm-be-used-together).** It runs over the existing `DataSource` and derives its table types from the entities, so queries move to checked references and inferred results one at a time while the entities, migrations, and repositories stay. ### Is Kysely faster than TypeORM?[​](#is-kysely-faster-than-typeorm "Direct link to Is Kysely faster than TypeORM?") **The database cannot tell them apart when the statements match: both send one parameterized statement, and [performance belongs to the statement](https://kysely.dev/docs/comparisons/query-builder-vs-raw-sql.md#performance-belongs-to-the-statement-not-the-authoring-tool).** The statements do not always match. TypeORM's entity results are hydrated from expanded join rows or, with the query load strategy, from three statements for one relation, and a paginated `take()` with a join runs two statements. TypeORM's own [performance guide](https://github.com/typeorm/typeorm/blob/5a572a40bae2f85a1d5f7b87a0aa88bbbaec5ab3/docs/docs/performance-optimization/2-efficient-use-of-query-builder.md#L23-L25) recommends `getRawMany()` to "avoid TypeORM processing too much information". Kysely returns rows as the database shaped them and nests in SQL. Neither library is benchmarked here. ### Is Kysely smaller than TypeORM?[​](#is-kysely-smaller-than-typeorm "Direct link to Is Kysely smaller than TypeORM?") **Yes, by a wide margin as a package and as a dependency tree.** Kysely's published package is a 319.6 KiB download with no dependencies, against 3,137.3 KiB and ten dependencies for TypeORM 1.1.2; with `pg`, the production trees are 14 and 41 packages. The [measurements](#measured-sizes) and what they exclude are above. ### Which is easier for a coding agent to use?[​](#which-is-easier-for-a-coding-agent-to-use "Direct link to Which is easier for a coding agent to use?") **Kysely checks more of what the agent writes, before the query runs.** An agent works by editing and running the compiler again, and the checks on this page sit inside that loop: a wrong reference, a stale annotation, or a misspelled JSON key is a compile error it can read and fix without a database, where TypeORM gives it a failed request or a silent `null`. Each library documents its methods in the type declarations it installs, and Kysely's inline examples are [type-checked in CI](https://kysely.dev/docs/integrations/llms.md) against the release they ship with. **Kysely types the query you write, in every clause, before it runs.** [Get started with Kysely](https://kysely.dev/docs/getting-started.md), find equivalents in the [query examples](https://kysely.dev/docs/category/examples.md), or compare [query builders with ORMs](https://kysely.dev/docs/comparisons/query-builder-vs-orm.md), [query builders with raw SQL](https://kysely.dev/docs/comparisons/query-builder-vs-raw-sql.md), [Kysely with Drizzle](https://kysely.dev/docs/comparisons/kysely-vs-drizzle.md), [Kysely with Knex](https://kysely.dev/docs/comparisons/kysely-vs-knex.md), and [Kysely with Sequelize](https://kysely.dev/docs/comparisons/kysely-vs-sequelize.md). Adoption: replacing TypeORM with Kysely [Immich](https://immich.app/) moved its server from TypeORM to Kysely in 2025. After [the database repository moved to Kysely](https://github.com/immich-app/immich/pull/16593) in March, "TypeORM is now gone from everything, outside of migrations", and [a pull request in July removed it](https://github.com/immich-app/immich/pull/20366), the old migrations included. --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # SQL query builder vs ORM in TypeScript **Kysely is a type-safe SQL query builder for TypeScript, not an ORM.** A SQL query builder is a library that constructs SQL through a programming language API: you choose the tables, columns, joins, and expressions; the library generates the SQL and binds the parameters. Kysely also checks those queries against your database types and infers their results. An **object–relational mapper (ORM)** maps application models and relationships to database tables and keys. Its model API lets you request related objects or save a graph of records, coordinating the SQL needed to perform that work. **A model API has you work backwards from the statement you need to the options that produce it; a query builder has you write the statement.** Reuse a query, add a computed selection, change its joins, or introduce a subquery, all through the same interface. **Reads multiply and keep changing; write workflows settle into a few shared functions.** A few shared transaction functions can handle creating pages and comments while lists, searches, exports, and reports keep changing. Query composition pays off across those reads; your application coordinates the related writes an ORM could automate. That asymmetry is the case for a query builder, and the examples below follow it. ## A query builder composes SQL; an ORM maps models[​](#a-query-builder-composes-sql-an-orm-maps-models "Direct link to A query builder composes SQL; an ORM maps models") Compose SQLWork with models SQL query builders & toolkits * [Kysely](https://kysely.dev/docs/getting-started.md) * [Knex](https://knexjs.org/) * [Zapatos](https://jawj.github.io/zapatos/) Compose queries against tables and columns. ORMs with query builders * [Drizzle](https://orm.drizzle.team/docs/select)SQL and relational query APIs * [TypeORM](https://typeorm.io/docs/query-builder/select-query-builder/)with its own query builder * [Lucid](https://lucid.adonisjs.com/docs/introduction)with Knex * [Objection.js](https://vincit.github.io/objection.js/guide/query-examples.html) with Knex * [MikroORM](https://mikro-orm.io/docs/kysely) with Kysely Combine SQL composition with model and relationship operations. ORM model APIs * [Sequelize](https://sequelize.org/docs/v6/core-concepts/model-querying-basics/) * [Orange ORM](https://orange-orm.io/) * [Prisma 7](https://www.prisma.io/docs/orm/prisma-client/queries) Query models and persist related records through model operations. Grouped by the interfaces they offer, not ranked by capability. Zapatos combines SQL templates with typed query helpers; Prisma also supports raw SQL and TypedSQL. An ORM can include a builder without making the builder itself an ORM. Objects and relational queries organize data differently: an application might work with a page and its comments as an object graph, while a report needs rows containing an author, a page count, and a computed flag. This difference is part of the **object–relational impedance mismatch**. An ORM bridges the representations through model mappings and relationship operations; a query builder lets each query define its result directly, including results that don't correspond to a persistent model. An ORM can provide both interfaces. [Objection.js builds on Knex](https://vincit.github.io/objection.js/guide/query-examples.html), adding model and relationship operations. [MikroORM integrates Kysely](https://mikro-orm.io/docs/kysely), so you can keep ORM persistence and compose queries with Kysely in the same transaction. Using that integration is a query builder choice too. Returning JavaScript objects does not make a library an ORM: even [node-postgres returns plain row objects](https://node-postgres.com/features/queries#row-mode). Neither do TypeScript result types or migration tools. The distinction is the model mapping and the operations built around it. ### Is Kysely an ORM?[​](#is-kysely-an-orm "Direct link to Is Kysely an ORM?") No. Kysely has no model classes, no relationship mappings, and no persistence layer. It composes SQL statements, checks them against your database types, and infers their result types; the rows it returns are plain objects, not managed entities. By the definition above, typed results and bundled [migration APIs](https://kysely.dev/docs/migrations.md) don't make it an ORM. To add model persistence on top of it, use an ORM that integrates it, such as [MikroORM](https://mikro-orm.io/docs/kysely). What about schema definitions, migrations, and code generation? Products marketed as ORMs often bundle mapping and persistence with schema definitions, migrations, and code generation. Here, **ORM** describes the model mapping and persistence layer; **data framework** describes the larger stack. A standalone builder can also supply schema and migration tools without introducing model persistence. ## Query builder composition survives changing requirements[​](#query-builder-composition-survives-changing-requirements "Direct link to Query builder composition survives changing requirements") Start with pages owned by a user and an optional title filter. Both approaches handle this list well. The examples follow how the query changes as it needs a parent title, a computed flag, and eventually a recursive permission lookup. They use Kysely with PostgreSQL: ```ts // db is a Kysely instance. Here, page has numeric id and // owner_id columns, nullable numeric parent_id, non-null text title, // and non-null updated_at timestamps represented by Date values. function searchPages(userId: number, title: string | undefined) { let query = db.selectFrom('page').where('page.owner_id', '=', userId) if (title !== undefined) { query = query.where('page.title', '=', title) } return query } const pageQuery = searchPages(userId, title) .select(['page.id', 'page.title']) .orderBy('page.id') .limit(20) const pages = await pageQuery.execute() // Inferred result: // { id: number; title: string }[] ``` ### Reusing filters for an export and parent titles[​](#reusing-filters-for-an-export-and-parent-titles "Direct link to Reusing filters for an export and parent titles") An export reuses the filters, adds the timestamp, and leaves out pagination: ```ts const exportedPages = await searchPages(userId, title) .select(['page.id', 'page.title', 'page.updated_at']) .orderBy('page.id') .execute() // Inferred result: // { id: number; title: string; updated_at: Date }[] ``` An admin view needs each parent's title. Extend the paginated query before execution: ```ts const pagesWithParents = await pageQuery .leftJoin('page as parent', 'parent.id', 'page.parent_id') .select('parent.title as parent_title') .execute() // Inferred result: // { id: number; title: string; parent_title: string | null }[] ``` **Both views reuse the same query function; each statement carries only the selections and joins it needs.** The result gains a nullable `parent_title` because a page may have no parent. Rename the alias and the caller's result type changes with it. Assuming `page.id` is unique, the parent join above preserves one row per page. A to-many join could multiply rows and change which pages fit within the limit. SQL composition gives you control over that structure; it still requires understanding its effect on the result. ### Adding a computed result[​](#adding-a-computed-result "Direct link to Adding a computed result") The list now needs to flag pages with an immediate child updated more recently than the page itself. Add a correlated `exists` expression: ```ts const pagesWithNewerChildren = await pageQuery .select((eb) => eb .exists( eb .selectFrom('page as child') .select('child.id') .whereRef('child.parent_id', '=', 'page.id') .whereRef('child.updated_at', '>', 'page.updated_at'), ) .as('has_newer_children'), ) .execute() // Inferred result: // { id: number; title: string; has_newer_children: SqlBool }[] ``` PostgreSQL returns a boolean for each page without loading its children or multiplying the outer rows. Kysely checks the references in both scopes and infers the new result property. **Each new requirement so far was one addition to an existing query, and the result type followed it.** Kysely's builders are immutable, so extending `pageQuery` leaves the original list query available to other callers. A model API may require a mapped computed property: MikroORM's [SQL formulas](https://mikro-orm.io/docs/defining-entities#formulas), for example, put the expression in entity metadata. That is useful for a shared model property. Here, the flag is needed only for this list, so its query defines the expression and result name together. ### What a model API adds[​](#what-a-model-api-adds "Direct link to What a model API adds") When you want a page and its comments as related objects, a model API can handle the loading and assembly. With Objection.js, assume a `Page` model mapped to `page` and a declared `comments` relation: ```ts const pagesWithComments = await Page.query() .where('owner_id', userId) .orderBy('id') .limit(20) .withGraphFetched('comments') ``` Objection's [`withGraphFetched`](https://vincit.github.io/objection.js/guide/query-examples.html#eager-loading) loads the relation through additional queries and attaches comment models to each page. Its Knex-based builder remains available for SQL composition. The model mapping earns its place when those relationship operations are work you want the library to handle. The next requirement is different: no relation mapping describes a rule inherited through an unknown number of ancestors. ## The same query builder interface for recursive queries[​](#the-same-query-builder-interface-for-recursive-queries "Direct link to The same query builder interface for recursive queries") A documentation app stores pages in a tree using a nullable `page.parent_id`. A user's permission comes from the nearest explicit rule: on the requested page itself, or on one of its ancestors. The query must return the rule's page, level, and distance. The number of ancestor steps is not known in advance, so a fixed-depth parent selection does not cover the requirement. A recursive CTE expresses that traversal in one statement. Assume PostgreSQL, an acyclic tree, and at most one rule per page/user. The SQL for the permission lookup ```sql with recursive ancestors as ( select id, parent_id, 0 as depth from page where id = $1 union all select parent.id, parent.parent_id, ancestors.depth + 1 from page as parent inner join ancestors on ancestors.parent_id = parent.id ) select ancestors.id as page_id, page_access.level, ancestors.depth from ancestors inner join page_access on page_access.page_id = ancestors.id where page_access.user_id = $2 order by ancestors.depth limit 1; ``` The database performs traversal, rule lookup, ordering, and limiting in one statement. [Docmost uses recursive ancestors for page restrictions](https://github.com/docmost/docmost/blob/7bef7b1a00d31991f009865ec14c8d06540eb1f0/apps/server/src/database/repos/page/page-permission.repo.ts#L325-L373); this query simplifies that requirement. Compose it with Kysely using the same query operations as the earlier queries. Assume the page column types above, numeric `page_access.page_id` and `page_access.user_id`, and a non-null string `page_access.level`. The `pageId` and `userId` values are numbers: ```ts import { sql } from 'kysely' const nearestRule = db .withRecursive('ancestors', (qb) => qb .selectFrom('page') .select(['id', 'parent_id', sql`0`.as('depth')]) .where('id', '=', pageId) .unionAll((qb) => qb .selectFrom('page as parent') .innerJoin('ancestors', 'ancestors.parent_id', 'parent.id') .select(['parent.id', 'parent.parent_id']) .select((eb) => eb('ancestors.depth', '+', 1).as('depth')), ), ) .selectFrom('ancestors') .innerJoin('page_access', 'page_access.page_id', 'ancestors.id') .where('page_access.user_id', '=', userId) .select(['ancestors.id as page_id', 'page_access.level', 'ancestors.depth']) .orderBy('ancestors.depth') .limit(1) const rule = await nearestRule.executeTakeFirst() // Inferred: { page_id: number; level: string; depth: number } | undefined ``` Remove the `page_access` join and its remaining references become type errors. The seed expression declares its `number` result type explicitly; arbitrary SQL fragments are not checked by Kysely. A relationship loader can fetch an ancestor graph; this requirement asks the database to return just the nearest matching rule. A recursive CTE combines traversal, filtering, and limiting in one statement. ### What changed as the requirements grew?[​](#what-changed-as-the-requirements-grew "Direct link to What changed as the requirements grew?") | Requirement | Query builder | Model API | | ------------------------------------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | | List, export, and parent title | Reuse a query function; vary selections, joins, and limit. | Reuse filters and model selections; request mapped relationships. | | Computed flag for one list | Add an `exists` selection to the existing query. | Use a computed-property feature or the SQL builder. | | Choose the flag's SQL structure | Rewrite the join and aggregation as a subquery. | Adjust the mapped expression or use the SQL builder. | | Find the nearest inherited permission | Compose a recursive CTE, join, order, and limit. | Use a suitable hierarchy feature or move to a SQL API. | **The builder's advantage is continuity as the query changes.** The same selections, joins, expressions, and query functions serve the lists, exports, and permission lookup, whether you use a standalone builder or an ORM's integrated one. ## A query builder gives production queries room to tune[​](#a-query-builder-gives-production-queries-room-to-tune "Direct link to A query builder gives production queries room to tune") When a model operation produces an expensive query, you still need to understand the SQL: its joins, row counts, and execution plan. Then you must map that understanding back into model options, or switch to a SQL API. This is where the abstraction **leaks**: the database details become necessary to use the higher-level interface effectively. **A query builder keeps those SQL decisions in the interface you already use.** Tuning is writing the statement you want, not working backwards to the model options that produce it. Inspect the generated statement and its plan against real data, then adjust the query and indexes. Kysely's [`.compile()`](https://kysely.dev/docs/recipes/splitting-query-building-and-execution.md) exposes the SQL and bound parameters for inspection. Suppose the flag above was first implemented by joining children, grouping by page, and counting the matches: ```ts const flaggedPages = await pageQuery .leftJoin('page as child', (join) => join .onRef('child.parent_id', '=', 'page.id') .onRef('child.updated_at', '>', 'page.updated_at'), ) .select((eb) => eb(eb.fn.count('child.id'), '>', 0).as('has_newer_children')) .groupBy('page.id') .execute() ``` Rewriting this as the correlated `exists` query takes a few local edits: drop the join and grouping, and move the two join conditions into the subquery. The filters, callers, and one-row-per-page result shape stay as they are. The join-and-count version asks for matching children to be aggregated; `exists` asks whether any qualifying child exists. Compare the generated SQL and plans to establish whether the rewrite helps on your data. **The builder gives you a direct path from the SQL change to the application change.** Tuning changes the query through the same interface that built it. [Raw SQL gives the same statement control](https://kysely.dev/docs/comparisons/query-builder-vs-raw-sql.md); a builder also lets callers extend shared queries through functions and ordinary control flow. The SQL concepts you use with a database specialist or in a SQL console carry into application code. ## Statement count is explicit; N+1 is a composition choice[​](#statement-count-is-explicit-n1-is-a-composition-choice "Direct link to Statement count is explicit; N+1 is a composition choice") **One model API call does not necessarily mean one SQL statement.** Relationship loaders can use joins or separate queries. Either can be appropriate: joins across collections can multiply rows, while querying each parent's children in a loop creates N+1 round trips. [Objection.js explains its fetching and joining strategies](https://vincit.github.io/objection.js/api/query-builder/eager-methods.html). **With a query builder, the statement count is whatever your code composed; there is no loading strategy to configure or audit.** Some ORMs also track object identity and pending changes. [MikroORM's unit of work](https://mikro-orm.io/docs/unit-of-work), for example, writes managed-entity changes through `flush()`. These services can save coordination when several operations share managed entities within a request. **A standalone builder's results are ordinary values: mutating them never schedules a database write.** ## Your code owns the writes an ORM would coordinate[​](#your-code-owns-the-writes-an-orm-would-coordinate "Direct link to Your code owns the writes an ORM would coordinate") **An ORM can coordinate related writes from a graph of models.** With Objection.js, assume `Page` and `Comment` models with a `comments` relation joining `page.id` to `comment.page_id`: ```ts const page = await Page.transaction(async (trx) => { return await Page.query(trx).insertGraph({ title: 'Getting started', comments: [{ body: 'Add an installation example.' }], }) }) ``` Objection's [`insertGraph`](https://vincit.github.io/objection.js/guide/query-examples.html#graph-inserts) uses the relationship mapping to order inserts and pass generated keys. The explicit transaction makes the operation atomic; `insertGraph` does not start one automatically. With Kysely and PostgreSQL, your code coordinates the same writes, typically as an ordinary shared function. For this example, assume `page` has a generated numeric `id` and a required `title`, and `comment` requires `page_id` and `body`, with no other required insert inputs: ```ts async function createPageWithComment(title: string, body: string) { return await db.transaction().execute(async (trx) => { const page = await trx .insertInto('page') .values({ title }) .returning('id') .executeTakeFirstOrThrow() await trx.insertInto('comment').values({ page_id: page.id, body }).execute() return page }) } const page = await createPageWithComment( 'Getting started', 'Add an installation example.', ) ``` The transaction commits when the callback succeeds and rolls back if it throws. Your function owns insert ordering and key passing; callers need only its inputs and result. Write policies such as timestamps and optimistic version checks also belong in application code. The asymmetry holds here: adding the computed flag, export, or permission lookup does not change `createPageWithComment`. When shared functions cover the write workflows, that coordination is a modest cost beside the recurring benefit of query composition. Frequently changing graphs of related records give an ORM more work to save. ## Type safety depends on the library[​](#type-safety-depends-on-the-library "Direct link to Type safety depends on the library") SQL-first composition does not require result type inference. Query builders differ in whether they check references and expressions or infer result types, and an ORM's typed models do not guarantee those capabilities in its SQL API either. To assess a library's type safety, try removing a join, renaming an alias, or adding a nullable selection: does the caller's type follow the query? The examples above run that test. The [left-joined parent title](#reusing-filters-for-an-export-and-parent-titles) arrives as `string | null`, and renaming its alias changes the caller's result type. Removing the `page_access` join from the [permission lookup](#the-same-query-builder-interface-for-recursive-queries) turns its remaining references into type errors. [Kysely vs Drizzle](https://kysely.dev/docs/comparisons/kysely-vs-drizzle.md) runs the same test between two SQL-first libraries, [Kysely vs TypeORM](https://kysely.dev/docs/comparisons/kysely-vs-typeorm.md) against a data framework's string-based builder, and [Kysely vs Sequelize](https://kysely.dev/docs/comparisons/kysely-vs-sequelize.md) against a model API's finder options. Inferred types depend on accurate database declarations and the driver's runtime value mapping. Kysely does not validate returned rows against those types or convert values to match a TypeScript annotation. ## Other practical considerations[​](#other-practical-considerations "Direct link to Other practical considerations") Schema tooling and production migrations **A query builder lets you choose schema tooling independently of model persistence.** You can author migrations through SQL or a schema API, use a dedicated migration tool, and [generate database types](https://kysely.dev/docs/generating-types.md) from the resulting schema. Model-diff generators save work by drafting migrations. Production rollout still requires deployment decisions: adding a replacement column, deploying code that writes both, backfilling, switching readers, and eventually removing the old column. [Prisma documents expand-and-contract migrations](https://www.prisma.io/docs/guides/database/data-migration) within its own workflow. Either approach can support staged rollouts; the team chooses their order and deployment boundaries. Generated and hand-authored migrations also need review against database constraints. PostgreSQL's [`CREATE INDEX CONCURRENTLY`](https://www.postgresql.org/docs/current/sql-createindex.html), for example, allows writes during the build but cannot run inside a transaction block. Database-specific features and portability A builder can support multiple engines while exposing their specific features. Kysely, for example, provides distinct operations for PostgreSQL-style conflict handling and MySQL-style duplicate-key updates. Assess how directly a library exposes the SQL your application needs. Both builders and model APIs can reduce the code needed to target multiple engines. Differences in constraints, collations, JSON behavior, transactions, indexes, and query plans still require testing. If portability is required, test the shared behavior and performance your application depends on. Querying a database you don't own Teams querying shared schemas, customer systems, or read-only views may have no control over schema design or migrations. **When the job is querying an existing database, an ORM can add a model layer with little work to do.** In a read-only integration, cascade persistence, change tracking for writes, and model-driven migrations provide little value, while entity mappings still need to be defined and kept consistent with someone else's schema. A builder lets you compose queries against the tables, views, and joins the database exposes, with database types supplied separately if needed. An adapter or SDK can accept a builder configured by its consumer, leaving schema ownership with that consumer. ORM relationship loading and value conversion can still be useful, and [Objection.js treats schema management as a separate concern](https://vincit.github.io/objection.js/guide/models.html). Choose a model layer when those services simplify the integration enough to justify its mappings. For query-specific reads, a standalone builder often covers the requirement directly. Comparing development package footprints Package footprint depends on the implementation, rather than the category. These measurements compare particular setups: two standalone query builders and five [data frameworks](#orms-data-frameworks-and-plain-objects). These representative PostgreSQL development setups include `pg` 8.23.1, schema/model definitions, migration and generation tools, and installed transitive dependencies. Their capabilities differ: Kysely includes migration authoring and execution, while several data framework setups also generate migrations from model changes. ShowCompressed downloads (compressedBytes) **Query builders**Data frameworks 079.79 MiB 1. [Kysely](https://www.npmjs.com/package/kysely/v/0.29.7)0.29.7 · 41 packages 1.50 MiB 2. [MikroORM](https://www.npmjs.com/package/@mikro-orm/postgresql/v/7.2.5)7.2.5 · 42 packages 1.68 MiB 3. [Knex](https://www.npmjs.com/package/knex/v/3.3.0)3.3.0 · 56 packages 1.88 MiB 4. [TypeORM](https://www.npmjs.com/package/typeorm/v/1.1.1)1.1.1 · 60 packages 4.58 MiB 5. [Sequelize](https://www.npmjs.com/package/sequelize/v/6.37.8)6.37.8 · 133 packages 5.10 MiB 6. [Drizzle](https://www.npmjs.com/package/drizzle-orm/v/0.45.4)0.45.4 · 32 packages 15.38 MiB 7. [Prisma 7](https://www.npmjs.com/package/@prisma/client/v/7.10.1)7.10.1 · 155 packages 79.79 MiB Measured October 25, 2026 on macOS arm64. Includes pg 8.23.1, each setup's schema/migration/generation tools, and installed transitive dependencies. Bars share a linear scale. These are npm package payloads, excluding Node.js itself and the TypeScript compiler. Generated application files and install-script downloads are also excluded. Footprint varies substantially by implementation: this MikroORM setup is close to Kysely despite including model persistence and migration generation. These measurements compare the selected development setups; they do not predict runtime performance or deployment bundle size. What's included in each setup? Main library versions appear in the chart; additional tool versions and the selected workflows are listed here. The Prisma measurement uses version 7.10.1, not version 8. | Setup | Packages beyond `pg` | Schema, migrations, and generation | | ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [Kysely](https://kysely.dev/docs/migrations.md) | `kysely`, `kysely-ctl` 0.22.0, `kysely-typegen` 2.1.0 | Bundled schema builder and migration APIs, CLI migration authoring/execution, and [database types generated programmatically](https://github.com/theoludwig/kysely-typegen) from PostgreSQL. | | [Knex](https://knexjs.org/guide/migrations.html) | `knex`, `ts-node` 10.9.2 | Bundled schema builder and migration CLI, with ts-node loading TypeScript configuration/migrations. No code generation required. | | [Drizzle](https://orm.drizzle.team/docs/drizzle-kit-generate) | `drizzle-orm`, `drizzle-kit` 0.31.11 | Hand-authored table definitions; Kit generates and runs migrations. | | Prisma 7 | `@prisma/client`, `@prisma/adapter-pg`, `prisma` CLI, all 7.10.1 | Hand-authored Prisma schema; CLI migrates and generates client code. | | [TypeORM](https://typeorm.io/docs/migrations/executing/) | `typeorm`, `ts-node` 10.9.2 | Decorated entities; bundled CLI generates and runs migrations, with ts-node loading TypeScript sources. Includes reflect-metadata. | | [Sequelize](https://sequelize.org/docs/v6/other-topics/typescript/) | `sequelize`, `sequelize-cli` 6.6.5, `pg-hstore` 2.3.4, `sequelize-typescript` 2.1.6, `reflect-metadata` 0.2.2, `ts-node` 10.9.2 | Decorated TypeScript models using the recommended add-on; CLI scaffolds JavaScript migrations and discovers TypeScript migrations, with ts-node registered to execute them. | | [MikroORM](https://mikro-orm.io/docs/guide/project-setup) | `@mikro-orm/core`, `@mikro-orm/postgresql`, `@mikro-orm/cli`, `@mikro-orm/migrations`, all 7.2.5, plus `jiti` 2.7.0 | Entities authored with [defineEntity](https://mikro-orm.io/docs/define-entity), MikroORM 7’s primary documented approach; CLI generates and runs migrations, with [jiti loading TypeScript migrations](https://mikro-orm.io/docs/typescript-loaders). Includes its SQL layer and Kysely dependency. | TypeScript is assumed for every setup and excluded from package counts and both size totals, including when a tool requires it as a peer. Knex, TypeORM, and Sequelize still include ts-node and its other dependencies. CLI and migration packages count even when installed as development dependencies. The measurement includes hard dependencies, required peers, and compatible optional dependencies installed by npm, including packaged native tool binaries. Compressed downloads count each package version once; unpacked sizes count every installed copy. Shared Node.js and application type declarations are excluded unless pulled in by a tool. Kysely database types are generated with `kysely-typegen`; the other setups use hand-authored model/table definitions, with Prisma client generation included. Additional generators, seeders, and unrelated integrations are excluded. Install-script downloads and generated application files are also excluded, so these totals measure development package payloads rather than complete disk usage or deployed application bundles. ## Choosing a query builder or ORM[​](#choosing-a-query-builder-or-orm "Direct link to Choosing a query builder or ORM") **Choose a query builder when you need direct control over how queries are composed and changed.** The list, computed flag, recursive lookup, and SQL rewrite above use the same operations. You can change the statement's structure without looking for a model API option that produces it. A standalone builder lets you work from the database schema, with query functions for reads and shared transaction functions for related writes. Compare that with maintaining an ORM model layer: | Responsibility | Standalone builder with database-generated types | ORM model layer with an integrated builder | | ----------------------------------------------------- | -------------------------------------------------------------- | ------------------------------------------------------------------------ | | Describe tables and columns | Database schema plus generated declarations. | Entity mappings; the integrated builder can derive types from them. | | Express the list, flag, export, and permission lookup | Query functions. | Query functions through the builder, or model operations where they fit. | | Create a page and comment | A transaction function owns insert order and key passing. | Model operations can coordinate the related writes. | | Add a column such as `archived_at` | Migrate, regenerate declarations, and update affected queries. | Update the schema and entity mapping, and update affected queries. | **Keep the model layer when its relationship loading, related writes, or managed entities save recurring work.** An integrated builder lets you retain those services and use SQL composition where you need it. [MikroORM's Kysely integration](https://mikro-orm.io/docs/kysely) is one way to combine them. Try one related write and one query that has needed substantial changes. Compare the persistence code you must own, how easily each API expresses the next requirement, and the statements it executes. **Choose Kysely when you want SQL composition with checked references and inferred results, without maintaining an ORM model layer.** [Get started with Kysely](https://kysely.dev/docs/getting-started.md), explore [query examples](https://kysely.dev/docs/category/examples.md), or learn how to [generate database types](https://kysely.dev/docs/generating-types.md). Adoption: OpenClaw uses Kysely for runtime queries OpenClaw's [contributor guide](https://github.com/openclaw/openclaw/blob/28340c41f8b88ae6d11488e523808315319747b5/AGENTS.md#L71) requires Kysely for ordinary SQLite access, reserving raw SQL for schema, migrations, bootstrap, and justified primitives. Its creator, Peter Steinberger, also [described replacing Drizzle with Kysely in one of his projects](https://x.com/steipete/status/2005692454553673900). A builder gives coding agents SQL operations to compose and compiler feedback as references and result shapes change. Your team can review the resulting query structure directly. --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # SQL query builder vs raw SQL in TypeScript **Raw SQL in TypeScript is a whole statement written as SQL text: a template beside application code, or a `.sql` file compiled to a typed call.** A SQL query builder composes the statement through an API; Kysely also checks each operation against the database types and infers the result. A statement that never changes is where raw SQL is strongest, and the builder still checks it; every statement that does change is the builder's. **A team that composes raw SQL is already maintaining a query builder, a bespoke and untyped one; a team that writes typed SQL files has done without one until the first dynamic query.** This page starts with the fixed statement, then follows one asset query through optional filters, a shared count, an export, and nested tags, and tries to break it. ## Both kinds of raw SQL write the statement whole[​](#both-kinds-of-raw-sql-write-the-statement-whole "Direct link to Both kinds of raw SQL write the statement whole") Whole statementComposed statement SQL code generators * [PgTyped](https://pgtyped.dev/docs/)Annotations and parameter spreads * [Prisma TypedSQL](https://www.prisma.io/docs/orm/v7/prisma-client/using-raw-sql/typedsql)Typed parameter comments * [sqlc](https://docs.sqlc.dev/)Macros and query annotations Compile whole statements in SQL files to typed application calls. SQL clients * [node-postgres](https://node-postgres.com/features/queries#parameterized-query)SQL strings with $1 placeholders * [Postgres.js](https://github.com/porsager/postgres/blob/570be764d96c8c13e6a1a262103bf60974571b67/README.md#building-queries)SQL templates and fragments * [Slonik](https://github.com/gajus/slonik)SQL templates and result schemas Write SQL beside application code, with clients that bind values. SQL query builders * [Kysely](https://kysely.dev/docs/getting-started.md)Checked composition and inferred results * [Knex](https://knexjs.org/guide/query-builder.html)Composition through an API * [Zapatos](https://jawj.github.io/zapatos/)Typed helpers over SQL templates Compose clauses and expressions through an API that checks them. SQL checkers * [SafeQL](https://safeql.dev/)ESLint plugin for SQL Check whole statements against the database. Grouped by where the statement is written, not ranked by capability. Each tool adds something a SQL console does not accept: interpolation and fragments in templates, parameter syntax or macros in SQL files. PgTyped also accepts SQL in TypeScript. **SQL templates** such as [Postgres.js](https://github.com/porsager/postgres/blob/570be764d96c8c13e6a1a262103bf60974571b67/README.md#building-queries) and [Slonik](https://github.com/gajus/slonik) live beside application code, bind values, and compose through fragments; [SafeQL](https://safeql.dev/) checks the statements it can see whole. **Typed SQL files** are whole statements in `.sql` files that a SQL code generator, [PgTyped](https://pgtyped.dev/docs/), [Prisma TypedSQL](https://www.prisma.io/docs/orm/v7/prisma-client/using-raw-sql/typedsql), or [sqlc](https://docs.sqlc.dev/), turns into typed calls. Knex and Zapatos sit with the builders in the figure and are not compared here: Knex composes without checking references against a schema, and Zapatos types shortcut helpers over SQL templates. ## A whole statement still gains checked references in the builder[​](#a-whole-statement-still-gains-checked-references-in-the-builder "Direct link to A whole statement still gains checked references in the builder") The statement to test the builder against is the one raw SQL is best at: complete, fixed, and readable on its own. A report of each owner's unfiled favorites is one statement with a CTE and two joins: ```sql with favorites as ( select asset_tag.asset_id from asset_tag inner join tag on tag.id = asset_tag.tag_id where tag.name = 'favorite' ) select asset.id, asset.name, asset.owner_id from asset inner join favorites on favorites.asset_id = asset.id where asset.folder_id is null order by asset.owner_id, asset.name; ``` It runs unchanged in a SQL console, under `EXPLAIN ANALYZE`, and in a review by someone who does not write TypeScript. In application code it is a string: nothing checks `asset.owner_id` against the schema, the result type is whatever the caller annotates, and a renamed column is found by search. The same report in Kysely: ```ts const unfiledFavorites = await db .with('favorites', (qb) => qb .selectFrom('asset_tag') .innerJoin('tag', 'tag.id', 'asset_tag.tag_id') .select('asset_tag.asset_id') .where('tag.name', '=', 'favorite'), ) .selectFrom('asset') .innerJoin('favorites', 'favorites.asset_id', 'asset.id') .select(['asset.id', 'asset.name', 'asset.owner_id']) .where('asset.folder_id', 'is', null) .orderBy('asset.owner_id') .orderBy('asset.name') .execute() // Inferred: { id: string; name: string; owner_id: string }[] ``` **Raw SQL's best case is a fixed statement, and the builder still checks it.** Every reference is completed by the editor as it is typed and checked against the database declarations, the result type is inferred from the selection, and renaming `asset.name` turns the report into a compile error. The join on `favorites.asset_id` is checked against what the CTE selected, so a column dropped from the CTE fails in the clause that reads it, and the caller annotates nothing. The builder version reads as an API, not as a second language: `with`, `selectFrom`, `innerJoin`, `select`, `where`, and `orderBy` are SQL's clauses under SQL's names, with the same column references, so the skill the builder asks for is SQL. Where the API stops looking like SQL, at `fn` and the JSON helpers below, [`.compile()`](https://kysely.dev/docs/recipes/splitting-query-building-and-execution.md) shows the statement and its parameters for the console and the reviewer, and [`.explain()`](https://kysely-org.github.io/kysely-apidoc/interfaces/Explainable.html) runs it under `EXPLAIN ANALYZE`. A statement tuned in a console or handed over by a DBA is translated once, clause for clause, and every later edit to it is checked. A fixed write is checked the same way. An insert that omits a required column is a valid statement until it runs: PostgreSQL prepares it without objection and rejects the row at execution. Kysely's `values()` accepts the table's columns only and requires each one the declaration marks neither generated nor nullable: ```ts await db .insertInto('asset') .values({ id: 'asset-7', name: 'IMG_0001.jpg' }) // TypeScript error: owner_id is required // Argument of type '{ id: string; name: string; }' is not assignable to parameter of type 'InsertExpression'. Type '{ id: string; name: string; }' is not assignable to type 'InsertObject'. Property 'owner_id' is missing in type '{ id: string; name: string; }' but required in type '{ id: ValueExpression; name: ValueExpression; owner_id: ValueExpression; }'. .execute() ``` `set()` on an update holds the same line, and `returning()` infers its result like a selection. **A SQL checker stops where PostgreSQL does, at a statement that prepares; the builder also requires the columns the row needs.** A typed SQL file misses the same insert: the statement is valid, so the generator types it, and the row still fails. **The builder checks the fixed statement in the same API the next section composes with, so a fixed query and a dynamic one share one toolchain, one type source, and no generation step between a query edit and its type check.** The declarations are [generated](https://kysely.dev/docs/generating-types.md) when the schema changes. A typed SQL file checks the report too, with the database, and derives its type, though not the nullability a left join adds, as the export below shows. That check is a generation run after every query edit, against a live database for PgTyped and TypedSQL. Whole raw statements keep their place in migrations, bootstrap, and one-off scripts, where there is no composition to check. The three forms part at the first filter that applies only sometimes. ## Every variation is a fragment, a file, or a checked operation[​](#every-variation-is-a-fragment-a-file-or-a-checked-operation "Direct link to Every variation is a fragment, a file, or a checked operation") An asset list starts as an owner's assets, sorted by name and ID and limited to 50; any of the three forms writes that in a few lines. Then the list needs an optional album filter, which adds a join and a predicate, and an optional name prefix. Database types and request options for the following examples ```ts interface Database { asset: { id: string name: string owner_id: string folder_id: string | null } folder: { id: string; name: string } album_asset: { album_id: string; asset_id: string } asset_tag: { asset_id: string; tag_id: string } tag: { id: string; name: string } } ``` ```ts type AssetOptions = { ownerId: string albumId?: string includeTags: boolean namePrefix?: string } ``` Assume a `Kysely` instance named `db`, a configured Postgres.js client named `sql`, one row per album/asset pair, and PostgreSQL. The prefix filter uses SQL LIKE-pattern semantics: `%` and `_` in the input remain wildcards. ### Add the optional join and filters[​](#add-the-optional-join-and-filters "Direct link to Add the optional join and filters") Put the shared query in a function. Kysely's `$call` hands the builder to a function and returns its result, so each addition is a plain `if`; the join is applied inside the branch that needs it, and the references in that branch are checked against the joined table: ```ts function matchingAssets(options: AssetOptions) { return db .selectFrom('asset') .where('asset.owner_id', '=', options.ownerId) .$call((qb) => { if (options.albumId !== undefined) { qb = qb .innerJoin('album_asset', 'album_asset.asset_id', 'asset.id') .where('album_asset.album_id', '=', options.albumId) } if (options.namePrefix !== undefined) { qb = qb.where('asset.name', 'like', options.namePrefix + '%') } return qb }) } ``` With raw SQL, the same rules live in fragment helpers. Postgres.js numbers the parameters; a `pool.query` string built by concatenation renumbers its `$n` placeholders by hand each time a filter moves: ```ts const albumJoin = (options: AssetOptions) => options.albumId !== undefined ? sql`inner join album_asset on album_asset.asset_id = asset.id` : sql`` const albumFilter = (options: AssetOptions) => options.albumId !== undefined ? sql`and album_asset.album_id = ${options.albumId}` : sql`` const nameFilter = (options: AssetOptions) => options.namePrefix !== undefined ? sql`and asset.name like ${options.namePrefix + '%'}` : sql`` function matchingAssetSql(options: AssetOptions) { return sql` from asset ${albumJoin(options)} where asset.owner_id = ${options.ownerId} ${albumFilter(options)} ${nameFilter(options)} ` } ``` ```ts const assets = await sql<{ id: string; name: string }[]>` select asset.id, asset.name ${matchingAssetSql(options)} order by asset.name, asset.id limit 50 ` ``` The album join and its predicate are one branch in Kysely and two fragments that must agree here, because the join lands before `where` and the predicate after it, and one fragment cannot carry both. **Three helpers that each decide when their text applies, and a function that places them in order, are a query builder: one the team maintains through tests, since no type records which fragment is present.** `$call` is the typed form of the ternary and the empty template, the part of the raw version that was never SQL either. **The first conditional in a shared helper takes every statement that uses it out of the checker's coverage.** [SafeQL's Postgres.js integration](https://safeql.dev/compatibility/postgres.js.html#support-matrix) lists conditional fragment selection as unsupported, so every statement assembled from these helpers is outside what it checks. Its maintainer [explains the limit as combinatorial](https://github.com/ts-safeql/safeql/issues/100#issuecomment-1311048387): each condition doubles the forms to check. Kysely checks the album branch once, inside its `if`. A typed SQL file cannot add or remove clauses, so each optional filter becomes a nullable parameter guarded by `is null or`, and album membership becomes `exists`. With Prisma TypedSQL, parameters are typed by comments and the rest is plain SQL: ```sql -- @param {String} $1:ownerId -- @param {String} $2:albumId? -- @param {String} $3:namePrefix? select asset.id, asset.name from asset where asset.owner_id = $1 and ($2::text is null or exists ( select 1 from album_asset where album_asset.asset_id = asset.id and album_asset.album_id = $2 )) and ($3::text is null or asset.name like $3 || '%') order by asset.name, asset.id limit 50; ``` PgTyped and sqlc write the same statement with `:albumId` and `sqlc.narg(album_id)`, syntax that fails in a console. **A SQL file with tool syntax is the input to a tool that produces a statement, which is what a builder is too.** [PgTyped's documentation](https://pgtyped.dev/docs/dynamic-queries) states the design: "pgTyped doesn't support query composition or concatenation", and "forces you to move the dynamic logic into the SQL layer". The nullable parameter, with the casts PostgreSQL [requires on a reused parameter](https://github.com/jackc/pgx/issues/2233), is the mild form of that move. The rest is catalogued in sqlc's [dynamic queries discussion](https://github.com/sqlc-dev/sqlc/discussions/364), open since 2020: `CASE WHEN` switches that defeat indexes, placeholders filled by application code, and a query builder beside the generator. **The composition did not disappear; it moved into the statement, where the planner pays for every variation, or back into application code, where nothing checks it.** ### Reuse the filters for a list and a count[​](#reuse-the-filters-for-a-list-and-a-count "Direct link to Reuse the filters for a list and a count") The list chooses its fields and pagination after calling `matchingAssets`; the total reuses the filters without inheriting the limit: ```ts const assets = await matchingAssets(options) .select(['asset.id', 'asset.name']) .orderBy('asset.name') .orderBy('asset.id') .limit(50) .execute() // Inferred: { id: string; name: string }[] const total = await matchingAssets(options) .select((eb) => eb.cast(eb.fn.countAll(), 'integer').as('count')) .executeTakeFirstOrThrow() // Inferred: { count: number } ``` Each consumer keeps its own selections and pagination; each inherits the shared query's scope and result type. Kysely's builders are immutable, so extending one does not change another, and a new shared rule goes into `matchingAssets` once. Fragments give Postgres.js the same reuse of the predicates and none of the result: each template declares its shape again by hand, so every consumer is one more annotation that nothing checks against its SQL. A generated call returns one fixed shape, so the count is a second statement that repeats the predicates. **Checking both statements does not establish that their filtering rules agree.** ### Add a folder name through a left join[​](#add-a-folder-name-through-a-left-join "Direct link to Add a folder name through a left join") An export needs each asset's folder name, and unfiled assets have none: ```ts const exportedAssets = await matchingAssets(options) .leftJoin('folder', 'folder.id', 'asset.folder_id') .select(['asset.id', 'asset.name', 'folder.name as folder_name']) .orderBy('asset.name') .orderBy('asset.id') .execute() // Inferred: { id: string; name: string; folder_name: string | null }[] ``` `folder_name` is nullable because the left join made it nullable. The Postgres.js caller annotates the result itself, and nothing objects to `folder_name: string`. A generator has to infer nullability, because PostgreSQL's [`RowDescription`](https://www.postgresql.org/docs/current/protocol-message-formats.html) reports a column's type and source table and nothing about whether it can be null. Put this export in a `.sql` file and Prisma TypedSQL and PgTyped generate `folder_name: string`: the source column is `NOT NULL`, the left join is not consulted, and `folder_name.toUpperCase()` compiles and throws on the first unfiled asset. sqlc tracks the join and emits `string | null`. **Nullability is where two of the three generators type the column wrong, and it is what Kysely tracks through the join.** ### Add optional nested tags[​](#add-optional-nested-tags "Direct link to Add optional nested tags") The list needs tags when requested. Add a correlated JSON subquery with `jsonArrayFrom` from `kysely/helpers/postgres`: ```ts const assets = await matchingAssets(options) .select(['asset.id', 'asset.name']) .$if(options.includeTags, (qb) => qb.select((eb) => jsonArrayFrom( eb .selectFrom('asset_tag') .innerJoin('tag', 'tag.id', 'asset_tag.tag_id') .select(['tag.id', 'tag.name']) .whereRef('asset_tag.asset_id', '=', 'asset.id') .orderBy('tag.name'), ).as('tags'), ), ) .orderBy('asset.name') .orderBy('asset.id') .limit(50) .execute() // Inferred: { id: string; name: string; tags?: { id: string; name: string }[] }[] ``` Requested tags use `[]` when none exist; unrequested tags omit the key and the subquery. The inner references are checked, including the one to the outer `asset`. A fixed statement cannot remove a column, so a SQL file is a second statement chosen in TypeScript, and the database describes its `tags` column as `json`: TypedSQL and PgTyped generate `JsonValue | null` and `Json | null`, and sqlc `string | null`. **A JSON column's shape is where generated types stop; the nested shape is known only to the code that wrote the subquery, and Kysely wrote it.** See [conditional selects](https://kysely.dev/docs/recipes/conditional-selects.md) and [nested relations](https://kysely.dev/docs/recipes/relations.md). ### What changed as the requirements grew?[​](#what-changed-as-the-requirements-grew "Direct link to What changed as the requirements grew?") | Requirement | Kysely | SQL templates | Typed SQL files | | ---------------------------------------- | ------------------------------------------------------ | ---------------------------------------------------------- | ------------------------------------------------------------------------------------- | | Add a conditional join and predicate | Extend the builder; references checked in the branch. | Compose fragments; the statements leave SafeQL's coverage. | Nullable parameters and `exists`; one statement, and one plan, for every combination. | | Share filters across list, count, export | One unfinished query; each caller selects its fields. | Share fragments; each caller declares its own annotation. | A statement per shape; repeat the predicates, or use a view. | | Left join an optional folder name | The column arrives as `string \| null`. | The annotation says whatever the caller wrote. | A new statement; `string` from TypedSQL and PgTyped, `string \| null` from sqlc. | | Optional nested tags | A conditional selection; the nested shape is inferred. | A conditional fragment; the annotation declares the shape. | A second statement; the column is JSON, or a string. | **Each requirement cost the builder one checked operation; it cost the fragments a helper and an annotation, and the SQL files a statement.** ## Try to break the shared query[​](#try-to-break-the-shared-query "Direct link to Try to break the shared query") The test of a composition layer is what happens when someone changes it without reading all of it. ### A consumer cannot reference a table the shared query only sometimes joins[​](#a-consumer-cannot-reference-a-table-the-shared-query-only-sometimes-joins "Direct link to A consumer cannot reference a table the shared query only sometimes joins") A per-album export needs each row's album ID. With fragments, the caller adds the column: ```ts const albumExport = await sql<{ id: string; name: string; album_id: string }[]>` select asset.id, asset.name, album_asset.album_id ${matchingAssetSql(options)} order by asset.name, asset.id ` ``` This compiles and runs for requests that supply an album. For the rest, the helper omits the join and PostgreSQL rejects `album_asset.album_id`; the fragment records nothing about when `album_asset` is present. The same caller does not compile with Kysely: ```ts const albumExport = await matchingAssets(options) .select(['asset.id', 'asset.name', 'album_asset.album_id']) // TypeScript error // No overload matches this call. Overload 1 of 3, '(selections: readonly SelectExpression[]): SelectQueryBuilder', gave the following error. Type '"album_asset.album_id"' is not assignable to type 'SelectExpression'. Overload 2 of 3, '(callback: SelectCallback): SelectQueryBuilder', gave the following error. Argument of type 'string[]' is not assignable to parameter of type 'SelectCallback'. Type 'string[]' provides no match for the signature '(eb: ExpressionBuilder): readonly SelectExpression[]'. Overload 3 of 3, '(selection: SelectExpression): SelectQueryBuilder', gave the following error. Argument of type 'string[]' is not assignable to parameter of type 'SelectExpression'. .execute() ``` `album_asset` is in scope only inside the `if` that joins it; the shared query's type is the builder before the join, so it does not offer the table. The error names the decision: require the album and join it unconditionally, or select the column inside the branch that has it. **A fragment carries SQL text and bound values; a Kysely builder also carries the tables in scope and the result selected so far.** Whether a join applies the right rule or preserves row counts still needs review and tests. With SQL files the export is a new statement with its own `exists`. **A generated call cannot be extended by its caller, which prevents the mistake and also prevents the extension.** [TypedSQL documents its dynamic-column limit](https://www.prisma.io/docs/orm/v7/prisma-client/using-raw-sql/typedsql#dynamic-sql-queries-with-dynamic-columns) as a hand-off to unsafe raw queries. ### A rename reaches every caller through the compiler[​](#a-rename-reaches-every-caller-through-the-compiler "Direct link to A rename reaches every caller through the compiler") Suppose a migration renames `asset.name` to `asset.label`, and an agent must update the application. With Kysely, [regenerate the declarations](https://kysely.dev/docs/generating-types.md) once and type-check: ```ts interface Database { asset: { id: string label: string owner_id: string folder_id: string | null } // ... } function matchingAssets(options: AssetOptions) { return ( db .selectFrom('asset') // ... .$call((qb) => { // ... if (options.namePrefix !== undefined) { qb = qb.where('asset.name', 'like', options.namePrefix + '%') // TypeScript error // Argument of type '"asset.name"' is not assignable to parameter of type 'ReferenceExpression'. } return qb }) ) } const assets = await matchingAssets(options) .select(['asset.id', 'asset.name']) // TypeScript error // No overload matches this call. Overload 1 of 3, '(selections: readonly SelectExpression[]): SelectQueryBuilder', gave the following error. Type '"asset.name"' is not assignable to type 'SelectExpression'. Overload 2 of 3, '(callback: SelectCallback): SelectQueryBuilder', gave the following error. Argument of type 'string[]' is not assignable to parameter of type 'SelectCallback'. Type 'string[]' provides no match for the signature '(eb: ExpressionBuilder): readonly SelectExpression[]'. Overload 3 of 3, '(selection: SelectExpression): SelectQueryBuilder', gave the following error. Argument of type 'string[]' is not assignable to parameter of type 'SelectExpression'. .orderBy('asset.id') ``` The compiler lists every stale reference: the shared filter and each consumer's selection, in the list, the count, the export, and the tags listing, and the editor completes `asset.label` where `asset.name` used to be. The same edit in the raw SQL forms is a text search. A SQL template's declared annotation keeps claiming `name` exists until a runtime value is undefined. A generated type catches the drift at the next generation run, and only in the statements it generated. For PgTyped and TypedSQL that run needs a database at the new schema; for sqlc it needs the schema files and the generator; for all three it produces regenerated output to review before the compiler has anything to compare. **A type check is a verification step an agent can run on every edit, with nothing but the repository.** The database enters Kysely's loop when the schema changes, not when a query does; a query edit, such as selecting `asset.name as label`, changes the consumer's inferred type and its callers' errors with no generation step. ## SQL checkers verify a statement; Kysely verifies a composition[​](#sql-checkers-verify-a-statement-kysely-verifies-a-composition "Direct link to SQL checkers verify a statement; Kysely verifies a composition") **A SQL checker verifies a statement it can see whole; Kysely verifies each operation that application code adds to a query.** SafeQL and the generators ask PostgreSQL to describe a statement, so its grammar, functions, and result columns are checked against the database. Kysely's grammar is library output, tested per dialect across its API, so a misplaced clause is not a mistake application code can make; a reference, a result shape, or a composition is, and those are what its types check. What the builder leaves to the first run is a short list; raw SQL outside a checker's coverage leaves the whole statement there. Kysely's coverage ends where a statement's meaning depends on the database rather than the declarations: an unqualified `id` after a join of two tables that both have one compiles and PostgreSQL rejects it as ambiguous, a selected column missing from `GROUP BY` compiles, `fn('lower', ['asset.id'])` compiles whatever the column's type, and a `sql` expression is typed as declared. The declarations are also a snapshot: a migration applied without regenerating them is drift the compiler cannot see and a checker reading the live database can, so regeneration belongs in the migration step or in CI. The checker and the builder are not exclusive: SafeQL's [Kysely plugin](https://safeql.dev/compatibility/kysely.html), experimental, inlines the `sql` expressions in a Kysely query and checks them against the database, so the one input the builder takes on trust can have a checker too. A checker with the database catches each of those gaps in a fixed statement; the builder sends them to the first run with the references and the composition already checked. **Every mistake a builder prevents is one that unchecked SQL finds at runtime, one round trip at a time.** Outside a checker's coverage, which ends at the first conditional, a misspelled column, a parameter numbered wrong, or a comparison against the wrong type is found by running the statement and reading the database's message, and PostgreSQL [stops at the first error](https://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY): one per attempt. With Kysely those are compile errors, reported together, before a connection is opened. For a coding agent that is an execution loop per mistake, against a database it may not have. ### Can raw SQL be type-safe?[​](#can-raw-sql-be-type-safe "Direct link to Can raw SQL be type-safe?") **Yes, one statement at a time.** A declared result type checks callers against the annotation, not the SQL; a runtime schema, such as Slonik's with a [parser interceptor](https://github.com/gajus/slonik/blob/5130ed4320686ab8876cb2296d35f9a1b2cccc93/README.md#result-parser-interceptor), rejects an incompatible row when the query runs; SafeQL and the generators check the statements they see whole. None of them establish conditional composition. Kysely does not validate returned rows, so runtime validation still has a place at boundaries. ## Performance belongs to the statement, not the authoring tool[​](#performance-belongs-to-the-statement-not-the-authoring-tool "Direct link to Performance belongs to the statement, not the authoring tool") **The database receives a parameterized statement either way, and cannot tell which tool wrote it.** Compiling a builder to SQL is work in application memory before the round trip; the comparison that matters is between the statements and their plans. For a request with only an owner filter, [`.compile()`](https://kysely.dev/docs/recipes/splitting-query-building-and-execution.md) on the list query returns the parameters `['owner-1', 50]` and this SQL: ```sql select "asset"."id", "asset"."name" from "asset" where "asset"."owner_id" = $1 order by "asset"."name", "asset"."id" limit $2 ``` A request without an album sends no `album_asset` reference, so each shape the application composes is planned as the statement it is, with that statement's indexes. The fixed `($2::text is null or ...)` statement serves every combination with one text: after five executions of a prepared statement PostgreSQL [may keep a generic plan](https://www.postgresql.org/docs/current/sql-prepare.html#SQL-PREPARE-NOTES), chosen without the parameter values, and PgTyped's documentation warns that "highly dynamic SQL queries can lead to worse DB execution times". **The fixed statement asks the planner to serve every combination from one plan; the composed one asks the application to own the combinations and gives each its own plan.** ## Kysely's escape hatch is a typed expression inside the builder[​](#kyselys-escape-hatch-is-a-typed-expression-inside-the-builder "Direct link to Kysely's escape hatch is a typed expression inside the builder") **Raw SQL has a place inside Kysely: as an expression inside a composed query, not a statement beside it.** Kysely does not cover all of SQL; it covers what applications write most, extends that coverage release by release, and types the escape hatch for the rest. A `sql` template inside a query is an expression like any other: a reference passed through `eb.ref` is checked against the tables in scope, values bind as parameters, and the declared result type flows into the query. The builder's `like` operator has no `ESCAPE` clause; a [reusable helper](https://kysely.dev/docs/recipes/reusable-helpers.md) supplies it: ```ts import { Expression, sql } from 'kysely' function like(column: Expression, pattern: string, escape = '\\') { return sql`${column} like ${pattern} escape ${escape}` } ``` ```ts const matches = await matchingAssets(options) .where((eb) => like(eb.ref('asset.name'), pattern)) .select(['asset.id', 'asset.name']) .limit(50) .execute() // Inferred: { id: string; name: string }[] ``` A whole statement through the `sql` tag gives up every check on this page; keep that form for migrations and scripts, and `sql.raw` for trusted syntax such as an identifier. See [raw expressions](https://kysely.dev/docs/recipes/raw-sql.md) and the [SQL template API](https://kysely-org.github.io/kysely-apidoc/interfaces/Sql.html). ## Production code draws the same line[​](#production-code-draws-the-same-line "Direct link to Production code draws the same line") OpenClaw's [contributor guide](https://github.com/openclaw/openclaw/blob/28340c41f8b88ae6d11488e523808315319747b5/AGENTS.md#L71), written for coding agents, requires Kysely for ordinary SQLite access and limits raw SQL to schema, migrations, bootstrap, and justified primitives. **Schema, migrations, and bootstrap are written as SQL; the queries application code runs go through the builder.** The same composition appears in larger codebases: * [Immich](https://github.com/immich-app/immich/blob/0733cc10ee7a0c8ebd5d37b1804b5c28944b7cdd/server/src/repositories/asset.repository.ts#L572-L624) composes optional relation selections and a lateral subquery for stacked assets. * [Open Collective](https://github.com/opencollective/opencollective-api/blob/0a59b37c8b33574ee8d9d9a586d5a19506fd5921/server/graphql/v2/query/collection/OrdersCollectionQuery.ts#L780-L826) conditionally adds currency conversion through a correlated exchange-rate lookup. * [Docmost](https://github.com/docmost/docmost/blob/7bef7b1a00d31991f009865ec14c8d06540eb1f0/apps/server/src/database/repos/page/page-permission.repo.ts#L326-L366) composes recursive ancestors for page restrictions with the same builder interface as its simpler queries. ## Other practical considerations[​](#other-practical-considerations "Direct link to Other practical considerations") SQL injection A query builder does not prevent SQL injection on its own, and raw SQL does not invite it on its own. Every client here binds values as parameters; injection enters through request text placed in SQL syntax, which [Postgres.js `sql.unsafe`](https://github.com/porsager/postgres/blob/570be764d96c8c13e6a1a262103bf60974571b67/README.md#unsafe-raw-string-queries) and Kysely's `sql.raw` both send as SQL. Column names and sort directions are syntax, so every workflow allow-lists them; pass an allow-listed column to `orderBy` and a misspelled entry is a type error, while Kysely's [dynamic references](https://kysely-org.github.io/kysely-apidoc/classes/DynamicModule.html) leave the allow-list to you. **Safe parameterization is not the reason to adopt a builder; raw SQL has it. The checked composition API is.** Type-checking cost Raw SQL costs nothing at the type level. Kysely's checks are computed by the compiler, and a schema with hundreds of tables or a deeply composed query can slow type-checking and the editor. Generated declarations keep that cost tied to schema size, not query count, and conditional branches and helpers typed with `Expression` keep individual queries shallow. Incremental adoption Kysely's PostgreSQL dialect takes an existing node-postgres `Pool`, so adoption runs one helper at a time while the remaining `pool.query` calls keep running. Engines, drivers, and portability Raw SQL is written in one engine's grammar, with its placeholder style, identifier quoting, and functions. PgTyped is PostgreSQL only. Prisma TypedSQL supports PostgreSQL, MySQL, and SQLite, with argument types declared manually on SQLite. sqlc supports the same three; its TypeScript plugin targets `pg`, Postgres.js, `mysql2`, and `better-sqlite3`, and its README states that it is "still in early access". Kysely ships dialects for PostgreSQL, MySQL, SQLite, and Microsoft SQL Server, compiles the same operations to each engine's syntax, and exposes engine-specific features such as PostgreSQL conflict handling and MySQL duplicate-key updates. Most applications never change engines, so portability is a weak reason on its own to adopt a builder; it matters for libraries, multi-engine products, and teams that test on a lighter engine. ## Choosing raw SQL or Kysely[​](#choosing-raw-sql-or-kysely "Direct link to Choosing raw SQL or Kysely") ### Why use a query builder instead of raw SQL?[​](#why-use-a-query-builder-instead-of-raw-sql "Direct link to Why use a query builder instead of raw SQL?") **Because application queries change, and a query builder is the only form here that checks the change itself, not only the statement it produces.** Raw SQL binds the same parameters and sends the same statement; what it leaves to review, tests, and search, Kysely's types report before a connection is opened. ### When does raw SQL belong in a TypeScript application?[​](#when-does-raw-sql-belong-in-a-typescript-application "Direct link to When does raw SQL belong in a TypeScript application?") **Where there is no composition to check: migrations and DDL, bootstrap, one-off scripts, and the expression a builder cannot express.** Try one endpoint whose filters are repeated across a list and count. Add a shared rule, change a selected alias, and let a consumer reference a conditional join. Compare the edits, the steps before anything can tell you the edit was valid, and the statements the database receives. **Write application queries in Kysely, fixed or composed: references checked, results inferred, and the composition layer checked rather than maintained.** [Get started with Kysely](https://kysely.dev/docs/getting-started.md), explore [query examples](https://kysely.dev/docs/category/examples.md), learn how to [generate database types](https://kysely.dev/docs/generating-types.md), or compare [Kysely with Drizzle](https://kysely.dev/docs/comparisons/kysely-vs-drizzle.md). --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Dialects A dialect is the glue between Kysely and the underlying database engine. Check the [API docs](https://kysely-org.github.io/kysely-apidoc/interfaces/Dialect.html) to learn how to build your own. ## Core dialects[​](#core-dialects "Direct link to Core dialects") | Dialect | Link | | ---------------------------- | ------------------------------------------------------------------------- | | PostgreSQL | | | MySQL | | | Microsoft SQL Server (MSSQL) | | | SQLite | | | PGlite | | ## Organization dialects[​](#organization-dialects "Direct link to Organization dialects") | Dialect | Link | | -------------------- | -------------------------------------------------- | | Postgres.js | | | SingleStore Data API | | ## Community dialects[​](#community-dialects "Direct link to Community dialects") | Dialect | Link | | ----------------------------- | ----------------------------------------------------------------------------- | | PlanetScale Serverless Driver | | | Cloudflare D1 | | | Cloudflare Durable Objects | | | Cloudflare Durable Objects | | | AWS RDS Data API | | | SurrealDB | | | Neon | | | Xata | | | AWS S3 Select | | | libSQL/sqld | | | Fetch driver | | | SQLite WASM | | | Deno SQLite | | | Deno SQLite3 | | | Node SQLite | | | TiDB Cloud Serverless Driver | | | Capacitor SQLite Kysely | | | BigQuery | | | Clickhouse | | | PGLite | | | Oracle | | | Firebird | | | MariaDB | | --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Inserts, updates and deletions Some databases like postgres also allow you to run other queries than selects in CTEs. On these databases CTEs are extremely powerful: ```ts const result = await db .with('new_person', (db) => db .insertInto('person') .values({ first_name: 'Jennifer', age: 35, }) .returning('id') ) .with('new_pet', (db) => db .insertInto('pet') .values({ name: 'Doggo', species: 'dog', is_favorite: true, // Use the id of the person we just inserted. owner_id: db .selectFrom('new_person') .select('id') }) .returning('id') ) .selectFrom(['new_person', 'new_pet']) .select([ 'new_person.id as person_id', 'new_pet.id as pet_id' ]) .execute() ``` --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Simple selects Common table expressions (CTE) are a great way to modularize complex queries. Essentially they allow you to run multiple separate queries within a single roundtrip to the DB. Since CTEs are a part of the main query, query optimizers inside DB engines are able to optimize the overall query. For example, postgres is able to inline the CTEs inside the using queries if it decides it's faster. ```ts const result = await db // Create a CTE called `jennifers` that selects all // persons named 'Jennifer'. .with( 'jennifers', db .selectFrom('person') .where('first_name', '=', 'Jennifer') .select(['id', 'age']), ) // Select all rows from the `jennifers` CTE and // further filter it. // To refer to a CTE in another CTE, use the callback variant of `with`. .with('adult_jennifers', (db) => db.selectFrom('jennifers').where('age', '>', 18).select(['id', 'age']), ) // Finally select all adult jennifers that are // also younger than 60. .selectFrom('adult_jennifers') .where('age', '<', 60) .selectAll() .execute() ``` --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Single row Delete a single row: ```ts const result = await db .deleteFrom('person') .where('person.id', '=', 1) .executeTakeFirst() console.log(result.numDeletedRows) ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [deleteFrom method](https://kysely-org.github.io/kysely-apidoc/classes/Kysely.html#deleteFrom) * [returning method](https://kysely-org.github.io/kysely-apidoc/classes/DeleteQueryBuilder.html#returning) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Complex values In addition to primitives, the values can also be arbitrary expressions. You can build the expressions by using a callback and calling the methods on the expression builder passed to it: ```ts import { sql } from 'kysely' const ani = "Ani" const ston = "ston" const result = await db .insertInto('person') .values(({ ref, selectFrom, fn }) => ({ first_name: 'Jennifer', last_name: sql`concat(${ani}, ${ston})`, middle_name: ref('first_name'), age: selectFrom('person') .select(fn.avg('age').as('avg_age')), })) .executeTakeFirst() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [values method](https://kysely-org.github.io/kysely-apidoc/classes/InsertQueryBuilder.html#values) * [onConflict method](https://kysely-org.github.io/kysely-apidoc/classes/InsertQueryBuilder.html#onConflict) * [returning method](https://kysely-org.github.io/kysely-apidoc/classes/InsertQueryBuilder.html#returning) * [insertInto method](https://kysely-org.github.io/kysely-apidoc/classes/Kysely.html#insertInto) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Insert subquery You can create an `INSERT INTO SELECT FROM` query using the `expression` method. This API doesn't follow our WYSIWYG principles and might be a bit difficult to remember. The reasons for this design stem from implementation difficulties. ```ts const result = await db.insertInto('person') .columns(['first_name', 'last_name', 'age']) .expression((eb) => eb .selectFrom('pet') .select((eb) => [ 'pet.name', eb.val('Petson').as('last_name'), eb.lit(7).as('age'), ]) ) .execute() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [values method](https://kysely-org.github.io/kysely-apidoc/classes/InsertQueryBuilder.html#values) * [onConflict method](https://kysely-org.github.io/kysely-apidoc/classes/InsertQueryBuilder.html#onConflict) * [returning method](https://kysely-org.github.io/kysely-apidoc/classes/InsertQueryBuilder.html#returning) * [insertInto method](https://kysely-org.github.io/kysely-apidoc/classes/Kysely.html#insertInto) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Multiple rows On dialects that support it (for example PostgreSQL) you can insert multiple rows by providing an array. Note that the return value is once again very dialect-specific. Some databases may only return the id of the *last* inserted row and some return nothing at all unless you call `returning`. ```ts await db .insertInto('person') .values([{ first_name: 'Jennifer', last_name: 'Aniston', age: 40, }, { first_name: 'Arnold', last_name: 'Schwarzenegger', age: 70, }]) .execute() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [values method](https://kysely-org.github.io/kysely-apidoc/classes/InsertQueryBuilder.html#values) * [onConflict method](https://kysely-org.github.io/kysely-apidoc/classes/InsertQueryBuilder.html#onConflict) * [returning method](https://kysely-org.github.io/kysely-apidoc/classes/InsertQueryBuilder.html#returning) * [insertInto method](https://kysely-org.github.io/kysely-apidoc/classes/Kysely.html#insertInto) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Returning data On supported dialects like PostgreSQL you need to chain `returning` to the query to get the inserted row's columns (or any other expression) as the return value. `returning` works just like `select`. Refer to `select` method's examples and documentation for more info. ```ts const result = await db .insertInto('person') .values({ first_name: 'Jennifer', last_name: 'Aniston', age: 40, }) .returning(['id', 'first_name as name']) .executeTakeFirstOrThrow() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [values method](https://kysely-org.github.io/kysely-apidoc/classes/InsertQueryBuilder.html#values) * [onConflict method](https://kysely-org.github.io/kysely-apidoc/classes/InsertQueryBuilder.html#onConflict) * [returning method](https://kysely-org.github.io/kysely-apidoc/classes/InsertQueryBuilder.html#returning) * [insertInto method](https://kysely-org.github.io/kysely-apidoc/classes/Kysely.html#insertInto) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Single row Insert a single row: ```ts const result = await db .insertInto('person') .values({ first_name: 'Jennifer', last_name: 'Aniston', age: 40 }) .executeTakeFirst() // `insertId` is only available on dialects that // automatically return the id of the inserted row // such as MySQL and SQLite. On PostgreSQL, for example, // you need to add a `returning` clause to the query to // get anything out. See the "returning data" example. console.log(result.insertId) ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [values method](https://kysely-org.github.io/kysely-apidoc/classes/InsertQueryBuilder.html#values) * [onConflict method](https://kysely-org.github.io/kysely-apidoc/classes/InsertQueryBuilder.html#onConflict) * [returning method](https://kysely-org.github.io/kysely-apidoc/classes/InsertQueryBuilder.html#returning) * [insertInto method](https://kysely-org.github.io/kysely-apidoc/classes/Kysely.html#insertInto) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Aliased inner join You can give an alias for the joined table like this: ```ts await db.selectFrom('person') .innerJoin('pet as p', 'p.owner_id', 'person.id') .where('p.name', '=', 'Doggo') .selectAll() .execute() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [innerJoin method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#innerJoin) * [leftJoin method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#leftJoin) * [rightJoin method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#rightJoin) * [fullJoin method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#fullJoin) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Complex join You can provide a function as the second argument to get a join builder for creating more complex joins. The join builder has a bunch of `on*` methods for building the `on` clause of the join. There's basically an equivalent for every `where` method (`on`, `onRef` etc.). You can do all the same things with the `on` method that you can with the corresponding `where` method (like [OR expressions for example](https://kysely.dev/docs/examples/WHERE/or-where)). See the `where` method documentation for more examples. ```ts await db.selectFrom('person') .innerJoin( 'pet', (join) => join .onRef('pet.owner_id', '=', 'person.id') .on('pet.name', '=', 'Doggo') .on((eb) => eb.or([ eb('person.age', '>', 18), eb('person.age', '<', 100) ])) ) .selectAll() .execute() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [innerJoin method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#innerJoin) * [leftJoin method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#leftJoin) * [rightJoin method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#rightJoin) * [fullJoin method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#fullJoin) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Simple inner join Simple `inner join`s can be done by providing a table name and two columns to join: ```ts const result = await db .selectFrom('person') .innerJoin('pet', 'pet.owner_id', 'person.id') // `select` needs to come after the call to `innerJoin` so // that you can select from the joined table. .select(['person.id', 'pet.name as pet_name']) .execute() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [innerJoin method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#innerJoin) * [leftJoin method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#leftJoin) * [rightJoin method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#rightJoin) * [fullJoin method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#fullJoin) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Subquery join You can join a subquery by providing two callbacks: ```ts const result = await db.selectFrom('person') .innerJoin( (eb) => eb .selectFrom('pet') .select(['owner_id as owner', 'name']) .where('name', '=', 'Doggo') .as('doggos'), (join) => join .onRef('doggos.owner', '=', 'person.id'), ) .selectAll('doggos') .execute() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [innerJoin method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#innerJoin) * [leftJoin method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#leftJoin) * [rightJoin method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#rightJoin) * [fullJoin method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#fullJoin) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Source row existence Update a target column based on the existence of a source row: ```ts const result = await db .mergeInto('person as target') .using('pet as source', 'source.owner_id', 'target.id') .whenMatchedAnd('target.has_pets', '!=', 'Y') .thenUpdateSet({ has_pets: 'Y' }) .whenNotMatchedBySourceAnd('target.has_pets', '=', 'Y') .thenUpdateSet({ has_pets: 'N' }) .executeTakeFirstOrThrow() console.log(result.numChangedRows) ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [mergeInto method](https://kysely-org.github.io/kysely-apidoc/classes/Kysely.html#mergeInto) * [using method](https://kysely-org.github.io/kysely-apidoc/classes/MergeQueryBuilder.html#using) * [whenMatched method](https://kysely-org.github.io/kysely-apidoc/classes/WheneableMergeQueryBuilder.html#whenMatched) * [thenUpdateSet method](https://kysely-org.github.io/kysely-apidoc/classes/MatchedThenableMergeQueryBuilder.html#thenUpdateSet) * [thenDelete method](https://kysely-org.github.io/kysely-apidoc/classes/MatchedThenableMergeQueryBuilder.html#thenDelete) * [thenDoNothing method](https://kysely-org.github.io/kysely-apidoc/classes/MatchedThenableMergeQueryBuilder.html#thenDoNothing) * [whenNotMatched method](https://kysely-org.github.io/kysely-apidoc/classes/WheneableMergeQueryBuilder.html#whenNotMatched) * [thenInsertValues method](https://kysely-org.github.io/kysely-apidoc/classes/NotMatchedThenableMergeQueryBuilder.html#thenInsertValues) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Temporary changes table Merge new entries from a temporary changes table: ```ts const result = await db .mergeInto('wine as target') .using( 'wine_stock_change as source', 'source.wine_name', 'target.name', ) .whenNotMatchedAnd('source.stock_delta', '>', 0) .thenInsertValues(({ ref }) => ({ name: ref('source.wine_name'), stock: ref('source.stock_delta'), })) .whenMatchedAnd( (eb) => eb('target.stock', '+', eb.ref('source.stock_delta')), '>', 0, ) .thenUpdateSet('stock', (eb) => eb('target.stock', '+', eb.ref('source.stock_delta')), ) .whenMatched() .thenDelete() .executeTakeFirstOrThrow() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [mergeInto method](https://kysely-org.github.io/kysely-apidoc/classes/Kysely.html#mergeInto) * [using method](https://kysely-org.github.io/kysely-apidoc/classes/MergeQueryBuilder.html#using) * [whenMatched method](https://kysely-org.github.io/kysely-apidoc/classes/WheneableMergeQueryBuilder.html#whenMatched) * [thenUpdateSet method](https://kysely-org.github.io/kysely-apidoc/classes/MatchedThenableMergeQueryBuilder.html#thenUpdateSet) * [thenDelete method](https://kysely-org.github.io/kysely-apidoc/classes/MatchedThenableMergeQueryBuilder.html#thenDelete) * [thenDoNothing method](https://kysely-org.github.io/kysely-apidoc/classes/MatchedThenableMergeQueryBuilder.html#thenDoNothing) * [whenNotMatched method](https://kysely-org.github.io/kysely-apidoc/classes/WheneableMergeQueryBuilder.html#whenNotMatched) * [thenInsertValues method](https://kysely-org.github.io/kysely-apidoc/classes/NotMatchedThenableMergeQueryBuilder.html#thenInsertValues) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # A single column Select a single column: ```ts const persons = await db .selectFrom('person') .select('id') .where('first_name', '=', 'Arnold') .execute() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [select method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#select) * [selectAll method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#selectAll) * [selectFrom method](https://kysely-org.github.io/kysely-apidoc/classes/Kysely.html#selectFrom) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Aliases You can give an alias for selections and tables by appending `as the_alias` to the name: ```ts const persons = await db .selectFrom('person as p') .select([ 'first_name as fn', 'p.last_name as ln' ]) .execute() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [select method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#select) * [selectAll method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#selectAll) * [selectFrom method](https://kysely-org.github.io/kysely-apidoc/classes/Kysely.html#selectFrom) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # All columns The `selectAll` method generates `SELECT *`: ```ts const persons = await db .selectFrom('person') .selectAll() .execute() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [select method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#select) * [selectAll method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#selectAll) * [selectFrom method](https://kysely-org.github.io/kysely-apidoc/classes/Kysely.html#selectFrom) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # All columns of a table Select all columns of a table: ```ts const persons = await db .selectFrom('person') .selectAll('person') .execute() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [select method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#select) * [selectAll method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#selectAll) * [selectFrom method](https://kysely-org.github.io/kysely-apidoc/classes/Kysely.html#selectFrom) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Column with a table Select a single column and specify a table: ```ts const persons = await db .selectFrom(['person', 'pet']) .select('person.id') .execute() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [select method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#select) * [selectAll method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#selectAll) * [selectFrom method](https://kysely-org.github.io/kysely-apidoc/classes/Kysely.html#selectFrom) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Complex selections You can select arbitrary expression including subqueries and raw sql snippets. When you do that, you need to give a name for the selections using the `as` method: ```ts import { sql } from 'kysely' const persons = await db.selectFrom('person') .select(({ eb, selectFrom, or, val, lit }) => [ // Select a correlated subquery selectFrom('pet') .whereRef('person.id', '=', 'pet.owner_id') .select('pet.name') .orderBy('pet.name') .limit(1) .as('first_pet_name'), // Build and select an expression using // the expression builder or([ eb('first_name', '=', 'Jennifer'), eb('first_name', '=', 'Arnold') ]).as('is_jennifer_or_arnold'), // Select a raw sql expression sql`concat(first_name, ' ', last_name)`.as('full_name'), // Select a static string value val('Some value').as('string_value'), // Select a literal value lit(42).as('literal_value'), ]) .execute() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [select method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#select) * [selectAll method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#selectAll) * [selectFrom method](https://kysely-org.github.io/kysely-apidoc/classes/Kysely.html#selectFrom) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Distinct ```ts const persons = await db.selectFrom('person') .select('first_name') .distinct() .execute() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [select method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#select) * [selectAll method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#selectAll) * [selectFrom method](https://kysely-org.github.io/kysely-apidoc/classes/Kysely.html#selectFrom) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Distinct on ```ts const persons = await db.selectFrom('person') .innerJoin('pet', 'pet.owner_id', 'person.id') .where('pet.name', '=', 'Doggo') .distinctOn('person.id') .selectAll('person') .execute() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [select method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#select) * [selectAll method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#selectAll) * [selectFrom method](https://kysely-org.github.io/kysely-apidoc/classes/Kysely.html#selectFrom) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Function calls This example shows how to create function calls. These examples also work in any other place (`where` calls, updates, inserts etc.). The only difference is that you leave out the alias (the `as` call) if you use these in any other place than `select`. ```ts import { sql } from 'kysely' const result = await db.selectFrom('person') .innerJoin('pet', 'pet.owner_id', 'person.id') .select(({ fn, val, ref }) => [ 'person.id', // The `fn` module contains the most common // functions. fn.count('pet.id').as('pet_count'), // You can call any function by calling `fn` // directly. The arguments are treated as column // references by default. If you want to pass in // values, use the `val` function. fn('concat', [ val('Ms. '), 'first_name', val(' '), 'last_name' ]).as('full_name_with_title'), // You can call any aggregate function using the // `fn.agg` function. fn.agg('array_agg', ['pet.name']).as('pet_names'), // And once again, you can use the `sql` // template tag. The template tag substitutions // are treated as values by default. If you want // to reference columns, you can use the `ref` // function. sql`concat( ${ref('first_name')}, ' ', ${ref('last_name')} )`.as('full_name') ]) .groupBy('person.id') .having((eb) => eb.fn.count('pet.id'), '>', 10) .execute() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [select method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#select) * [selectAll method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#selectAll) * [selectFrom method](https://kysely-org.github.io/kysely-apidoc/classes/Kysely.html#selectFrom) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Generic find query A generic type-safe helper function for finding a row by a column value: ```ts import { SelectType } from 'kysely' import { Database } from 'type-editor' async function getRowByColumn< T extends keyof Database, C extends keyof Database[T] & string, V extends SelectType, >(t: T, c: C, v: V) { // We need to use the dynamic module since the table name // is not known at compile time. const { table, ref } = db.dynamic return await db .selectFrom(table(t).as('t')) .selectAll() .where(ref(c), '=', v) .orderBy('t.id') .executeTakeFirstOrThrow() } const person = await getRowByColumn('person', 'first_name', 'Arnold') ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [select method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#select) * [selectAll method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#selectAll) * [selectFrom method](https://kysely-org.github.io/kysely-apidoc/classes/Kysely.html#selectFrom) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Multiple columns Select multiple columns: ```ts const persons = await db .selectFrom('person') .select(['person.id', 'first_name']) .execute() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [select method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#select) * [selectAll method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#selectAll) * [selectFrom method](https://kysely-org.github.io/kysely-apidoc/classes/Kysely.html#selectFrom) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Nested array While kysely is not an ORM and it doesn't have the concept of relations, we do provide helpers for fetching nested objects and arrays in a single query. In this example we use the `jsonArrayFrom` helper to fetch person's pets along with the person's id. Please keep in mind that the helpers under the `kysely/helpers` folder, including `jsonArrayFrom`, are not guaranteed to work with third party dialects. In order for them to work, the dialect must automatically parse the `json` data type into JavaScript JSON values like objects and arrays. Some dialects might simply return the data as a JSON string. In these cases you can use the built in `ParseJSONResultsPlugin` to parse the results. ```ts import { jsonArrayFrom } from 'kysely/helpers/postgres' const result = await db .selectFrom('person') .select((eb) => [ 'id', jsonArrayFrom( eb.selectFrom('pet') .select(['pet.id as pet_id', 'pet.name']) .whereRef('pet.owner_id', '=', 'person.id') .orderBy('pet.name') ).as('pets') ]) .execute() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [select method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#select) * [selectAll method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#selectAll) * [selectFrom method](https://kysely-org.github.io/kysely-apidoc/classes/Kysely.html#selectFrom) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Nested object While kysely is not an ORM and it doesn't have the concept of relations, we do provide helpers for fetching nested objects and arrays in a single query. In this example we use the `jsonObjectFrom` helper to fetch person's favorite pet along with the person's id. Please keep in mind that the helpers under the `kysely/helpers` folder, including `jsonObjectFrom`, are not guaranteed to work with third-party dialects. In order for them to work, the dialect must automatically parse the `json` data type into JavaScript JSON values like objects and arrays. Some dialects might simply return the data as a JSON string. In these cases you can use the built in `ParseJSONResultsPlugin` to parse the results. ```ts import { jsonObjectFrom } from 'kysely/helpers/postgres' const result = await db .selectFrom('person') .select((eb) => [ 'id', jsonObjectFrom( eb.selectFrom('pet') .select(['pet.id as pet_id', 'pet.name']) .whereRef('pet.owner_id', '=', 'person.id') .where('pet.is_favorite', '=', true) ).as('favorite_pet') ]) .execute() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [select method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#select) * [selectAll method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#selectAll) * [selectFrom method](https://kysely-org.github.io/kysely-apidoc/classes/Kysely.html#selectFrom) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Not null Sometimes you can be sure something's not null, but Kysely isn't able to infer it. For example calling `where('last_name', 'is not', null)` doesn't make `last_name` not null in the result type, but unless you have other where statements you can be sure it's never null. Kysely has a couple of helpers for dealing with these cases: `$notNull()` and `$narrowType`. Both are used in the following example: ```ts import { NotNull } from 'kysely' import { jsonObjectFrom } from 'kysely/helpers/postgres' const persons = db .selectFrom('person') .select((eb) => [ 'last_name', // Let's assume we know the person has at least one // pet. We can use the `.$notNull()` method to make // the expression not null. You could just as well // add `pet` to the `$narrowType` call below. jsonObjectFrom( eb.selectFrom('pet') .selectAll() .limit(1) .whereRef('person.id', '=', 'pet.owner_id') ).$notNull().as('pet') ]) .where('last_name', 'is not', null) // $narrowType can be used to narrow the output type. // The special `NotNull` type can be used to make a // selection not null. You could add `pet: NotNull` // here and omit the `$notNull()` call on it. // Use whichever way you prefer. .$narrowType<{ last_name: NotNull }>() .execute() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [select method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#select) * [selectAll method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#selectAll) * [selectFrom method](https://kysely-org.github.io/kysely-apidoc/classes/Kysely.html#selectFrom) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Controlled transaction A controlled transaction allows you to commit and rollback manually, execute savepoint commands, and queries in general. In this example we start a transaction, use it to insert two rows and then commit the transaction. If an error is thrown, we catch it and rollback the transaction. ```ts const trx = await db.startTransaction().execute() try { const jennifer = await trx.insertInto('person') .values({ first_name: 'Jennifer', last_name: 'Aniston', age: 40, }) .returning('id') .executeTakeFirstOrThrow() const catto = await trx.insertInto('pet') .values({ owner_id: jennifer.id, name: 'Catto', species: 'cat', is_favorite: false, }) .returningAll() .executeTakeFirstOrThrow() await trx.commit().execute() // ... } catch (error) { if (!trx.isRolledBack) { await trx.rollback().execute() } } ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [transaction method](https://kysely-org.github.io/kysely-apidoc/classes/Kysely.html#transaction) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Controlled transaction /w savepoints A controlled transaction allows you to commit and rollback manually, execute savepoint commands, and queries in general. In this example we start a transaction, insert a person, create a savepoint, try inserting a toy and a pet, and if an error is thrown, we rollback to the savepoint. Eventually we release the savepoint, insert an audit record and commit the transaction. If an error is thrown, we catch it and rollback the transaction. ```ts const trx = await db.startTransaction().execute() try { const jennifer = await trx .insertInto('person') .values({ first_name: 'Jennifer', last_name: 'Aniston', age: 40, }) .returning('id') .executeTakeFirstOrThrow() const trxAfterJennifer = await trx.savepoint('after_jennifer').execute() try { const catto = await trxAfterJennifer .insertInto('pet') .values({ owner_id: jennifer.id, name: 'Catto', species: 'cat', }) .returning('id') .executeTakeFirstOrThrow() await trxAfterJennifer .insertInto('toy') .values({ name: 'Bone', price: 1.99, pet_id: catto.id }) .execute() } catch (error) { await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute() } await trxAfterJennifer.releaseSavepoint('after_jennifer').execute() await trx.insertInto('audit').values({ action: 'added Jennifer' }).execute() await trx.commit().execute() } catch (error) { if (!trx.isRolledBack) { await trx.rollback().execute() } } ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [transaction method](https://kysely-org.github.io/kysely-apidoc/classes/Kysely.html#transaction) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Simple transaction This example inserts two rows in a transaction. If an exception is thrown inside the callback passed to the `execute` method, 1. the exception is caught, 2. the transaction is rolled back, and 3. the exception is thrown again. Otherwise the transaction is committed. ```ts const catto = await db.transaction().execute(async (trx) => { const jennifer = await trx.insertInto('person') .values({ first_name: 'Jennifer', last_name: 'Aniston', age: 40, }) .returning('id') .executeTakeFirstOrThrow() return await trx.insertInto('pet') .values({ owner_id: jennifer.id, name: 'Catto', species: 'cat', is_favorite: false, }) .returningAll() .executeTakeFirst() }) ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [transaction method](https://kysely-org.github.io/kysely-apidoc/classes/Kysely.html#transaction) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Complex values As always, you can provide a callback to the `set` method to get access to an expression builder: ```ts const result = await db .updateTable('person') .set((eb) => ({ age: eb('age', '+', 1), first_name: eb.selectFrom('pet').select('name').limit(1), last_name: 'updated', })) .where('id', '=', 1) .executeTakeFirst() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [set method](https://kysely-org.github.io/kysely-apidoc/classes/UpdateQueryBuilder.html#set) * [returning method](https://kysely-org.github.io/kysely-apidoc/classes/UpdateQueryBuilder.html#returning) * [updateTable method](https://kysely-org.github.io/kysely-apidoc/classes/Kysely.html#updateTable) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # MySQL joins MySQL allows you to join tables directly to the "main" table and update rows of all joined tables. This is possible by passing all tables to the `updateTable` method as a list and adding the `ON` conditions as `WHERE` statements. You can then use the `set(column, value)` variant to update columns using table qualified names. The `UpdateQueryBuilder` also has `innerJoin` etc. join methods, but those can only be used as part of a PostgreSQL `update set from join` query. Due to type complexity issues, we unfortunately can't make the same methods work in both cases. ```ts const result = await db .updateTable(['person', 'pet']) .set('person.first_name', 'Updated person') .set('pet.name', 'Updated doggo') .whereRef('person.id', '=', 'pet.owner_id') .where('person.id', '=', 1) .executeTakeFirst() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [set method](https://kysely-org.github.io/kysely-apidoc/classes/UpdateQueryBuilder.html#set) * [returning method](https://kysely-org.github.io/kysely-apidoc/classes/UpdateQueryBuilder.html#returning) * [updateTable method](https://kysely-org.github.io/kysely-apidoc/classes/Kysely.html#updateTable) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Single row Update a row in `person` table: ```ts const result = await db .updateTable('person') .set({ first_name: 'Jennifer', last_name: 'Aniston' }) .where('id', '=', 1) .executeTakeFirst() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [set method](https://kysely-org.github.io/kysely-apidoc/classes/UpdateQueryBuilder.html#set) * [returning method](https://kysely-org.github.io/kysely-apidoc/classes/UpdateQueryBuilder.html#returning) * [updateTable method](https://kysely-org.github.io/kysely-apidoc/classes/Kysely.html#updateTable) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Complex where clause For complex `where` expressions you can pass in a single callback and use the `ExpressionBuilder` to build your expression: ```ts const firstName = 'Jennifer' const maxAge = 60 const persons = await db .selectFrom('person') .selectAll('person') .where(({ eb, or, and, not, exists, selectFrom }) => and([ or([ eb('first_name', '=', firstName), eb('age', '<', maxAge) ]), not(exists( selectFrom('pet') .select('pet.id') .whereRef('pet.owner_id', '=', 'person.id') )) ])) .execute() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [where method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#where) * [whereRef method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#whereRef) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Conditional where calls You can add expressions conditionally like this: ```ts import { Expression, SqlBool } from 'kysely' const firstName: string | undefined = 'Jennifer' const lastName: string | undefined = 'Aniston' const under18 = true const over60 = true let query = db .selectFrom('person') .selectAll() if (firstName) { // The query builder is immutable. Remember to reassign // the result back to the query variable. query = query.where('first_name', '=', firstName) } if (lastName) { query = query.where('last_name', '=', lastName) } if (under18 || over60) { // Conditional OR expressions can be added like this. query = query.where((eb) => { const ors: Expression[] = [] if (under18) { ors.push(eb('age', '<', 18)) } if (over60) { ors.push(eb('age', '>', 60)) } return eb.or(ors) }) } const persons = await query.execute() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [where method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#where) * [whereRef method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#whereRef) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Object filter You can use the `and` function to create a simple equality filter using an object ```ts const persons = await db .selectFrom('person') .selectAll() .where((eb) => eb.and({ first_name: 'Jennifer', last_name: eb.ref('first_name') })) .execute() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [where method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#where) * [whereRef method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#whereRef) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # OR where To combine conditions using `OR`, you can use the expression builder. There are two ways to create `OR` expressions. Both are shown in this example: ```ts const persons = await db .selectFrom('person') .selectAll() // 1. Using the `or` method on the expression builder: .where((eb) => eb.or([ eb('first_name', '=', 'Jennifer'), eb('first_name', '=', 'Sylvester') ])) // 2. Chaining expressions using the `or` method on the // created expressions: .where((eb) => eb('last_name', '=', 'Aniston').or('last_name', '=', 'Stallone') ) .execute() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [where method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#where) * [whereRef method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#whereRef) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Simple where clause `where` method calls are combined with `AND`: ```ts const person = await db .selectFrom('person') .selectAll() .where('first_name', '=', 'Jennifer') .where('age', '>', 40) .executeTakeFirst() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [where method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#where) * [whereRef method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#whereRef) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Where in Find multiple items using a list of identifiers: ```ts const persons = await db .selectFrom('person') .selectAll() .where('id', 'in', [1, 2, 3]) .execute() ``` More examples The API documentation is packed with examples. The API docs are hosted [here](https://kysely-org.github.io/kysely-apidoc/), but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away! For example, check out these sections: * [where method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#where) * [whereRef method](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#whereRef) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Execution flow The following page gives a **simplified** overview of Kysely's execution flow, from query building to querying the database. It is a nice introduction for anyone looking to understand how Kysely works under the hood. Knowing what your dependencies do and don't do is always a good idea! This breakdown explains the journey from a type-safe method call in your application to receiving results from the database, as depicted in the diagram. 1. ### Immutable query building[​](#immutable-query-building "Direct link to Immutable query building") The process starts in your `App`. You interact with the `QueryBuilder` by calling its methods (`selectFrom`, `where`, etc.). Each call returns a *new* `QueryBuilder` instance containing an updated, immutable `QueryAST` (Abstract Syntax Tree), which is the internal representation of your SQL query. 2. ### Initiating execution[​](#initiating-execution "Direct link to Initiating execution") When you chain the final `.execute()` call, the `QueryBuilder` begins a multi-step execution process, commanding the `QueryExecutor` to perform distinct tasks. 3. ### Query Transformation[​](#query-transformation "Direct link to Query Transformation") First, the `QueryBuilder` instructs the `QueryExecutor` to process the `QueryAST`. The `QueryExecutor` iterates through all registered plugins, calling `transformQuery` on each. This allows plugins to modify the query structure before compilation. The final, transformed `QueryAST` is returned to the `QueryBuilder`. 4. ### Query Compilation[​](#query-compilation "Direct link to Query Compilation") Next, the `QueryBuilder` tells the `QueryExecutor` to compile the transformed AST. The `QueryExecutor` delegates this to the `Dialect`-specific `QueryCompiler`. The compiler traverses the AST and produces a `CompiledQuery` object (containing the final SQL string and parameters). This `CompiledQuery` is then returned to the `QueryBuilder`. 5. ### Execution & Connection Handling[​](#execution--connection-handling "Direct link to Execution & Connection Handling") The `QueryBuilder` now asks the `QueryExecutor` to execute the `CompiledQuery`. * The `QueryExecutor` requests a connection from Kysely's `Driver`. * The `Driver`'s job is to abstract away vendor-specific details. It communicates with the actual third-party `DatabaseDriver` — for example, the `pg` or `mysql2` npm package — to get a connection from its pool. * A `DatabaseConnection` object, which wraps the native connection, is returned to the `QueryExecutor`. 6. ### Database Query[​](#database-query "Direct link to Database Query") The `QueryExecutor` passes the `CompiledQuery` to the `DatabaseConnection` object, which executes it. The `DatabaseConnection` uses the underlying `DatabaseDriver` to send the SQL and parameters to the database for execution. The `DatabaseDriver` sends the raw results back. The `DatabaseConnection` standardizes these into a `QueryResult` object and returns it to the `QueryExecutor`. Immediately after, the connection is released back to the pool. 7. ### Result Transformation[​](#result-transformation "Direct link to Result Transformation") The `QueryResult` is then passed through the plugin system again. The `QueryExecutor` calls the `transformResult` method on each plugin, allowing for final modifications to the results before they are returned to the `App`. 8. ### Returning to the App[​](#returning-to-the-app "Direct link to Returning to the App") The final, transformed `QueryResult` is passed up from the `QueryExecutor` to the `QueryBuilder`. The `QueryBuilder` then resolves the promise from the initial `.execute()` call, delivering the final, typed results to your `App`. --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Generating types To work with Kysely, you're required to provide a database schema type definition to the Kysely constructor. In many cases, defining your database schema definitions manually is good enough. However, when building production applications, it's best to stay aligned with the database schema, by automatically generating the database schema type definitions. There are several ways to do this using third-party libraries: * [kysely-codegen](https://github.com/RobinBlomberg/kysely-codegen) - This library generates Kysely database schema type definitions by connecting to and introspecting your database. Its CLI supports PostgreSQL, MySQL, SQLite, and Microsoft SQL Server. PGlite is not a CLI dialect; generating types from an in-process PGlite database requires a programmatic integration. * [kysely-typegen](https://github.com/theoludwig/kysely-typegen) - This library generates Kysely database schema type definitions by introspecting your database through the `Kysely` instance you pass to it. It is used programmatically rather than as a CLI, so it also works with in-process databases such as PGlite. It supports PostgreSQL, PGlite, MySQL, and SQLite, has no runtime dependencies, and can be extended to more dialects. * [prisma-kysely](https://github.com/valtyr/prisma-kysely) - This library generates Kysely database schema type definitions from your existing Prisma schemas. * [kanel-kysely](https://github.com/kristiandupont/kanel/tree/main/packages/kanel-kysely) - This library generates Kysely database schema type definitions by connecting to and introspecting your database. This library extends Kanel which is a mature PostgreSQL-only type generator. * [kysely-schema-generator](https://github.com/deanc/kysely-schema-generator) - This library generates Kysely database schema type definitions by connecting to and introspecting your database. Current MySQL only. --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Getting started ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") * [TypeScript](https://www.typescriptlang.org/) * Minimum supported version [5.4](https://devblogs.microsoft.com/typescript/announcing-typescript-5.4). * For improved compilation performance, use version [5.9](https://devblogs.microsoft.com/typescript/announcing-typescript-5-9/#cache-instantiations-on-mappers) or later. * You must enable `strict` mode in your `tsconfig.json` file's `compilerOptions`: ```jsonc { // ... "compilerOptions": { // ... "strict": true // ... } // ... } ``` ## Installation[​](#installation "Direct link to Installation") Kysely can be installed using any of the following package managers: * npm * pnpm * Yarn * Bun * Deno [npm](https://npmjs.com) is the default package manager for [Node.js](https://nodejs.org), and to where Kysely is published.
Your project is using npm if it has a `package-lock.json` file in its root folder. **Run the following command in your terminal:** ```bash npm install kysely ``` [pnpm](https://pnpm.io) is a fast, disk space efficient package manager for [Node.js](https://nodejs.org).
Your project is using pnpm if it has a `pnpm-lock.yaml` file in its root folder. **Run the following command in your terminal:** ```bash pnpm install kysely ``` [Yarn](https://yarnpkg.com) is a fast, reliable and secure dependency manager for [Node.js](https://nodejs.org).
Your project is using Yarn if it has a `yarn.lock` file in its root folder. **Run the following command in your terminal:** ```bash yarn add kysely ``` [Bun](https://bun.sh) is a new [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript) runtime built for speed, with a native bundler, transpiler, test runner, and npm-compatible package manager baked-in. **Run the following command in your terminal:** ```bash bun install kysely ``` [Deno](https://deno.com/runtime) is a secure runtime for [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript) and [TypeScript](https://www.typescriptlang.org). **Run the following command in your terminal:** ```bash deno add jsr:@kysely/kysely ``` ## Types[​](#types "Direct link to Types") For Kysely's type-safety and autocompletion to work, it needs to know your database structure. This requires a TypeScript `Database` interface, that contains table names as keys and table schema interfaces as values. **Let's define our first database interface:** ```ts import { ColumnType, Generated, Insertable, JSONColumnType, Selectable, Updateable, } from 'kysely' export interface Database { person: PersonTable pet: PetTable } // This interface describes the `person` table to Kysely. Table // interfaces should only be used in the `Database` type above // and never as a result type of a query!. See the `Person`, // `NewPerson` and `PersonUpdate` types below. export interface PersonTable { // Columns that are generated by the database should be marked // using the `Generated` type. This way they are automatically // made optional in inserts and updates. id: Generated first_name: string gender: 'man' | 'woman' | 'other' // If the column is nullable in the database, make its type nullable. // Don't use optional properties. Optionality is always determined // automatically by Kysely. last_name: string | null // You can specify a different type for each operation (select, insert and // update) using the `ColumnType` // wrapper. Here we define a column `created_at` that is selected as // a `Date`, can optionally be provided as a `string` in inserts and // can never be updated: created_at: ColumnType // You can specify JSON columns using the `JSONColumnType` wrapper. // It is a shorthand for `ColumnType`, where T // is the type of the JSON object/array retrieved from the database, // and the insert and update types are always `string` since you're // always stringifying insert/update values. metadata: JSONColumnType<{ login_at: string ip: string | null agent: string | null plan: 'free' | 'premium' }> } // You should not use the table schema interfaces directly. Instead, you should // use the `Selectable`, `Insertable` and `Updateable` wrappers. These wrappers // make sure that the correct types are used in each operation. // // Most of the time you should trust the type inference and not use explicit // types at all. These types can be useful when typing function arguments. export type Person = Selectable export type NewPerson = Insertable export type PersonUpdate = Updateable export interface PetTable { id: Generated name: string owner_id: number species: 'dog' | 'cat' } export type Pet = Selectable export type NewPet = Insertable export type PetUpdate = Updateable ``` Codegen For production apps, it is recommended to automatically generate your `Database` interface by introspecting your production database or Prisma schemas. Generated types might differ in naming convention, internal order, etc. Find out more at ["Generating types"](https://kysely.dev/docs/generating-types). Runtime types Kysely only deals with types in the TypeScript level. The runtime JavaScript types are decided by the underlying third-party driver such as `pg` or `mysql2` and it's up to you to select the correct TypeScript types in the database interface. Kysely never touches the runtime output types in any way. Find out more at ["Data types"](https://kysely.dev/docs/recipes/data-types). ## Dialects[​](#dialects "Direct link to Dialects") For Kysely's query compilation and execution to work, it needs to understand your database's SQL specification and how to communicate with it. This requires a `Dialect` implementation.

There are 5 built-in dialects for PostgreSQL, MySQL, Microsoft SQL Server (MSSQL), SQLite, and PGlite. Additionally, the community has implemented several dialects to choose from. Find out more at ["Dialects"](https://kysely.dev/docs/dialects.md). ### Driver installation A `Dialect` implementation usually requires a database driver library as a peer dependency. Let's install it using the same package manager command from before: * PostgreSQL * MySQL * Microsoft SQL Server (MSSQL) * SQLite * PGlite Kysely's built-in PostgreSQL dialect uses the "pg" driver library under the hood. Please refer to its [official documentation](https://node-postgres.com/) for configuration options. **Run the following command in your terminal:** ```bash npm install pg ``` Kysely's built-in MySQL dialect uses the "mysql2" driver library under the hood. Please refer to its [official documentation](https://github.com/sidorares/node-mysql2/tree/master/documentation) for configuration options. **Run the following command in your terminal:** ```bash npm install mysql2 ``` Kysely's built-in Microsoft SQL Server (MSSQL) dialect uses the "tedious" driver library under the hood. Please refer to its [official documentation](https://tediousjs.github.io/tedious/index.html) for configuration options. Additionally, Kysely's Microsoft SQL Server (MSSQL) dialect uses the "tarn" resource pool package for connection pooling. Please refer to its [official documentation](https://github.com/vincit/tarn.js) for configuration options. **Run the following command in your terminal:** ```bash npm install tedious tarn ``` Kysely's built-in SQLite dialect uses the "better-sqlite3" driver library under the hood. Please refer to its [official documentation](https://github.com/WiseLibs/better-sqlite3/blob/master/docs/api.md) for configuration options. **Run the following command in your terminal:** ```bash npm install better-sqlite3 ``` Kysely's built-in PGlite dialect uses the "@electric-sql/pglite" driver library under the hood. Please refer to its [official documentation](https://pglite.dev/docs) for configuration options. **Run the following command in your terminal:** ```bash npm install @electric-sql/pglite ``` [I use a different package manager (not npm)](#installation) Driverless Kysely can also work in compile-only mode that doesn't require a database driver. Find out more at ["Splitting query building and execution"](https://kysely.dev/docs/recipes/splitting-query-building-and-execution.md). ## Instantiation[​](#instantiation "Direct link to Instantiation") **Let's create a Kysely instance**** using the built-in **`PostgresDialect`** dialect****:** ```ts import { Database } from './types.ts' // this is the Database interface we defined earlier import { Pool } from 'pg' import { Kysely, PostgresDialect } from 'kysely' const dialect = new PostgresDialect({ pool: new Pool({ database: 'test', host: 'localhost', user: 'admin', port: 5434, max: 10, }) }) // Database interface is passed to Kysely's constructor, and from now on, Kysely // knows your database structure. // Dialect is passed to Kysely's constructor, and from now on, Kysely knows how // to communicate with your database. export const db = new Kysely({ dialect, }) ``` [I use a different package manager (not npm)](#installation) [I use a different dialect (not PostgreSQL)](#dialects) Singleton In most cases, you should only create a single Kysely instance per database. Most dialects use a connection pool internally, or no connections at all, so there's no need to create a new instance for each request. keeping secrets Use a secrets manager, environment variables (DO NOT commit \`.env\` files to your repository), or a similar solution, to avoid hardcoding database credentials in your code. Closing connections When Kysely is responsible for closing its connections, pool, or database instance, call `await db.destroy()` when you are done using it to release those resources. If you share the pool or database instance with other consumers or manage its lifecycle elsewhere, skip `db.destroy()`. Let the application close it once all consumers, including Kysely, have finished. No separate cleanup of the Kysely instance is needed. Kysely initializes its driver lazily. Calling `db.destroy()` before initialization has started does nothing, even if you have used the supplied pool or database instance independently. ## Querying[​](#querying "Direct link to Querying") **Let's implement the person repository:** ```ts import { db } from './database' import { PersonUpdate, Person, NewPerson } from './types' export async function findPersonById(id: number) { return await db.selectFrom('person') .where('id', '=', id) .selectAll() .executeTakeFirst() } export async function findPeople(criteria: Partial) { let query = db.selectFrom('person') if (criteria.id) { query = query.where('id', '=', criteria.id) // Kysely is immutable, you must re-assign! } if (criteria.first_name) { query = query.where('first_name', '=', criteria.first_name) } if (criteria.last_name !== undefined) { query = query.where( 'last_name', criteria.last_name === null ? 'is' : '=', criteria.last_name ) } if (criteria.gender) { query = query.where('gender', '=', criteria.gender) } if (criteria.created_at) { query = query.where('created_at', '=', criteria.created_at) } return await query.selectAll().execute() } export async function updatePerson(id: number, updateWith: PersonUpdate) { await db.updateTable('person').set(updateWith).where('id', '=', id).execute() } export async function createPerson(person: NewPerson) { return await db.insertInto('person') .values(person) .returningAll() .executeTakeFirstOrThrow() } export async function deletePerson(id: number) { return await db.deleteFrom('person').where('id', '=', id) .returningAll() .executeTakeFirst() } ``` [I use a different dialect (not PostgreSQL)](#dialects) But wait, there's more! This is a simplified example with basic CRUD operations. Kysely supports many more SQL features including: joins, subqueries, complex boolean logic, set operations, CTEs, functions (aggregate and window functions included), raw SQL, transactions, DDL queries, etc.
Find out more at [Examples](https://kysely.dev/docs/category/examples.md). ## Summary[​](#summary "Direct link to Summary") We've seen how to install and instantiate Kysely, its dialects and underlying drivers. We've also seen how to use Kysely to query a database.

**Let's put it all to the test:** ```ts import { sql } from 'kysely' import { db } from './database' import * as PersonRepository from './PersonRepository' describe('PersonRepository', () => { beforeAll(async () => { await db.schema.createTable('person') .addColumn('id', 'serial', (cb) => cb.primaryKey()) .addColumn('first_name', 'varchar', (cb) => cb.notNull()) .addColumn('last_name', 'varchar') .addColumn('gender', 'varchar(50)', (cb) => cb.notNull()) .addColumn('created_at', 'timestamp', (cb) => cb.notNull().defaultTo(sql`now()`) ) .addColumn('metadata', 'jsonb', (cb) => cb.notNull()) .execute() }) afterEach(async () => { await sql`truncate table ${sql.table('person')}`.execute(db) }) afterAll(async () => { await db.schema.dropTable('person').execute() }) it('should find a person with a given id', async () => { await PersonRepository.findPersonById(123) }) it('should find all people named Arnold', async () => { await PersonRepository.findPeople({ first_name: 'Arnold' }) }) it('should update gender of a person with a given id', async () => { await PersonRepository.updatePerson(123, { gender: 'woman' }) }) it('should create a person', async () => { await PersonRepository.createPerson({ first_name: 'Jennifer', last_name: 'Aniston', gender: 'woman', metadata: JSON.stringify({ login_at: new Date().toISOString(), ip: null, agent: null, plan: 'free', }), }) }) it('should delete a person with a given id', async () => { await PersonRepository.deletePerson(123) }) }) ``` [I use a different dialect (not PostgreSQL)](#dialects) Migrations As you can see, Kysely supports DDL queries. It also supports classic "up/down" migrations. Find out more at [Migrations](https://kysely.dev/docs/migrations.md). --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # LLMs Kysely provides LLM-friendly documentation to help AI tools like **Cursor**, **Windsurf**, **GitHub Copilot**, **ChatGPT**, **Claude**, and **Claude Code** understand and work with it. ## Documentation for the installed version[​](#documentation-for-the-installed-version "Direct link to Documentation for the installed version") Kysely's API documentation and examples ship inside the package's TypeScript declarations. An agent with access to your dependencies or language server can read the documentation attached to the method it is calling, including query examples, SQL output, related methods, and deprecations. Those docs travel with the installed release. Reading them avoids a common source of agent mistakes: combining an older dependency with examples from a newer website or a model's memory. Interface documentation is also copied onto implementing methods, so following a method definition exposes its documentation. The inline TypeScript examples are type-checked in CI against the API being released, rather than maintained as a separate collection of unchecked snippets. The published package keeps those examples alongside that version's types. For agent experience (AX), this gives the agent a direct loop: 1. Resolve the installed `kysely` package and read the relevant method's documentation and examples. 2. Build or extend the query using the project's database types. 3. Run the project's TypeScript check and use errors about references, aliases, values, or result fields to correct the query. For example, an agent adding an optional relation can inspect the local `$if`, join, and selection documentation, then let TypeScript check how the new branch affects the result. It can obtain API guidance for the installed version without a browser, documentation server, or extra agent integration. ## Website documentation[​](#website-documentation "Direct link to Website documentation") Use the website's recipes and documentation index for broader discovery, and the installed package for version-specific API details. The website's playground examples are generated from the same annotated JSDoc. API documentation and website examples share their source, rather than relying on separately maintained copies. All TypeScript code blocks on the website are type-checked when the site builds, against the Kysely source they document. A snippet that stops compiling fails the build, and hovering an identifier shows its inferred type and documentation. `llms.txt` documentation is automatically generated and kept up-to-date with each push on GitHub and is based on the [llms.txt standard](https://llmstxt.org/). We audit the website's agent experience with [AFDocs](https://afdocs.dev), the tool behind Mintlify's Agent Score. ## Documentation Structure[​](#documentation-structure "Direct link to Documentation Structure") The [llms.txt](https://kysely.dev/llms.txt) file acts as a summary and index to all the docs pages. The [llms-full.txt](https://kysely.dev/llms-full.txt) file includes all of the Kysely docs in a single file. ## Usage with AI Tools[​](#usage-with-ai-tools "Direct link to Usage with AI Tools") ### Cursor[​](#cursor "Direct link to Cursor") In Cursor, you can reference the documentation using the `@Docs` feature: 1. Type `@Docs` in your prompt 2. Reference the Kysely documentation URL: `https://kysely.dev/llms-full.txt` 3. Ask questions about Kysely queries, types, or database operations ### Windsurf[​](#windsurf "Direct link to Windsurf") For Windsurf users: 1. Reference the documentation using `@https://kysely.dev/llms-full.txt` 2. Or add it to your `.windsurfrules` file for persistent access ### ChatGPT & Claude[​](#chatgpt--claude "Direct link to ChatGPT & Claude") When using ChatGPT or Claude: 1. Mention that you're using Kysely 2. Reference the documentation URL: `https://kysely.dev/llms-full.txt` 3. The AI will fetch and use the documentation to provide accurate answers ### GitHub Copilot[​](#github-copilot "Direct link to GitHub Copilot") While Copilot doesn't directly support external documentation, you can: 1. Include relevant documentation snippets in your comments 2. Reference query builder methods and types accurately for better suggestions ### Claude Code[​](#claude-code "Direct link to Claude Code") For Claude Code users: 1. Reference the documentation by mentioning the URL: `https://kysely.dev/llms-full.txt` 2. Ask Claude Code to analyze the documentation for specific Kysely patterns 3. Use commands like: `claude -p "Using the Kysely docs at https://kysely.dev/llms-full.txt, help me build a type-safe query"` ## Example Prompts[​](#example-prompts "Direct link to Example Prompts") Here are some example prompts you can use with AI tools: * "Using Kysely, how do I build a type-safe SELECT query with JOINs?" * "Show me how to define a database schema interface for Kysely" * "How can I use transactions with Kysely?" * "Create a complex query with subqueries and aggregations" * "How to handle database migrations with Kysely?" --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Supabase Supabase is an open-source Firebase alternative that provides a suite of tools for building applications. At the core, it is a managed PostgreSQL database vendor. They provide a CLI library called `supabase` that's at the heart of their ecosystem. It manages your database, migrates it and can generate TypeScript types from it. They also provide a JavaScript client library called `@supabase/supabase-js` that wraps a PostgREST API, and is pretty limited - doesn't even allow raw SQL. This is where Kysely comes in. We provide a bridge library called `kysely-supabase` that allows you to translate `supabase`'s generated TypeScript types into types compatible with Kysely. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") 1. `supabase` CLI installed and a Supabase project set up. 2. `kysely` installed. 3. A PostgreSQL driver installed - e.g. `pg` or `postgres`. The latter requires `kysely-postgres-js` to be installed as well. ## Installation[​](#installation "Direct link to Installation") ```bash npm i -D kysely-supabase ``` ## Usage[​](#usage "Direct link to Usage") ### Generate TypeScript types using `supabase` CLI[​](#generate-typescript-types-using-supabase-cli "Direct link to generate-typescript-types-using-supabase-cli") ```bash npx supabase gen types typescript --local > path/to/supabase/generated/types/file ``` ### Translate Supabase types to Kysely types[​](#translate-supabase-types-to-kysely-types "Direct link to Translate Supabase types to Kysely types") ```ts import type { Database as SupabaseDatabase } from 'path/to/supabase/generated/types/file' import type { KyselifyDatabase } from 'kysely-supabase' export type Database = KyselifyDatabase ``` ### Pass translated types to Kysely constructor[​](#pass-translated-types-to-kysely-constructor "Direct link to Pass translated types to Kysely constructor") ```ts import { Kysely, PostgresDialect } from 'kysely' import { Pool } from 'pg' import type { Database } from './types' export const db = new Kysely({ dialect: new PostgresDialect({ pool: new Pool({ connectionString: process.env.DATABASE_URL, }), }), }) ``` --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Introduction Kysely (pronounced “Key-Seh-Lee”) is a type-safe and autocompletion-friendly TypeScript SQL query builder. Inspired by Knex. Mainly developed for [node.js](https://nodejs.org/en/) but also runs on all other JavaScript environments like [deno](https://deno.land/) and [bun](https://bun.sh/). Kysely makes sure you only refer to tables and columns that are visible to the part of the query you're writing. The result type only has the selected columns with correct types and aliases. As an added bonus you get autocompletion for all that stuff. Through the pure magic of modern TypeScript, Kysely is even able to parse the alias given to `pet.name` and add the `pet_name` column to the result row type. Kysely is able to infer column names, aliases and types from selected subqueries, joined subqueries, `with` statements and pretty much anything you can think of. Of course there are cases where things cannot be typed at compile time, and Kysely offers escape hatches for these situations. See the [sql template tag](https://kysely-org.github.io/kysely-apidoc/interfaces/Sql.html) and the [DynamicModule](https://kysely-org.github.io/kysely-apidoc/classes/DynamicModule.html#ref) for more info. All API documentation is written in the typing files and you can simply hover over the module, class or method you're using to see it in your IDE. The same documentation is also available in the [Kysely API reference](https://kysely-org.github.io/kysely-apidoc/). ## Choosing a query builder?[​](#choosing-a-query-builder "Direct link to Choosing a query builder?") Explore the [comparisons](https://kysely.dev/docs/category/comparisons.md) for SQL query builders, ORMs, and SQL workflows in TypeScript. ## Looking for help?[​](#looking-for-help "Direct link to Looking for help?") If you start using Kysely and can't find something you'd want to use, please [open an issue](https://github.com/kysely-org/kysely/issues) or [join our Discord server](https://discord.gg/xyBJ3GwvAm). --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Migrations ## Migration files[​](#migration-files "Direct link to Migration files") Migration files should look like this: ```ts import { Kysely } from 'kysely' export async function up(db: Kysely): Promise { // Migration code } export async function down(db: Kysely): Promise { // Migration code } ``` The `up` function is called when you update your database schema to the next version and `down` when you go back to previous version. The only argument for the functions is an instance of `Kysely`. It's important to use `Kysely` and not `Kysely`. Migrations should never depend on the current code of your app because they need to work even when the app changes. Migrations need to be "frozen in time". Migrations can use the `Kysely.schema` module to modify the schema. Migrations can also run normal queries to read/modify data. ## Execution order[​](#execution-order "Direct link to Execution order") Migrations will be run in the alpha-numeric order of your migration names. An excellent way to name your migrations is to prefix them with an ISO 8601 date string. By default, Kysely will also ensure this order matches the execution order of any previously executed migrations in your database. If the orders do not match (for example, a new migration was added alphabetically before a previously executed one), an error will be returned. This adds safety by always executing your migrations in the correct, alphanumeric order. There is also an `allowUnorderedMigrations` option. This option will allow new migrations to be run even if they are added alphabetically before ones that have already executed. Allowing unordered migrations works well in large teams where multiple team members may add migrations at the same time in parallel commits without knowing about the other migrations. Pending (unexecuted) migrations will be run in alpha-numeric order when migrating up. When migrating down, migrations will be undone in the opposite order in which they were executed (reverse sorted by execution timestamp). To allow unordered migrations, pass the `allowUnorderedMigrations` option to Migrator: ```ts import { FileMigrationProvider, Migrator } from 'kysely/migration' const migrator = new Migrator({ db, provider: new FileMigrationProvider({ fs, path, migrationFolder }), allowUnorderedMigrations: true }) ``` ### Execution timestamps[​](#execution-timestamps "Direct link to Execution timestamps") Kysely's migrator keeps track of executed migrations in a `kysely_migration` table (configurable with the `migrationTableName` and `migrationTableSchema` options). Each row holds the migration's `name` and a `timestamp` of when it was executed, stored as an ISO 8601 string. The migrator uses it to order executed migrations, e.g. to undo them in reverse execution order when migrating down. It is also exposed as `executedAt` by `Migrator.getMigrations`. In most cases, the timestamp is the time on the machine running the migrator when the migration was applied (as reported by `Date.now()`), not the database server's time. Since it determines the execution order, it never goes backwards. If the machine clock is behind the latest recorded timestamp, for example after a virtual machine time sync, an NTP step or a leap second, because of clock drift between machines running migrations, or because the clock was ahead when a previous migration was applied, the migration is recorded 1 millisecond after the latest recorded timestamp instead. If the clock is behind by a second or more, a warning is logged once. Don't rely on it as an exact audit log of when migrations ran. If a recorded timestamp can't be parsed, the migrator fails with a "corrupted migrations" error. ## Single file vs multiple file migrations[​](#single-file-vs-multiple-file-migrations "Direct link to Single file vs multiple file migrations") You don't need to store your migrations as separate files if you don't want to. You can easily implement your own MigrationProvider and give it to the Migrator class when you instantiate one. ## PostgreSQL migration example[​](#postgresql-migration-example "Direct link to PostgreSQL migration example") ```ts import { Kysely, sql } from 'kysely' export async function up(db: Kysely): Promise { await db.schema .createTable('person') .addColumn('id', 'serial', (col) => col.primaryKey()) .addColumn('first_name', 'varchar', (col) => col.notNull()) .addColumn('last_name', 'varchar') .addColumn('gender', 'varchar(50)', (col) => col.notNull()) .addColumn('created_at', 'timestamp', (col) => col.defaultTo(sql`now()`).notNull(), ) .execute() await db.schema .createTable('pet') .addColumn('id', 'serial', (col) => col.primaryKey()) .addColumn('name', 'varchar', (col) => col.notNull().unique()) .addColumn('owner_id', 'integer', (col) => col.references('person.id').onDelete('cascade').notNull(), ) .addColumn('species', 'varchar', (col) => col.notNull()) .execute() await db.schema .createIndex('pet_owner_id_index') .on('pet') .column('owner_id') .execute() } export async function down(db: Kysely): Promise { await db.schema.dropTable('pet').execute() await db.schema.dropTable('person').execute() } ``` ## SQLite migration example[​](#sqlite-migration-example "Direct link to SQLite migration example") ```ts import { Kysely, sql } from 'kysely' export async function up(db: Kysely): Promise { await db.schema .createTable('person') .addColumn('id', 'integer', (col) => col.primaryKey()) .addColumn('first_name', 'text', (col) => col.notNull()) .addColumn('last_name', 'text') .addColumn('gender', 'text', (col) => col.notNull()) .addColumn('created_at', 'text', (col) => col.defaultTo(sql`CURRENT_TIMESTAMP`).notNull(), ) .execute() await db.schema .createTable('pet') .addColumn('id', 'integer', (col) => col.primaryKey()) .addColumn('name', 'text', (col) => col.notNull().unique()) .addColumn('owner_id', 'integer', (col) => col.references('person.id').onDelete('cascade').notNull(), ) .addColumn('species', 'text', (col) => col.notNull()) .execute() await db.schema .createIndex('pet_owner_id_index') .on('pet') .column('owner_id') .execute() } export async function down(db: Kysely): Promise { await db.schema.dropTable('pet').execute() await db.schema.dropTable('person').execute() } ``` ## CLI (optional)[​](#cli-optional "Direct link to CLI (optional)") Kysely offers a CLI you can use for migrations (and more). It can help you create and run migrations. It is not part of the core, and your mileage may vary. For more information, visit . ## Running migrations[​](#running-migrations "Direct link to Running migrations") You can then use: ```ts import { Migrator } from 'kysely/migration' const migrator = new Migrator(migratorConfig) await migrator.migrateToLatest() ``` to run all migrations that have not yet been run. See the Migrator class's documentation for more info. You will probably want to add a simple migration script to your projects like this: ```ts import * as path from 'path' import { Pool } from 'pg' import { promises as fs } from 'fs' import { Kysely, PostgresDialect } from 'kysely' import { FileMigrationProvider, Migrator } from 'kysely/migration' import { Database } from './types' async function migrateToLatest() { const db = new Kysely({ dialect: new PostgresDialect({ pool: new Pool({ host: 'localhost', database: 'kysely_test', }), }), }) const migrator = new Migrator({ db, provider: new FileMigrationProvider({ fs, path, // This needs to be an absolute path. migrationFolder: path.join(__dirname, 'some/path/to/migrations'), }), }) const { error, results } = await migrator.migrateToLatest() results?.forEach((it) => { if (it.status === 'Success') { console.log(`migration "${it.migrationName}" was executed successfully`) } else if (it.status === 'Error') { console.error(`failed to execute migration "${it.migrationName}"`) } }) if (error) { console.error('failed to migrate') console.error(error) process.exit(1) } await db.destroy() } migrateToLatest() ``` The migration methods use a lock on the database level and parallel calls are executed serially. This means that you can safely call migrateToLatest and other migration methods from multiple server instances simultaneously and the migrations are guaranteed to only be executed once. The locks are also automatically released if the migration process crashes or the connection to the database fails. ## Reference documentation[​](#reference-documentation "Direct link to Reference documentation") [Migrator](https://kysely-org.github.io/kysely-apidoc/classes/migration.Migrator.html) --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Playground [@wirekang](https://github.com/wirekang) has created a [playground for Kysely](https://play.kysely.dev). You can use it to quickly test stuff out and for creating code examples for your issues, PRs and Discord messages. [Kysely Playground](https://play.kysely.dev/?theme=dark\¬heme=1\&open=1\&nomore=1\&nohotkey=1#r%7B%22dialect%22%3A%22postgres%22%2C%22editors%22%3A%7B%22query%22%3A%22const%20person%20%3D%20await%20db%5Cn.selectFrom\('person'\)%5Cn.select\(%5B'id'%2C%20'first_name'%5D\)%5Cn.where\('id'%2C%20'%3D'%2C%201\)%5Cn.executeTakeFirst\(\)%22%2C%22type%22%3A%22import%20type%20%7B%5Cn%20%20ColumnType%2C%5Cn%20%20Generated%2C%5Cn%20%20GeneratedAlways%2C%5Cn%20%20Insertable%2C%5Cn%20%20Kysely%2C%5Cn%20%20Selectable%2C%5Cn%20%20SqlBool%2C%5Cn%20%20Updateable%2C%5Cn%7D%20from%20'kysely'%5Cn%5Cnexport%20interface%20Database%20%7B%5Cn%20%20audit%3A%20AuditTable%5Cn%20%20person%3A%20PersonTable%5Cn%20%20person_backup%3A%20PersonTable%5Cn%20%20pet%3A%20PetTable%5Cn%20%20toy%3A%20ToyTable%5Cn%20%20wine%3A%20WineTable%5Cn%20%20wine_stock_change%3A%20WineStockChangeTable%5Cn%7D%5Cn%5Cninterface%20AuditTable%20%7B%5Cn%20%20id%3A%20Generated%3Cnumber%3E%5Cn%20%20action%3A%20string%5Cn%7D%5Cn%5Cninterface%20PersonTable%20%7B%5Cn%20%20id%3A%20Generated%3Cnumber%3E%5Cn%20%20address%3A%20%7B%20city%3A%20string%20%7D%20%7C%20null%5Cn%20%20age%3A%20number%20%7C%20null%5Cn%20%20birthdate%3A%20ColumnType%3CDate%20%7C%20null%2C%20string%20%7C%20null%20%7C%20undefined%2C%20string%20%7C%20null%3E%5Cn%20%20created_at%3A%20GeneratedAlways%3CDate%3E%5Cn%20%20deleted_at%3A%20ColumnType%3CDate%20%7C%20null%2C%20string%20%7C%20null%20%7C%20undefined%2C%20string%20%7C%20null%3E%5Cn%20%20experience%3A%20%7B%20role%3A%20string%20%7D%5B%5D%20%7C%20null%5Cn%20%20first_name%3A%20string%5Cn%20%20gender%3A%20'male'%20%7C%20'female'%20%7C%20'other'%20%7C%20null%5Cn%20%20has_pets%3A%20Generated%3C'Y'%20%7C%20'N'%3E%5Cn%20%20last_name%3A%20string%20%7C%20null%5Cn%20%20middle_name%3A%20string%20%7C%20null%5Cn%20%20nicknames%3A%20string%5B%5D%20%7C%20null%5Cn%20%20nullable_column%3A%20string%20%7C%20null%5Cn%20%20profile%3A%20%7B%5Cn%20%20%20%20addresses%3A%20%7B%20city%3A%20string%20%7D%5B%5D%5Cn%20%20%20%20website%3A%20%7B%20url%3A%20string%20%7D%5Cn%20%20%7D%20%7C%20null%5Cn%20%20updated_at%3A%20ColumnType%3CDate%20%7C%20null%2C%20string%20%7C%20null%20%7C%20undefined%2C%20string%20%7C%20null%3E%5Cn%20%20marital_status%3A%20'single'%20%7C%20'married'%20%7C%20'divorced'%20%7C%20'widowed'%20%7C%20null%5Cn%7D%5Cn%5Cninterface%20PetTable%20%7B%5Cn%20%20id%3A%20Generated%3Cnumber%3E%5Cn%20%20created_at%3A%20GeneratedAlways%3CDate%3E%5Cn%20%20is_favorite%3A%20Generated%3CSqlBool%3E%5Cn%20%20name%3A%20string%5Cn%20%20owner_id%3A%20number%5Cn%20%20species%3A%20Species%5Cn%7D%5Cn%5Cninterface%20ToyTable%20%7B%5Cn%20%20id%3A%20Generated%3Cnumber%3E%5Cn%20%20name%3A%20string%5Cn%20%20pet_id%3A%20number%5Cn%20%20price%3A%20number%5Cn%7D%5Cn%5Cninterface%20WineTable%20%7B%5Cn%20%20id%3A%20Generated%3Cnumber%3E%5Cn%20%20name%3A%20string%5Cn%20%20stock%3A%20number%5Cn%7D%5Cn%5Cninterface%20WineStockChangeTable%20%7B%5Cn%20%20id%3A%20Generated%3Cnumber%3E%5Cn%20%20stock_delta%3A%20number%5Cn%20%20wine_name%3A%20string%5Cn%7D%5Cn%5Cnexport%20type%20Person%20%3D%20Selectable%3CPersonTable%3E%5Cnexport%20type%20NewPerson%20%3D%20Insertable%3CPersonTable%3E%5Cnexport%20type%20PersonUpdate%20%3D%20Updateable%3CPersonTable%3E%5Cnexport%20type%20Pet%20%3D%20Selectable%3CPetTable%3E%5Cnexport%20type%20NewPet%20%3D%20Insertable%3CPetTable%3E%5Cnexport%20type%20PetUpdate%20%3D%20Updateable%3CPetTable%3E%5Cnexport%20type%20Species%20%3D%20'dog'%20%7C%20'cat'%20%7C%20'hamster'%5Cn%5Cndeclare%20global%20%7B%5Cn%20%20%2F%2F%20%40ts-ignore%5Cn%20%20export%20class%20Buffer%20%7B%5Cn%20%20%20%20static%20isBuffer\(obj%3A%20unknown\)%3A%20obj%20is%20%7B%20length%3A%20number%20%7D%5Cn%20%20%20%20static%20compare\(a%3A%20Buffer%2C%20b%3A%20Buffer\)%3A%20number%5Cn%20%20%7D%5Cn%20%20export%20const%20db%3A%20Kysely%3CDatabase%3E%5Cn%20%20export%20function%20functionThatExpectsPersonWithNonNullValue\(%5Cn%20%20%20%20person%3A%20Person%20%26%20%7B%20nullable_column%3A%20string%20%7D%2C%5Cn%20%20\)%3A%20void%5Cn%7D%5Cn%22%7D%2C%22hideType%22%3Atrue%7D) ## Codesandbox[​](#codesandbox "Direct link to Codesandbox") We also have a minimal [code sandbox example](https://codesandbox.io/s/kysely-demo-9l099t?file=/src/index.tsx:0-36). --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Plugin system Plugins are classes that implement [KyselyPlugin](https://kysely-org.github.io/kysely-apidoc/interfaces/KyselyPlugin.html). Plugins are then added to the `Kysely` instance as follows: ```ts import { CamelCasePlugin, Kysely, PostgresDialect } from 'kysely' import { Pool } from 'pg' const db = new Kysely({ dialect: new PostgresDialect({ pool: new Pool({ database: 'kysely_test', host: 'localhost', }), }), plugins: [new CamelCasePlugin()], }) ``` ## Built-in plugins[​](#built-in-plugins "Direct link to Built-in plugins") ### Camel case plugin[​](#camel-case-plugin "Direct link to Camel case plugin") A plugin that converts snake\_case identifiers in the database into camelCase in the JavaScript side. [Learn more](https://kysely-org.github.io/kysely-apidoc/classes/CamelCasePlugin.html). ### Deduplicate joins plugin[​](#deduplicate-joins-plugin "Direct link to Deduplicate joins plugin") A plugin that removes duplicate joins from queries. You can read more about it in the [examples](https://kysely.dev/docs/recipes/deduplicate-joins.md) section or check the [API docs](https://kysely-org.github.io/kysely-apidoc/classes/DeduplicateJoinsPlugin.html). ### Handle `in ()` and `not in ()` plugin[​](#handle-in--and-not-in--plugin "Direct link to handle-in--and-not-in--plugin") A plugin that allows handling `in ()` and `not in ()` with a chosen strategy. [Learn more](https://kysely-org.github.io/kysely-apidoc/classes/HandleEmptyInListsPlugin.html). ### Safe null comparison plugin[​](#safe-null-comparison-plugin "Direct link to Safe null comparison plugin") A plugin that converts `=`, `!=` and `<>` to the equivalent `is` and `is not` operators when the right-hand side value is `null`. [Learn more](https://kysely-org.github.io/kysely-apidoc/classes/SafeNullComparisonPlugin.html). --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Conditional selects Sometimes you may want to select some fields based on a runtime condition. Something like this: ```ts async function getPerson(id: number, withLastName: boolean) {} ``` If `withLastName` is true the person object is returned with a `last_name` property, otherwise without it. Your first thought can be to simply do this: ```ts async function getPerson(id: number, withLastName: boolean) { let query = db.selectFrom('person').select('first_name').where('id', '=', id) if (withLastName) { // ❌ The type of `query` doesn't change here query = query.select(['last_name', sql.val('person_with_last_name' as const).as('kind')]) } // ❌ Wrong return type { first_name: string, kind: 'person' } return await query.select(sql.val('person' as const).as('kind')).executeTakeFirstOrThrow() } const person = await getPerson(1, true) // ❌ `last_name` is missing from the result type console.log(person.last_name) // Property 'last_name' does not exist on type '{ first_name: string; kind: "person"; }'. ``` While `getPerson` *would* compile, its result type would be `{ first_name: string, kind: 'person' }` without the `last_name` column and `kind` being "person\_with\_last\_name", which is wrong. What happens is that the type of `query` when created is something, let's say `A`. The type of the query with `last_name` selection is `B` which extends `A` but also contains information about the new selection. When you assign an object of type `B` to `query` inside the `if` statement, the type gets downcast to `A`. info You *can* write code like this to add conditional `where`, `groupBy`, `orderBy` etc. statements that don't change the type of the query builder, but it doesn't work with `select`, `returning`, `innerJoin` etc. that *do* change the type of the query builder. In this simple case you could implement the method like this: ```ts async function getPerson(id: number, withLastName: boolean) { const query = db .selectFrom("person") .select("first_name") .where("id", "=", id); if (withLastName) { // ✅ The return type is { first_name: string, last_name: string, kind: 'person_with_last_name' } return await query .select([ "last_name", sql.val("person_with_last_name" as const).as("kind"), ]) .executeTakeFirstOrThrow(); } // ✅ The return type is { first_name: string, kind: 'person' } return await query .select(sql.val("person" as const).as("kind")) .executeTakeFirstOrThrow(); } ``` This works fine when you have one single condition. As soon as you have two or more conditions the amount of code explodes if you want to keep things type-safe. You need to create a separate branch for every possible combination of selections or otherwise the types won't be correct. This is where the [$if](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#_if) method can help you: ```ts async function getPerson(id: number, withLastName: boolean) { // ✅ The return type is { first_name: string, last_name?: string } return await db .selectFrom("person") .select("first_name") .$if(withLastName, (qb) => qb.select("last_name")) .where("id", "=", id) .executeTakeFirstOrThrow(); } ``` Any selections added inside the `$if` callback will be added as optional fields to the output type since we can't know if the selections were actually made before running the code. A downside of `$if` is that, unlike the imperative example, it cannot result in discriminated union return types - `kind` would be a union of `'person' | 'person_with_last_name'`. --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Data types When talking about data types in Kysely we need to make a distinction between the two kinds of types: 1. Typescript types 2. Runtime JavaScript types ## Typescript types[​](#typescript-types "Direct link to Typescript types") In Kysely, you only define TypeScript types for your tables and columns. Since TypeScript is entirely a compile-time concept, TypeScript types **can't** affect runtime JavaScript types. If you define your column to be a `string` in TypeScript but the database returns a `number`, the runtime type doesn't magically change to `string`. You'll see a `string` in the TypeScript code, but observe a number when you run the program. info It's up to **you** to select correct TypeScript types for your columns based on what the driver returns. ## Runtime JavaScript types[​](#runtime-javascript-types "Direct link to Runtime JavaScript types") The database driver, such as `pg` or `mysql2`, decides the runtime JavaScript types the queries return. Kysely never touches the runtime types the driver returns. In fact, Kysely doesn't touch the data returned by the driver in any way. It simply executes the query and returns whatever the driver returns. An exception to this rule is when you use a plugin like `CamelCasePlugin`, in which case Kysely does change the column names. You need to read the underlying driver's documentation or otherwise figure out what the driver returns and then align the TypeScript types to match them. ### Configuring runtime JavaScript types[​](#configuring-runtime-javascript-types "Direct link to Configuring runtime JavaScript types") Most drivers provide a way to change the returned types. For example `pg` returns `bigint` and `numeric` types as strings by default, but often you want to configure it to return numbers instead. #### Postgres[​](#postgres "Direct link to Postgres") When using the `pg` driver, you can use the [pg-types](https://github.com/brianc/node-pg-types) package to configure the types. For example here's how you'd configure the `bigint` to be returned as a number: ```ts import { Kysely, PostgresDialect } from 'kysely' import * as pg from 'pg' const int8TypeId = 20 // Map int8 to number. pg.types.setTypeParser(int8TypeId, (val) => { return parseInt(val, 10) }) export const db = new Kysely({ dialect: new PostgresDialect({ pool: new pg.Pool(config), }), }) ``` See the documentation [here](https://github.com/brianc/node-pg-types) on how to figure out the correct type id. #### MySQL[​](#mysql "Direct link to MySQL") When using the `mysql2` driver, you can use the [typeCast](https://github.com/mysqljs/mysql?tab=readme-ov-file#custom-type-casting) pool property. For example here's how you'd map `tinyint(1)` to a boolean: ```ts import { Kysely, MysqlDialect } from 'kysely' import { createPool } from 'mysql2' export const db = new Kysely({ dialect: new MysqlDialect({ pool: createPool({ ...config, // Map tinyint(1) to boolean typeCast(field, next) { if (field.type === 'TINY' && field.length === 1) { return field.string() === '1' } else { return next() } }, }), }), }) ``` ## Type generators[​](#type-generators "Direct link to Type generators") There are third-party type generators such as [kysely-codegen](https://github.com/RobinBlomberg/kysely-codegen), [kysely-typegen](https://github.com/theoludwig/kysely-typegen) and [kanel-kysely](https://kristiandupont.github.io/kanel/kanel-kysely.html) that automatically generate TypeScript types based on the database schema. Find out more at ["Generating types"](https://kysely.dev/docs/generating-types). If these tools generate a type that doesn't match the runtime type you observe, please refer to their documentation or open an issue in their github. Kysely has no control over these libraries. --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Deduplicate joins When building dynamic queries, you sometimes end up in situations where the same join could be added twice. Consider this query: ```ts async function getPerson( id: number, withPetName: boolean, withPetSpecies: boolean ) { return await db .selectFrom('person') .selectAll('person') .$if(withPetName, (qb) => qb .innerJoin('pet', 'pet.owner_id', 'person.id') .select('pet.name as pet_name') ) .$if(withPetSpecies, (qb) => qb .innerJoin('pet', 'pet.owner_id', 'person.id') .select('pet.species as pet_species') ) .where('person.id', '=', id) .executeTakeFirst() } ``` We have two optional selections `pet_name` and `pet_species`. Both of them require the `pet` table to be joined, but we don't want to add an unnecessary join if both `withPetName` and `withPetSpecies` are `false`. But if both `withPetName` and `withPetSpecies` are `true`, we end up with two identical joins which will cause an error in the database. To prevent the error from happening, you can install the [DeduplicateJoinsPlugin](https://kysely-org.github.io/kysely-apidoc/classes/DeduplicateJoinsPlugin.html). You can either install it globally by providing it in the configuration: ```ts const db = new Kysely({ dialect, plugins: [new DeduplicateJoinsPlugin()], }) ``` or you can use it when needed: ```ts async function getPerson( id: number, withPetName: boolean, withPetSpecies: boolean ) { return await db .withPlugin(new DeduplicateJoinsPlugin()) .selectFrom('person') .selectAll('person') .$if(withPetName, (qb) => qb .innerJoin('pet', 'pet.owner_id', 'person.id') .select('pet.name as pet_name') ) .$if(withPetSpecies, (qb) => qb .innerJoin('pet', 'pet.owner_id', 'person.id') .select('pet.species as pet_species') ) .where('person.id', '=', id) .executeTakeFirst() } ``` You may wonder why this is a plugin and not the default behavior? The reason is that it's surprisingly difficult to detect if two joins are identical. It's trivial for simple joins like the ones in the example, but becomes quite complex with arbitrary joins with nested subqueries etc. There may be corner cases where the `DeduplicateJoinsPlugin` fails and we don't want it to affect people that don't need this deduplication (most people). See [this recipe](https://kysely.dev/docs/recipes/conditional-selects.md) if you are wondering why we are using the `$if` method. --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Expressions An [`Expression`](https://kysely-org.github.io/kysely-apidoc/interfaces/Expression.html) is the basic type-safe query building block in Kysely. Pretty much all methods accept expressions as inputs. Most internal classes like [SelectQueryBuilder](https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html) and [RawBuilder](https://kysely-org.github.io/kysely-apidoc/interfaces/RawBuilder.html) (the return value of the [sql tag](https://kysely-org.github.io/kysely-apidoc/functions/sql-1.html)) are expressions themselves. `Expression` represents an arbitrary SQL expression, like a binary expression (e.g. `a + b`), or a function call (e.g. `concat(arg1, ' ', arg2, ...)`). It can be any combination of those, no matter how complex. `T` is the output type of the expression. ## Expression builder[​](#expression-builder "Direct link to Expression builder") Expressions are usually built using an instance of [`ExpressionBuilder`](https://kysely-org.github.io/kysely-apidoc/interfaces/ExpressionBuilder.html). `DB` is the same database type you give to `Kysely` when you create an instance. `TB` is the union of all table names that are visible in the context. For example `ExpressionBuilder` means you can reference `person` and `pet` columns in the created expressions. You can get an instance of the expression builder using a callback: ```ts const person = await db .selectFrom('person') // `eb` is an instance of ExpressionBuilder .select((eb) => [ // Call the `upper` function on `first_name`. There's a bunch of // shortcuts to functions under the `fn` object such as // `eb.fn.coalesce()` that provide a cleaner syntax. eb.fn('upper', ['first_name']).as('upper_first_name'), // Select a subquery eb.selectFrom('pet') .select('name') .whereRef('pet.owner_id', '=', 'person.id') .limit(1) .as('pet_name'), // Select a boolean expression eb('first_name', '=', 'Jennifer').as('is_jennifer'), // Select a static string value eb.val('Some value').as('string_value'), // Select a literal value eb.lit(42).as('literal_value'), ]) // You can also destructure the expression builder like this .where(({ and, or, eb, not, exists, selectFrom }) => or([ and([ eb('first_name', '=', firstName), eb('last_name', '=', lastName) ]), not(exists( selectFrom('pet') .select('pet.id') .whereRef('pet.owner_id', '=', 'person.id') .where('pet.species', 'in', ['dog', 'cat']) )) ])) .executeTakeFirstOrThrow() console.log(person.upper_first_name) console.log(person.pet_name) console.log(person.is_jennifer) ``` The generated SQL: ```sql select upper("first_name") as "upper_first_name", ( select "name" from "pet" where "pet"."owner_id" = "person"."id" limit 1 ) as "pet_name", "first_name" = $1 as "is_jennifer", $2 as "string_value", 42 as "literal_value" from "person" where ( ( "first_name" = $3 and "last_name" = $4 ) or not exists ( select "pet.id" from "pet" where "pet"."owner_id" = "person"."id" and "pet"."species" in ($5, $6) ) ) ``` In the above query we used the expression builder in `select` and `where` methods. You can use it the same way in other methods like `having`, `on`, `orderBy`, `groupBy` etc. All expressions are composable. You can pass expressions as arguments of any expression. All query builder methods in Kysely accept expressions and expression builder callbacks. All expression builder methods offer auto-completions and type-safety just like methods on the query builders. You might be wondering, "why do I need to use a callback to get the expression builder?". "Why not just create an instance using a global function?". The reason is that when you use a callback, Kysely is able to infer the context correctly. The expression builder's methods only auto-complete and accept column and table names that are available in the context. In other words, using a callback provides more type-safety! There's also a global function `expressionBuilder` you can use to create expression builders: ```ts import { expressionBuilder } from 'kysely' // `eb1` has type `ExpressionBuilder` which means there are no tables in the // context. This variant should be used most of the time in helper functions since you // shouldn't make assumptions about the calling context. const eb1 = expressionBuilder() // `eb2` has type `ExpressionBuilder`. You can reference `person` columns // directly in all expression builder methods. const eb2 = expressionBuilder() // In this one you'd have access to tables `person` and `pet` and all their columns. const eb3 = expressionBuilder() let qb = db .selectFrom('person') .innerJoin('movie as m', 'm.director_id', 'person.id') // You can also provide a query builder instance and the context is inferred automatically. // Type of `eb` is `ExpressionBuilder` const eb = expressionBuilder(qb) qb = qb.where(eb.not(eb.exists( eb.selectFrom('pet') .select('pet.id') .whereRef('pet.name', '=', 'm.name') ))) ``` ## Creating reusable helpers[​](#creating-reusable-helpers "Direct link to Creating reusable helpers") The expression builder can be used to create reusable helper functions. Let's say we have a complex `where` expression we want to reuse in multiple queries: ```ts function hasDogNamed(name: string): Expression { const eb = expressionBuilder() return eb.exists( eb.selectFrom('pet') .select('pet.id') .whereRef('pet.owner_id', '=', 'person.id') .where('pet.species', '=', 'dog') .where('pet.name', '=', name) ) } ``` This helper can now be used in any query, and would work just fine if "person" table is in context: ```ts const doggoPersons = await db .selectFrom('person') .selectAll('person') .where(hasDogNamed('Doggo')) .execute() ``` However, the above helper is not very type-safe. The following code would compile, but fail at runtime: ```ts const bigFatFailure = await db .selectFrom('movie') // <-- "person" table is not in context! .selectAll('movie') .where(hasDogNamed('Doggo')) // <-- but we're referring to "person.id" in our helper .execute() ``` It's better to not make assumptions about the calling context and pass in all dependencies as arguments. In the following example we pass in the person's id as an expression. We also changed the type of `name` from `string` to `Expression`, which allows us to pass in arbitrary expressions instead of just values. ```ts function hasDogNamed(name: Expression, ownerId: Expression) { // Create an expression builder without any tables in the context. // This way we make no assumptions about the calling context. const eb = expressionBuilder() return eb.exists( eb.selectFrom('pet') .select('pet.id') .where('pet.owner_id', '=', ownerId) .where('pet.species', '=', 'dog') .where('pet.name', '=', name) ) } ``` Here's how you'd use our brand new helper: ```ts const doggoPersons = await db .selectFrom('person') .selectAll('person') .where((eb) => hasDogNamed(eb.val('Doggo'), eb.ref('person.id'))) .execute() ``` Learn more about reusable helper functions [here](https://kysely.dev/docs/recipes/reusable-helpers). ## Conditional expressions[​](#conditional-expressions "Direct link to Conditional expressions") In the following, we'll only cover `where` expressions. The same logic applies to `having`, `on`, `orderBy`, `groupBy` etc. > This section should not be confused with conditional selections in `select` clauses, which is a whole 'nother topic we discuss in [this recipe](https://kysely.dev/docs/recipes/conditional-selects). Having a set of optional filters you want to combine using `and`, is the most basic and common use case of conditional `where` expressions. Since the `where`, `having` and other filter functions are additive, most of the time this is enough: ```ts let query = db .selectFrom('person') .selectAll('person') if (firstName) { // The query builder is immutable. Remember to replace the builder // with the new one. query = query.where('first_name', '=', firstName) } if (lastName) { query = query.where('last_name', '=', lastName) } const persons = await query.execute() ``` The same query can be built using the expression builder like this: ```ts const persons = await db .selectFrom('person') .selectAll('person') .where((eb) => { const filters: Expression[] = [] if (firstName) { filters.push(eb('first_name', '=', firstName)) } if (lastName) { filters.push(eb('last_name', '=', lastName)) } return eb.and(filters) }) .execute() ``` Using the latter design, you can build conditional expressions of any complexity. --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Extending kysely In many cases, Kysely doesn't provide a built-in type-safe method for a feature. It's often because adding that feature in a generic way that would work in all use cases is difficult or impossible. In many cases it's better to create little helper functions in your project that suit your use case. Kysely makes this simple. The Kysely API is designed around two interfaces [`Expression`](https://kysely-org.github.io/kysely-apidoc/interfaces/Expression.html) and [`AliasedExpression`](https://kysely-org.github.io/kysely-apidoc/interfaces/AliasedExpression.html). Almost every method accepts values that implement these interfaces and most Kysely internals achieve their "type magic" by implementing them. Most of the time you can create your helpers using the [sql template tag](https://kysely-org.github.io/kysely-apidoc/interfaces/Sql.html) and the `RawBuilder` and `AliasedRawBuilder` class instances it returns, but it's good to first understand how the underlying interfaces they implement, `Expression` and `AliasedExpression`, work. ## Expression[​](#expression "Direct link to Expression") [`Expression`](https://kysely-org.github.io/kysely-apidoc/interfaces/Expression.html) is a simple interface that has a type `T` and a single method `toOperationNode()`. `T` tells Kysely's type system the type of the expression. `toOperationNode()` returns instructions on what SQL should be produced once the expression is compiled. Here's an example of a custom expression for `JSON` or `JSONB` values on PostgreSQL: ```ts import { Expression, Kysely, OperationNode, sql } from 'kysely' class JsonValue implements Expression { #value: T constructor(value: T) { this.#value = value } // This is a mandatory getter. You must add it and always return `undefined`. // The return type must always be `T | undefined`. get expressionType(): T | undefined { return undefined } toOperationNode(): OperationNode { const json = JSON.stringify(this.#value) // Most of the time you can use the `sql` template tag to build the returned node. // The `sql` template tag takes care of passing the `json` string as a parameter, alongside the sql string, to the DB. return sql`CAST(${json} AS JSONB)`.toOperationNode() } } ``` Now you can use your new `JsonValue` expression pretty much anywhere *as a value* in a type-safe way: ```ts interface DB { person: { address: { postalCode: string street: string } } } async function test(db: Kysely) { await db .insertInto('person') .values({ address: new JsonValue({ postalCode: '123456', street: 'Kysely avenue 42', }), }) .execute() await db .selectFrom('person') .selectAll() .where( 'address', '@>', new JsonValue({ postalCode: '123456', street: 'Kysely avenue 42' }) ) .execute() } ``` Most of the time you don't need to create your own classes that implement the `Expression` interface. You can simply wrap the [sql template tag](https://kysely-org.github.io/kysely-apidoc/interfaces/Sql.html) and the `RawBuilder` class instance it returns in a function. `RawBuilder`, like most things in Kysely, implements the `Expression` interface. Our previous example would get simplified into this: ```ts import { Kysely, RawBuilder, sql } from 'kysely' function json(value: T): RawBuilder { return sql`CAST(${JSON.stringify(value)} AS JSONB)` } ``` And you'd use it like this: ```ts interface DB { person: { address: { postalCode: string street: string } } } async function test(db: Kysely) { await db .insertInto('person') .values({ address: json({ postalCode: '123456', street: 'Kysely avenue 42', }), }) .execute() await db .selectFrom('person') .selectAll() .where( 'address', '@>', json({ postalCode: '123456', street: 'Kysely avenue 42' }) ) .execute() } ``` ## AliasedExpression[​](#aliasedexpression "Direct link to AliasedExpression") While `Expression` holds the type and compilation instructions of an SQL expression, [`AliasedExpression`](https://kysely-org.github.io/kysely-apidoc/interfaces/AliasedExpression.html) also holds an alias (a name) for that expression. `AliasedExpression` can be used in places where you need a name for the expression, like in a `SELECT` statement or a `FROM` statement. `AliasedExpression` is how kysely is able to infer the name and type of result columns. Let's expand the `JsonValue` example from the [previous section](#expression). We'll add an `as` method for the `JsonValue` class that can be used to turn an `Expression` into an `AliasedExpression`: ```ts import { Expression, AliasedExpression, Kysely, OperationNode, sql, AliasNode, IdentifierNode, } from 'kysely' class JsonValue implements Expression { // ... Methods from the previous example ... as(alias: A): AliasedJsonValue { return new AliasedJsonValue(this, alias) } } class AliasedJsonValue implements AliasedExpression { #expression: Expression #alias: A constructor(expression: Expression, alias: A) { this.#expression = expression this.#alias = alias } get expression(): Expression { return this.#expression } get alias(): A { return this.#alias } toOperationNode(): AliasNode { return AliasNode.create( this.#expression.toOperationNode(), IdentifierNode.create(this.#alias) ) } } ``` And now you can use `JsonValue` in `select` statements too with full type safety: ```ts interface DB { person: { address: { postalCode: string street: string } } } async function test(db: Kysely) { const result = await db .selectFrom('person') .select([new JsonValue({ someValue: 42 }).as('some_object'), 'address']) .where( 'address', '@>', new JsonValue({ postalCode: '123456', street: 'Kysely avenue 42' }) ) .executeTakeFirstOrThrow() console.log(result.some_object.someValue) console.log(result.address.postalCode) } ``` Again, in most cases you don't need to implement your own `AliasedExpression`. `RawBuilder` has a similar `as` method and we can use the three line long `json` function from our previous example: ```ts function json(value: T): RawBuilder { return sql`CAST(${JSON.stringify(value)} AS JSONB)` } ``` ```ts interface DB { person: { address: { postalCode: string street: string } } } async function test(db: Kysely) { const result = await db .selectFrom('person') .select([json({ someValue: 42 }).as('some_object'), 'address']) .where( 'address', '@>', json({ postalCode: '123456', street: 'Kysely avenue 42' }) ) .executeTakeFirstOrThrow() console.log(result.address.postalCode) console.log(result.some_object.someValue) } ``` ## A more complex example[​](#a-more-complex-example "Direct link to A more complex example") Consider this query: ```sql insert into t (t1, t2) select v.v1, j.j2 from (values ($1, $2, $3), ($4, $5, $6)) as v(id, v1, v2) inner join j on v.id = j.vid ``` Kysely doesn't have built-in support for the `values` keyword in this context, but you can create a type-safe helper function like this: ```ts function values, A extends string>( records: R[], alias: A ): AliasedRawBuilder { // Assume there's at least one record and all records // have the same keys. const keys = Object.keys(records[0]) // Transform the records into a list of lists such as // ($1, $2, $3), ($4, $5, $6) const values = sql.join( records.map((r) => sql`(${sql.join(keys.map((k) => r[k]))})`) ) // Create the alias `v(id, v1, v2)` that specifies the table alias // AND a name for each column. const wrappedAlias = sql.ref(alias) const wrappedColumns = sql.join(keys.map(sql.ref)) const aliasSql = sql`${wrappedAlias}(${wrappedColumns})` // Finally create a single `AliasedRawBuilder` instance of the // whole thing. Note that we need to explicitly specify // the alias type using `.as` because we are using a // raw sql snippet as the alias. return sql`(values ${values})`.as(aliasSql) } ``` A lot is going on in this function, but it's all documented in the [sql template tag's documentation.](https://kysely-org.github.io/kysely-apidoc/interfaces/Sql.html) Most of the time a helper like this would return either an instance of `RawBuilder` or `AliasedRawBuilder` and you'd create an instance using the `sql` template tag. You'd return a `RawBuilder` instance when only the data type of a column/table is needed and an `AliasedRawBuilder` when also the name of the column/table is needed. Our example function creates kind of a temporary table, so we need to tell Kysely both the type of the table AND the name of the table. This is how you could now create our query using the `values` helper: ```ts // This could come as an input from somewhere. const records = [ { id: 1, v1: 'foo', v2: 'bar', }, { id: 2, v1: 'baz', v2: 'spam', }, ] db.insertInto('t') .columns(['t1', 't2']) .expression( // The `values` function automatically parses the column types // from the records and you can refer to them through the table // alias `v`. This works because Kysely is able to parse the // AliasedRawBuilder type. db .selectFrom(values(records, 'v')) .innerJoin('j', 'v.id', 'j.vid') .select(['v.v1', 'j.j2']) ) ``` ## Extending using inheritance[​](#extending-using-inheritance "Direct link to Extending using inheritance") You usually don't want to do this because of the complexity of the types and TypeScript's limitations when it comes to inheritence and return types. You'll quickly run into problems. Even though Kysely uses classes, it is not designed from the OOP point of view. Classes are used because they are supported natively by TypeScript. They provide private variables and a nice discoverable API. ## Extending using module augmentation[​](#extending-using-module-augmentation "Direct link to Extending using module augmentation") > DISCLAIMER: We do not support this method. Use at your own risk. You can override and extend Kysely's builder classes via [Typescript module augmentation](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation). The following example adds an `addIdColumn` method to `CreateTableBuilder`, which helps in adding a PostgreSQL UUID primary key column: ```ts import { CreateTableBuilder, sql } from 'kysely' declare module 'kysely' { interface CreateTableBuilder { addIdColumn( col?: CN ): CreateTableBuilder } } CreateTableBuilder.prototype.addIdColumn = function ( this: CreateTableBuilder, col?: string ) { return this.addColumn(col || 'id', 'uuid', (col) => col.primaryKey().defaultTo(sql`gen_random_uuid()`) ) } ``` Now you can use `addIdColumn` seamlessly to create several tables with a uniform primary key definition: ```ts db.schema.createTable('person').addIdColumn().addColumn('name', 'varchar') db.schema.createTable('pet').addColumn('species', 'varchar').addIdColumn() ``` --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Introspecting relation metadata Extracting metadata about tables and views from your database schema in runtime is possible using the methods in the `instrospection` property of a `Kysely` instance. The example below uses a PostgreSQL connection to print information about all tables and views found in the database schema: ```ts import { Kysely, PostgresDialect } from 'kysely' import pg from 'pg' const { Pool } = pg async function logDatabaseSchema() { const db = new Kysely({ dialect: new PostgresDialect({ pool: new Pool({ connectionString: process.env.DATABASE_URL, }), }), }) const tables = await db.introspection.getTables() // const tables: TableMetadata[] console.log({ tables }) } logDatabaseSchema() ``` For more information check the docs for details on the interfaces [DatabaseIntrospector](https://kysely-org.github.io/kysely-apidoc/interfaces/DatabaseIntrospector.html) and [TableMetadata](https://kysely-org.github.io/kysely-apidoc/interfaces/TableMetadata.html). --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Logging It is possible to set up logs for all queries using the `log` property when instantiating `Kysely`. There are 2 ways to configure logging: ## 1. Provide an array with log level/s[​](#1-provide-an-array-with-log-levels "Direct link to 1. Provide an array with log level/s") You can provide an array of log levels to the `log` property when instantiating `Kysely`. When `'query'` is included in the array, `Kysely` will log all executed queries, not including parameter values. When `'error'` is included in the array, `Kysely` will log all errors. ```ts const db = new Kysely({ dialect, log: ['query', 'error'], }) ``` ## 2. Provide a custom logging function[​](#2-provide-a-custom-logging-function "Direct link to 2. Provide a custom logging function") You can provide a custom logging function to the `log` property when instantiating `Kysely`. The custom logging function receives a log event as an argument. `LogEvent` is a discriminated union. Query events may have `isStream`; only error events have an `error` property: ```ts type LogEvent = | { level: 'query' isStream?: boolean query: CompiledQuery queryDurationMillis: number } | { level: 'error' error: unknown query: CompiledQuery queryDurationMillis: number } ``` Example: ```ts const db = new Kysely({ dialect: new PostgresDialect(postgresConfig), log(event) { if (event.level === "error") { console.error("Query failed : ", { durationMs: event.queryDurationMillis, error: event.error, sql: event.query.sql, params: event.query.parameters.map(maskPII), }); } else { // `'query'` console.log("Query executed : ", { durationMs: event.queryDurationMillis, sql: event.query.sql, params: event.query.parameters.map(maskPII), }); } } }) ``` For more information check the docs for details on the interfaces [KyselyConfig](https://kysely-org.github.io/kysely-apidoc/interfaces/KyselyConfig.html). --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Raw SQL Use the [sql template tag](https://kysely-org.github.io/kysely-apidoc/interfaces/Sql.html) for a SQL expression inside a builder query or for a complete raw statement. A fragment can interpolate bound values, other fragments, and builder expressions. ## A small escape hatch inside a typed query[​](#a-small-escape-hatch-inside-a-typed-query "Direct link to A small escape hatch inside a typed query") [Materialize's time-bucket queries](https://github.com/MaterializeInc/materialize/blob/adb829aee5913d08eaccce2aee2e0df31c0a2dfd/console/src/api/materialize/cluster/replicaUtilizationHistory.ts#L150-L200), linked from the homepage, use `date_bin` expressions inside CTEs. The simplified PostgreSQL example below keeps the database-specific expression in one reusable helper: ```ts import { sql, type ExpressionBuilder } from 'kysely' interface Database { asset: { id: number owner_id: number kind: string created_at: Date } } const bucket = (eb: ExpressionBuilder) => sql`date_bin( ${'15 minutes'}::interval, ${eb.ref('created_at')}, ${new Date('2000-01-01T00:00:00Z')} )` ``` With a configured `Kysely` instance named `db`: ```ts const rows = await db .selectFrom('asset') .select('id') .select((eb) => bucket(eb).as('bucket')) .where('owner_id', '=', ownerId) .orderBy('bucket') .execute() // { id: number; bucket: Date }[] ``` The interval, origin, and owner ID become parameters. `eb.ref('created_at')` checks the reference against the query scope and renders an identifier. Renaming it to a missing column produces a TypeScript error, even though it appears inside a SQL fragment. The surrounding selection, filter, and ordering keep their builder checks. The `Date` in `sql` is a supplied result type. It does not verify the SQL, check the function's argument types, or convert the returned value. This example assumes PostgreSQL's driver returns the timestamp as a `Date`. Literal column names written directly inside the template are not checked; use `eb.ref` for checked references. A database function does not always need a SQL template: `eb.fn('function_name', [...])` can call functions without a dedicated helper. Its name, database signature, and supplied result type still need to be correct. ## Keep composing around the fragment[​](#keep-composing-around-the-fragment "Direct link to Keep composing around the fragment") A fragment is an expression the builder can alias, select, filter on, or combine with other expressions. Fragments can also interpolate subqueries and other fragments; values remain parameters as the pieces compose. You can keep most of a statement in the builder while using SQL text for one operation. Use `sql.ref`, `sql.table`, and `sql.id` when identifiers are only known at runtime. Those helpers quote identifiers but do not validate them against your `Database` type. `sql.raw` inserts text directly and does not bind or validate it; do not use it to interpolate untrusted values. For a full statement, `sql` can be executed through `.execute(db)`. Its result type is supplied rather than inferred from SQL text. See the [SQL API documentation](https://kysely-org.github.io/kysely-apidoc/interfaces/Sql.html) for fragment composition, parameter binding, and execution examples. --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Relations ### 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. Phew, glad we got that out the way.. Having said all 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, SQL Server, or SQLite) provide. In this recipe we show one way to do that when using the built-in PostgreSQL, MySQL, SQL Server, and SQLite dialects. This recipe is supported on MySQL versions starting from 8.0.14. This is due to the way subqueries use outer references in this recipe (cf. [MySQL 8.0.14 changelog](https://dev.mysql.com/doc/relnotes/mysql/8.0/en/news-8-0-14.html#mysqld-8-0-14-optimizer) | [MariaDB is not supported yet](https://jira.mariadb.org/browse/MDEV-19078)). ## The `json` data type and functions[​](#the-json-data-type-and-functions "Direct link to the-json-data-type-and-functions") PostgreSQL and MySQL have rich JSON support through their `json` data types and functions. `pg` and `mysql2`, the node drivers, automatically parse returned `json` columns as json objects. With the combination of these two things, we can write some super efficient queries with nested relations. Parsing JSON The built in `MssqlDialect`, `SqliteDialect` and some third-party dialects don't parse the returned JSON columns to objects automatically. Not even if they use `PostgreSQL` or `MySQL` under the hood! Parsing is handled (or not handled) by the database driver that Kysely has no control over. If your JSON columns get returned as strings, you can use the `ParseJSONResultsPlugin`: ```ts const db = new Kysely({ dialect, plugins: [new ParseJSONResultsPlugin()] }) ``` Let's start with some raw postgres SQL, and then see how we can write the query using Kysely in a nice type-safe way. In the following query, we fetch a list of people (from "person" table) and for each person, we nest the person's pets, and mother, into the returned objects: ```sql SELECT person.*, -- Select person's pets as a json array ( SELECT COALESCE(JSON_AGG(pets), '[]') FROM ( SELECT pet.id, pet.name FROM pet WHERE pet.owner_id = person.id ORDER BY pet.name ) pets ) pets, -- Select person's mother as a json object ( SELECT TO_JSON(mother) FROM ( SELECT mother.id, mother.first_name FROM person as mother WHERE mother.id = person.mother_id ) mother ) mother FROM person ``` Simple right 😅. Yeah, not so much. But it does provide full control over the queries and a really good performance as long as you have indices (or indexes, we don't judge) for "pet.owner\_id" and "person.mother\_id". Fortunately we can improve and simplify this a lot using Kysely. First let's define a couple of helpers: ```ts function jsonArrayFrom(expr: Expression) { return sql[]>`(select coalesce(json_agg(agg), '[]') from ${expr} as agg)` } function jsonObjectFrom(expr: Expression) { return sql>`(select to_json(obj) from ${expr} as obj)` } ``` These helpers are included in Kysely and you can import them from the `helpers` module like this: ```ts import { jsonArrayFrom, jsonObjectFrom } from 'kysely/helpers/postgres' ``` MySQL, SQL Server, and SQLite versions of the helpers are slightly different, but you can use them the same way. You can import them like this: ```ts import { jsonArrayFrom, jsonObjectFrom } from 'kysely/helpers/mysql' ``` ```ts import { jsonArrayFrom, jsonObjectFrom } from 'kysely/helpers/mssql' ``` ```ts import { jsonArrayFrom, jsonObjectFrom } from 'kysely/helpers/sqlite' ``` With these helpers, our example query already becomes a little more bearable to look at: ```ts const persons = await db .selectFrom('person') .selectAll('person') .select((eb) => [ // pets jsonArrayFrom( eb.selectFrom('pet') .select(['pet.id', 'pet.name']) .whereRef('pet.owner_id', '=', 'person.id') .orderBy('pet.name') ).as('pets'), // mother jsonObjectFrom( eb.selectFrom('person as mother') .select(['mother.id', 'mother.first_name']) .whereRef('mother.id', '=', 'person.mother_id') ).as('mother') ]) .execute() console.log(persons[0].pets[0].name) console.log(persons[0].mother?.first_name) ``` SQL Server SQL Server doesn't allow `ORDER BY` in subqueries unless they have an `OFFSET`, so add `.offset(0)` after `.orderBy(...)` in the subqueries you pass to the helpers, including the `pets` helper below: ```ts const persons = await db .selectFrom('person') .selectAll('person') .select((eb) => [ jsonArrayFrom( eb.selectFrom('pet') .select(['pet.id', 'pet.name']) .whereRef('pet.owner_id', '=', 'person.id') .orderBy('pet.name') .offset(0) ).as('pets'), ]) .execute() ``` That's better right? If you need to do this over and over in your codebase, you can create some helpers like these: ```ts function pets(ownerId: Expression) { return jsonArrayFrom( db.selectFrom('pet') .select(['pet.id', 'pet.name']) .where('pet.owner_id', '=', ownerId) .orderBy('pet.name') ) } function mother(motherId: Expression) { return jsonObjectFrom( db.selectFrom('person as mother') .select(['mother.id', 'mother.first_name']) .where('mother.id', '=', motherId) ) } ``` And now you get this: ```ts const persons = await db .selectFrom('person') .selectAll('person') .select(({ ref }) => [ pets(ref('person.id')).as('pets'), mother(ref('person.mother_id')).as('mother') ]) .execute() console.log(persons[0].pets[0].name) console.log(persons[0].mother?.first_name) ``` In some cases Kysely marks your selections as nullable if it's not able to know the related object always exists. If you have that information, you can mark the relation non-null using the `$notNull()` helper like this: ```ts const persons = await db .selectFrom('person') .selectAll('person') .select(({ ref }) => [ pets(ref('person.id')).as('pets'), mother(ref('person.mother_id')).$notNull().as('mother') ]) .execute() console.log(persons[0].pets[0].name) console.log(persons[0].mother.first_name) ``` If you need to select relations conditionally, `$if` is your friend: ```ts const persons = await db .selectFrom('person') .selectAll('person') .$if(includePets, (qb) => qb.select( (eb) => pets(eb.ref('person.id')).as('pets') )) .$if(includeMom, (qb) => qb.select( (eb) => mother(eb.ref('person.mother_id')).as('mother') )) .execute() ``` --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Reusable helpers info [Here's](https://play.kysely.dev/#cN4IgpgJglgLg9gJwM4gFyhgTwA5jSKAW20RgAJgAdAOzLIHExqwEBDGSAGhroGUwANmADGMVgCMh3WmQCq2COzASpPMgElqSFmMlhpAXzIAzBHEJlKIANaZtAzFYDcNGmAAeJBOSjUOCY1ZhMDIAEXYJVm0KNVxkOGpUMgAFFiQEgBUVMBcZXBgk1JgsvVyDV2ZPUjJff0DglLTM7JiZKAgkxmY2DggAHmoAV0JxFgA+XLpjKGQYAH1qVkIwJKQYBF8Ac0myASj5xeXV9a2dzaYIFk6LljKKjy8fPxZ6kKKSoVa6duvupX6hiNxjtDisyGsNtRtmo4AB3bpzH5kQGjBA7JC4YRQMBIJK8THYpB3ahuKreMhYXAMG4IMgAXksIEIrCEVjIAB9GcYwMzWSAOYy4DAABYsZykx4UnAhfEiQn0xkQOCbNmcqzCdiqxnCpZrMUgXIS6qUt5NWgM-hCUTZPqpeLUD5gCZG8kmsgAOTAsLt6XNGi0OhtPuaemdlUlbuD1Hkig4CpjSiDZsdYZd5EjYHIFsEIl0QltmZTuQexulHq9RQVmm03iTxWyYZLrrLRQTcYZbeUegL9dDuRAnBAAEdBixMPgiJLgGQAKKeBA4pBQBKcMi8IcCABCcDgAlXDwXSCXCU3gygAkuCFXSA3ZCMpnMjNs9kcBpok+q0-CuiiISiYU3O8TDMCwrBNABaSBYEQcUSWoYQEjWXZ9ndJYQgZKxeAyABBAAZXCAHl3RnWCaAQrRyDiX0kAARgVVhYVYWAyAgcQ1AAOnsXMADEQIACisKiEisABKDiuNEPiAG0rHaKxVysaZZgWNCrAAXTEmQAHotLIGj2LIAADG8BEMikeWwPY4zETYDIyYUoCQGonJFEIhH2KVcHApBWG5Mg4GwGBl2odi1B0sgAE04EGAByBcyGwMwADd2i2ClRTIBCBGGWhQTIWFYGFaLyFYahME8sBwOEUVhGsLZpDocLSogBLss2XwnNhBIYpK4xuVEGoYFCmR2NhUUFz4ky+ghLYxkMwZsDiPi9jWFTlhEwyFJAOl5OQtZUPWsLdIAJgM4yNzMjhiCskIbPywqjIXYxDIM7CypFNLsCibQWvgR6wGeo6yHOGAXOlKqausSAyFYTYmIo9K-2EYRhkGG6WpHMdMoSDh3CGjixpYMA+L46cwHEVcnrvET6TGNQ6HJyaN2mk4oTmhaloAEmAJ6BJAFaDlUkARIMDatp2gc9pgA6wBEhqyE0xrdIAZjsjLDOMagzOMQZ4KChIyFFARsCczBophpK4HaMhCEcpcoQS1gFz8UVtCQLSEMIZkkCBlgzGQGHqBawY3bIJ6nP-GikOEFaI4QTZhiYUHhroUbxuJ0myHJ1dNep2n6az8Q+M1lnIU2MY+Y5-VVxk-n9jWsB1LlxkJdXAWZbltRFbIdiPBEQYOD4kTDWoHW9eCsgq4QPiDySOdEsXYLS9mmmqBkBcYEGBBaCmma2fmxaWD47mD1FwziRoMfRAngQ4SP2fZ3nReEmXtnV7UDet535m9-Lwzb9hEfE+84z4X1Hrra+BtyIahgHxdi8CDy4kfgvI8S9f5jCkhpL4YdMxf3BBudiAArK21AZ7ziQNeC67J2SGREuxTmGo1gZDgK-cuQ8wHkSQkJLQx16KMWYqxcSOZRC8XMHzbhokhFWlgbXOSktFIzFWqCJuBN04kzJhTHBxg850jGIXPiU8+K8ysALBuolm5WFblLDu3de7uH7oPYeFROGUTNEgZWfCmLkEESNCSMBRGEHEWaSRvjhEyNkhAXaCjlLKJABpVRRN1GF0pgDVcSUWQ6LpjIBmRcC50GgewAS2S6AlIAUfYxIAlJKKFiJTuxSSlkHSQIPmjI6kNIaYYippjYm1Plg0tp7TLHyTyYyJAmABBJRxP4NcOF8JERIgOAuAzbF9xRo4keLiEpuIACyeIEWxUJ0iAlBPtCE1OvhugACkSFBJgLtPixDfA010QXR5IUEgk3Js8rJ7T9GCTNOxKpgtlhRO2rtMp09ybsQqfkdiPTelLPlrYvxSSnppIyaLWmZAZLFOidUkFizinhXUNos2gxJ7RFYIbQQcQai0GMmEzaZAyXIjANDP6LJGJ2ASsldof5aAPAEFALEdyiW6TysYRAg0KVpVckZKIZllgijgBAFOJSCmwJhQCoFZjhbouaWyUSKTjC3LhTUuhUQim-KsKCOYBURRzHyMM4pAz4kjUQJeTcmBUUA0ybsO+08Kk6vhSs+xaziZOLglffWtB2hIAIsYKMSB7LsAABKsEmaEZUMsIB8VBHPJ+qCX7oPfjITZ5MFQHmftQU855Lx9FCJuVczBJkIArpGoG2FwSDHEJjBA5URTsBwZvbeLkMp8r8FAaYaR-LaJZAILZ9ofbaV0oO8gOpJkwxYsqZEaEWqGVBC9D+uDt6FwLpxMJxz-l3OFuelF172JwgRHI7uqdCYTQfRiOUOJQVWKsEqFUt7ilp0SQ+2J4tdqgkjeUOCmyAMywVFYLNmxNhwFIvBRCril0AFY9neIOanPxV6QASKA4RsJ2EBAGpI8EsjPd30Zy+fnYpjMRn-PtOxORfSSmyRJIS35caE1JpTTAdNmbs17pnuIdiTS+LwbQgil1SKOKrIHhGke0aJ6OQIheFgKbSGwzBPPQ8x5qADGGKiMYpa6Cf1PVNdcW4dwCDmoZsgejuaGYMOfGgMGyKYcXdRAAbHhliBGe5Ef4ux30ZzwthOkhE0FwahZurfWozOTS-Xad0wgfTfFZOBYAAy1NDQ49TFRNMG3gJoGAfQMhZzxhcJyv8BRDCoxXB+xnq21as9g8K9lHLDq-k5QynWi1mZRCwFraNnNmSnUZA8s2nKtb2HoIGzUjKjdM+ZoEbazJCnGgVbQarbPfwEH0AudWPAcCDkt6bZAAD8yILOTc5MtsgSQJsIDUHNY+wBT4iVQKgWoYBzgIG89QXzGGEbcKQAAdhC6xC9RzIs0dOcLJHuZPniG+ditQCX+NckUcCxuBPDEF3JiMjHIiUdOrow0qnsCbU1MpwxgASgDE5vpOORPkWC3nsKn0sERDz19JT2JCttrAmiovU6cyiLwDUexp403Cn0cC4EyD9acgN5gkBICU85tQIU7pptDyRexS117dV1I0v2Awg5oAslzPgEgaxNiHgHDYOwghxzoBAK20z+ACvsWOgAThDyAAwBggA) a playground link containing all the code in this recipe. Let's say you want to write the following query: ```sql SELECT id, first_name FROM person WHERE upper(last_name) = $1 ``` Kysely doesn't have a built-in `upper` function but there are at least three ways you could write this: ```ts const lastName = 'STALLONE' const persons = await db .selectFrom('person') .select(['id', 'first_name']) // 1. `sql` template tag. This is the least type-safe option. // You're providing the column name without any type-checking, // and plugins won't affect it. .where( sql`upper(last_name)`, '=', lastName ) // 2. `sql` template tag with `ref`. Anything passed to `ref` // gets type-checked against the accumulated query context. .where(({ eb, ref }) => eb( sql`upper(${ref('last_name')})`, '=', lastName )) // 3. The `fn` function helps you avoid missing parentheses/commas // errors and uses refs as 1st class arguments. .where(({ eb, fn }) => eb( fn('upper', ['last_name']), '=', lastName )) .execute() ``` but each option could be more readable or type-safe. Fortunately Kysely allows you to easily create composable, reusable and type-safe helper functions: ```ts import { Expression, sql } from 'kysely' function upper(expr: Expression) { return sql`upper(${expr})` } function lower(expr: Expression) { return sql`lower(${expr})` } function concat(...exprs: Expression[]) { return sql.join(exprs, sql`||`) } ``` Using the `upper` helper, our query would look like this: ```ts const lastName = 'STALLONE' const persons = await db .selectFrom('person') .select(['id', 'first_name']) .where(({ eb, ref }) => eb( upper(ref('last_name')), '=', lastName )) .execute() ``` The recipe for helper functions is simple: take inputs as `Expression` instances where `T` is the type of the expression. For example `upper` takes in any `string` expression since it transforms strings to upper case. If you implemented the `round` function, it'd take in `Expression` since you can only round numbers. The helper functions should then use the inputs to create an output that's also an `Expression`. Everything you can create using the expression builder is an instance of `Expression`. So is the output of the `sql` template tag and all methods under the `sql` object. Same goes for `SelectQueryBuilder` and pretty much everything else in Kysely. Everything's an expression. See [this recipe](https://kysely.dev/docs/recipes/expressions) to learn more about expressions. So we've learned that everything's an expression and that expressions are composable. Let's put this idea to use: ```ts const persons = await db .selectFrom('person') .select(['id', 'first_name']) .where(({ eb, ref, val }) => eb( concat( lower(ref('first_name')), val(' '), upper(ref('last_name')) ), '=', 'sylvester STALLONE' )) .execute() ``` So far we've only used our helper functions in the first argument of `where` but you can use them anywhere: ```ts const persons = await db .selectFrom('person') .innerJoin('pet', (join) => join.on(eb => eb( 'person.first_name', '=', lower(eb.ref('pet.name')) ))) .select(({ ref, val }) => [ 'first_name', // If you use a helper in `select`, you need to always provide an explicit // name for it using the `as` method. concat(ref('person.first_name'), val(' '), ref('pet.name')).as('name_with_pet') ]) .orderBy(({ ref }) => lower(ref('first_name'))) .execute() ``` ## Reusable helpers using `ExpressionBuilder`[​](#reusable-helpers-using-expressionbuilder "Direct link to reusable-helpers-using-expressionbuilder") #### Subquery[​](#subquery "Direct link to Subquery") Here's an example of a helper function that uses the expression builder to build a subquery that gets filtered by a dynamic string expression. ```ts import { Expression, expressionBuilder } from 'kysely' function idsOfPersonsThatHaveDogNamed(name: Expression) { const eb = expressionBuilder() // A subquery that returns the identifiers of all persons // that have a dog named `name`. return eb .selectFrom('pet') .select('pet.owner_id') .where('pet.species', '=', 'dog') .where('pet.name', '=', name) } ``` And here's how you could use it: ```ts const dogName = 'Doggo' const persons = await db .selectFrom('person') .selectAll('person') .where((eb) => eb( 'person.id', 'in', idsOfPersonsThatHaveDogNamed(eb.val(dogName)) )) .execute() ``` Note that `idsOfPersonsThatHaveDogNamed` doesn't execute a separate query but instead returns a subquery expression that's compiled as a part of the parent query: ```sql select person.* from person where person.id in ( select pet.owner_id from pet where pet.species = 'dog' and pet.name = ? ) ``` In all our examples we've used the following syntax: ```ts .where(eb => eb(left, operator, right)) ``` When the expression builder `eb` is used as a function, it creates a binary expression. All binary expressions with a comparison operator are represented as a `Expression`. You don't always need to return `eb(left, operator, right)` from the callback though. Since `Expressions` are composable and reusable, you can return any `Expression`. This means you can create helpers like this: ```ts function isOlderThan(age: Expression) { return sql`age > ${age}` } ``` ```ts const persons = await db .selectFrom('person') .select(['id', 'first_name']) .where(({ val }) => isOlderThan(val(60))) .execute() ``` #### SQL function + calculation[​](#sql-function--calculation "Direct link to SQL function + calculation") Here we pass a dynamic `Date` expression to a function expression that takes part in a calculation. It is a timestamp to milliseconds helper and it is quite handy as a way to keep dates consistent, even after JSON functions throw away data type information denying drivers from transforming to `Date` in TypeScript-side. ```ts export function timestampToUnix(expr: Expression) { const eb = expressionBuilder() return eb(eb.fn('UNIX_TIMESTAMP', [expr]), '*', 1_000) } ``` Here's how to use it: ```ts await kysely.selectFrom('table').select((eb) => timestampToUnix(eb.ref('created_at')).as('created_at')) ``` ## Dealing with nullable expressions[​](#dealing-with-nullable-expressions "Direct link to Dealing with nullable expressions") If you want your helpers to work with nullable expressions (nullable columns etc.), you can do something like this: ```ts import { Expression, sql } from 'kysely' // This function accepts both nullable and non-nullable string expressions. function toInt(expr: Expression) { // This returns `Expression` if `expr` is nullable // and `Expression` otherwise. return sql`(${expr})::integer` } ``` ## Passing select queries as expressions[​](#passing-select-queries-as-expressions "Direct link to Passing select queries as expressions") Let's say we have the following query: ```ts const expr: Expression<{ name: string }> = db .selectFrom('pet') .select('pet.name') ``` The expression type of our query is `Expression<{ name: string }>` but SQL allows you to use a query like that as an `Expression`. In other words, SQL allows you to use single-column record types like scalars. Most of the time Kysely is able to automatically handle this case but with helper functions you need to use `$asScalar()` to convert the type. Here's an example: ```ts const persons = await db .selectFrom('person') .select((eb) => [ 'id', 'first_name', upper( eb.selectFrom('pet') .select('name') .whereRef('person.id', '=', 'pet.owner_id') .limit(1) .$asScalar() // <-- This is needed .$notNull() ).as('pet_name') ]) ``` The subquery is an `Expression<{ name: string }>` but our `upper` function only accepts `Expression`. That's why we need to call `$asScalar()`. `$asScalar()` has no effect on the generated SQL. It's simply a type-level helper. We also used `$notNull()` in the example because our simple `upper` function doesn't support nullable expressions. --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Working with schemas First of all, when we talk about schemas in this document, we mean custom schemas like [postgres schemas](https://www.postgresql.org/docs/14/ddl-schemas.html). There are two common ways to use schemas: 1. To group a logical set of tables under the same "namespace". For example all tables directly related to users could live under a `user` schema. 2. To have a separate namespaced copy of a set of tables for each tenant in a multitenant application. Kysely offers tools for both of these cases. ## 1[​](#1 "Direct link to 1") When you have an enumarable set of schemas, you can add them to your database interface like this: ```ts interface Database { 'user.user': UserTable 'user.user_permission': UserPermissionTable 'user.permission': PermissionTable pet: PetTable } ``` then you can refer to the tables just like you would a normal table: ```ts db.selectFrom('user.user') .where('username', '=', '') // You can also include the full table name .where('user.user.created_at', '>', createdAt) .innerJoin('user.user_permission as up', 'up.user_id', 'user.user.id') .innerJoin('user.permission as p', 'p.id', 'up.permission_id') .selectAll() ``` ## 2[​](#2 "Direct link to 2") In the multitenant case you have a schema per tenant and you can't add each of them to the database interface, nor would it make sense to do so. In this case you can use the [withSchema](https://kysely-org.github.io/kysely-apidoc/classes/Kysely.html#withSchema) method. The `withSchema` method sets the default schema of all table references that don't explicitly specify a schema: ```ts db.withSchema(tenant) .selectFrom('user') .innerJoin('user_permission as up', 'up.user_id', 'user.id') .innerJoin('public.permission as p', 'p.id', 'up.permission_id') .selectAll() ``` This is the generated SQL assuming `tenant` equals `'acme'`: ```sql select * from "acme"."user" inner join "acme"."user_permission" as "up" on "up"."user_id" = "acme"."user"."id" inner join "public"."permission" as "p" on "p"."id" = "up"."permission_id" ``` In this example we also referred to a shared table `permission` in the `public` schema. Please note that you need to add a `'public.permission': PermissionTable` item in your database schema to be able to refer to the `public.permission` table: ```ts interface Database { // Add your tenant tables without any schema: user: UserTable user_permission: UserPermissionTable // Add schemas and tables you need to explicitly reference like this: 'public.permission': PermissionTable // You can also have other shared tables with or without schemas here. // But keep in mind that if you want to refer to them from a `withSchema` // query, you need the table name with the schema name. pet: PetTable } ``` See the [first case](#1) for more info. --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Splitting query building and execution Kysely is primarily a type-safe sql query builder. It also does query execution, migrations, etc. in order to align with Knex's "batteries included" approach. ## "Cold" Kysely instances[​](#cold-kysely-instances "Direct link to \"Cold\" Kysely instances") In order to use Kysely purely as a query builder without database driver dependencies, you can instantiate it with the built-in `DummyDriver` class: ```ts import { Generated, DummyDriver, Kysely, PostgresAdapter, PostgresIntrospector, PostgresQueryCompiler, } from 'kysely' interface Person { id: Generated first_name: string last_name: string | null } interface Database { person: Person } const db = new Kysely({ dialect: { createAdapter: () => new PostgresAdapter(), createDriver: () => new DummyDriver(), createIntrospector: (db) => new PostgresIntrospector(db), createQueryCompiler: () => new PostgresQueryCompiler(), }, }) ``` This Kysely instance will compile to PostgreSQL sql dialect. You can brew "dummy" dialects to compile to all kinds of sql dialects (e.g. MySQL). Trying to execute queries using "cold" kysely instances will return empty results without communicating with a database. > "Cold" Kysely instances are not required for the following sections. You can use "hot" kysely instances, with real drivers, if you want to. ## Compile a query[​](#compile-a-query "Direct link to Compile a query") To compile a query, simply call `.compile()` at the end of the query building chain: ```ts const compiledQuery = db .selectFrom('person') .select('first_name') .where('id', '=', id) .compile() console.log(compiledQuery) // { sql: 'select "first_name" from "person" where "id" = $1', parameters: [1], query: { ... } } ``` The result of `.compile()` is a `CompiledQuery` object. It contains the query string (in `sql` field), parameters and the original Kysely-specific syntax tree used for compilation. This output alone can be used with any database driver that understands the sql dialect used (PostgreSQL in this example). Raw queries can be compiled as well: ```ts import { Selectable, sql } from 'kysely' const compiledQuery = sql>`select * from person where id = ${id}`.compile(db) console.log(compiledQuery) // { sql: 'select * from person where id = $1', parameters: [1], query: { ... } } ``` ## Infer result type[​](#infer-result-type "Direct link to Infer result type") Kysely supports inferring a (compiled) query's result type even when detached from query building chains. This allows splitting query building, compilation and execution code without losing type-safety. ```ts import { InferResult } from 'kysely' const query = db .selectFrom('person') .select('first_name') .where('id', '=', id) type QueryReturnType = InferResult // { first_name: string }[] const compiledQuery = query.compile() type CompiledQueryReturnType = InferResult // { first_name: string }[] ``` ## Execute compiled queries[​](#execute-compiled-queries "Direct link to Execute compiled queries") The `CompiledQuery` object returned by `.compile()` can be executed via "hot" Kysely instances (real drivers in use): ```ts const compiledQuery = db .selectFrom('person') .select('first_name') .where('id', '=', id) .compile() const results = await db.executeQuery(compiledQuery) ``` The `QueryResult` object returned by `.executeQuery()` contains the query results' rows, insertId and number of affected rows (if applicable). --- AI agents: Read [llms.txt](https://kysely.dev/llms.txt) for the documentation index and links to Markdown (.md) versions of individual pages. Read [llms-full.txt](https://kysely.dev/llms-full.txt) for the full documentation in one file. # Browser Kysely also runs in the browser. Here's a minimal example: ```ts import { Kysely, Generated, DummyDriver, SqliteAdapter, SqliteIntrospector, SqliteQueryCompiler, } from 'kysely' interface Person { id: Generated first_name: string last_name: string | null } interface Database { person: Person } const db = new Kysely({ dialect: { createAdapter() { return new SqliteAdapter() }, createDriver() { return new DummyDriver() }, createIntrospector(db: Kysely) { return new SqliteIntrospector(db) }, createQueryCompiler() { return new SqliteQueryCompiler() }, }, }) window.addEventListener('load', () => { const sql = db.selectFrom('person').select('id').compile() const result = document.createElement('span') result.id = 'result' result.innerHTML = sql.sql document.body.appendChild(result) }) ``` ---