Raw SQL
The sql
template tag lets you write raw SQL snippets while maintaining safety and type information:
Key Features
- All substitutions (
${}
) are automatically parameterized - SQL injection protection built-in
- Supports values, expressions, queries, and other Kysely builders
- Can be used in most Kysely query builder methods
Common Use Cases
In Select Statements
In Where Clauses
Combining with Other Queries
Utility Functions
sql.ref() - Column References
Creates safe column references:
sql.table() - Table References
Creates safe table references:
sql.join() - Lists of Values
Creates comma-separated lists:
sql.lit() - Literal Values
Adds literal values (use with caution):
sql.raw() - Raw SQL
Adds raw SQL (use with caution):
Type Safety Examples
Important Notes
-
Security:
- Regular substitutions (
${}
) are safe and parameterized sql.lit()
,sql.raw()
,sql.ref()
, andsql.table()
are NOT safe with unchecked input
- Regular substitutions (
-
Best Practices:
- Use the query builder when possible
- Use raw SQL only when necessary
- Always prefer parameterized values over literals
- Validate any input used with the unsafe utility functions
-
Type Safety:
- Specify return types using the generic parameter:
sql<ReturnType>
- Use builder expressions for maximum type safety
- TypeScript types don't affect runtime behavior
- Specify return types using the generic parameter: