sql template tag allows you to write raw SQL snippets and queries when Kysely’s query builder API doesn’t cover your use case. It provides a safe way to embed SQL while preventing SQL injection through parameterization.
Basic Usage
Simple Raw SQL
Create a raw SQL snippet:${}) are automatically passed to the database as parameters and are never interpolated into the SQL string. There’s no need to worry about SQL injection vulnerabilities.
Executing Raw SQL
SQL snippets can be executed by calling theexecute method:
Using Raw SQL in Queries
You can use raw SQL expressions in select, where, and other clauses:Merging SQL Expressions
You can merge othersql expressions and queries using substitutions:
Helper Methods
Thesql tag provides several helper methods for common use cases:
sql.ref - Column References
Interpret a substitution as a column reference:sql.table - Table References
Interpret a substitution as a table reference:sql.id - Arbitrary Identifiers
Add arbitrary identifiers (like index names):sql.val - Value Parameters
sql.val(value) is a shortcut for:
sql.lit - Literal Values
Add literal values directly to the SQL string:sql.raw - Raw SQL Strings
Add arbitrary runtime SQL:The difference between
sql.lit and sql.raw is that sql.lit assumes the input is a value and will quote it appropriately, while sql.raw assumes the input is already valid SQL and glues it in as-is.sql.join - Lists
Join arrays of values or expressions:, ):
Type Safety
When using thesql tag, you need to specify the type of the expression:
Working with Expression Builder
You can combine raw SQL with the expression builder for type-safe column references:Common Use Cases
Database Functions
Use raw SQL for database-specific functions:CTEs with Raw SQL
Complex WHERE Conditions
Database-Specific Features
Best Practices
- Always use parameters: Never concatenate user input directly into SQL strings
- Specify types: Always provide type parameters to the
sqltag - Use helpers cautiously: Only use
sql.ref,sql.table,sql.id,sql.lit, andsql.rawwith trusted inputs - Prefer query builder: Use raw SQL only when the query builder doesn’t support your use case
- Keep it simple: Break complex raw SQL into smaller, reusable pieces
API Reference
Main Tag
sql<T>- Create a raw SQL expression
Helper Methods
sql.ref<R>(columnReference)- Column referencesql.table<T>(tableReference)- Table referencesql.id<T>(...ids)- Arbitrary identifiersql.val<V>(value)- Value parametersql.lit<V>(value)- Literal valuesql.raw<R>(sql)- Raw SQL stringsql.join<T>(array, separator?)- Join array items
Deprecated
sql.value<V>(value)- Usesql.valinsteadsql.literal<V>(value)- Usesql.litinstead