Guides
Expressions
An Expression<T>
is Kysely's fundamental building block for type-safe queries. They represent SQL expressions like:
- Binary operations (
a + b
) - Function calls (
concat(arg1, ' ', arg2)
) - Complex combinations of both
Expression Builder
Basic Usage
Complex Conditions
Creating Reusable Helpers
❌ Less Type-Safe Approach
✅ Type-Safe Approach
Conditional Expressions
Simple AND Conditions
Global Expression Builder
Best Practices
-
Use Callbacks for Type Safety
- Prefer callback-style expression builders
- Provides better type inference and auto-completion
-
Helper Functions
- Accept expressions as parameters instead of raw values
- Avoid assuming table context
- Pass table references explicitly
-
Conditional Logic
- Use array of filters for AND conditions
- Build complex conditions using expression builder methods
- Remember query builder immutability
-
Type Safety
- Use
never
as table context when creating generic helpers - Pass all dependencies explicitly
- Let the caller provide the context
- Use