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 ofExpressionBuilder<DB, TB>:
DBis the same database type you give toKyselyTBis the union of all table names visible in the context
ExpressionBuilder<DB, 'person' | 'pet'> means you can reference person and pet columns.
Getting an expression builder
You can get an instance using a callback:Why use callbacks?
You might wonder: “Why use a callback to get the expression builder? Why not a global function?”Using expressionBuilder globally
There’s also a globalexpressionBuilder 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:Type-safe helpers
It’s better to not make assumptions about the calling context: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 withand, use additive where calls:
Using expression builder
The same query using the expression builder: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