Skip to main content
An Expression<T> is the basic type-safe query building block in Kysely. Pretty much all methods accept expressions as inputs.

What is an Expression?

Expression<T> represents an arbitrary SQL expression, like:
  • A binary expression (e.g., a + b)
  • A function call (e.g., concat(arg1, ' ', arg2, ...))
  • Any combination of these, no matter how complex
T is the output type of the expression.
Most internal classes like SelectQueryBuilder and RawBuilder (the return value of the sql tag) are expressions themselves.

Expression Builder

Expressions are usually built using an instance of ExpressionBuilder<DB, TB>:
  • DB is the same database type you give to Kysely
  • TB is the union of all table names visible in the context
For example, ExpressionBuilder<DB, 'person' | 'pet'> means you can reference person and pet columns.

Getting an expression builder

You can get an instance using a callback:
This generates:

Why use callbacks?

You might wonder: “Why use a callback to get the expression builder? Why not a global function?”
Callbacks allow Kysely 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. This provides more type-safety!

Using expressionBuilder globally

There’s also a global expressionBuilder function:

Composability

All expressions are composable:

Pass expressions as arguments

You can pass expressions as arguments to other expressions

Use anywhere

All query builder methods accept expressions and callbacks

Type-safe

All methods offer auto-completions and type checking

No runtime cost

Expressions compile to efficient SQL

Creating reusable helpers

The expression builder is perfect for creating reusable helpers. Here’s a basic example:
The above helper is not very type-safe. The following would compile but fail at runtime:

Type-safe helpers

It’s better to not make assumptions about the calling context:
Learn more in the reusable helpers recipe.

Conditional expressions

This section covers conditional where expressions. For conditional selections in select clauses, see the conditional selects recipe.

Basic conditional filters

For optional filters combined with and, use additive where calls:

Using expression builder

The same query using the expression builder:
Using this pattern, you can build conditional expressions of any complexity.

Common expression builder methods

Where to use expressions

Expressions work in all parts of a query:
1

select

Build complex selections with functions and subqueries
2

where / having

Create complex filter conditions
3

on

Use in join conditions
4

orderBy / groupBy

Sort and group by expressions
5

set / values

Use in updates and inserts