Skip to main content
Kysely is built in a way that by default you can’t refer to tables or columns that are not visible in the current query context. This is all done by TypeScript at compile time, which means you need to know the columns and tables at compile time. The DynamicModule is designed for cases where column or table names come from user input or are not otherwise known at compile time.
Security Warning: Unlike values, column names are not escaped by the database engine or Kysely. If you pass unchecked column names using the dynamic module, you create an SQL injection vulnerability. Always validate user input before passing it to these methods.

Accessing the dynamic module

The dynamic module is available on the db instance:

Dynamic column references

Use ref() to create references to columns not known at compile time.

Filter by dynamic column

Order by dynamic column

Dynamic selections

You can add selections dynamically with proper typing:
The resulting type contains all PossibleColumns as optional fields because we cannot know which field was actually selected before running the code.

Dynamic table references

Use table() to reference tables that aren’t fully known at compile time. The type parameter can be a union of multiple tables.

Generic find function

Here’s a type-safe helper for finding a row by any column value:

Best practices

Validate input

Always validate column and table names before passing them to dynamic methods

Use type unions

Define explicit type unions for possible column values to maintain type safety

Prefer static

Only use dynamic queries when truly necessary — static queries are safer

Use allowlists

Maintain allowlists of valid column/table names rather than accepting arbitrary input
Here’s a more complete example combining multiple dynamic features:
Notice how we use TypeScript’s type system to restrict which columns can be searched and sorted, providing a layer of safety on top of the dynamic references.