sql template tag is Drizzle’s core primitive for constructing raw SQL queries with automatic parameter binding and type safety. It provides escape hatches for complex queries while maintaining protection against SQL injection.
Import
Basic Usage
Simple SQL Queries
Thesql template tag allows you to write raw SQL with automatic parameter escaping:
Type-Safe SQL Queries
Specify the return type using TypeScript generics:SQL Methods
sql.raw()
Create SQL from a raw string without parameter binding:string
required
The raw SQL query string
sql.identifier()
Create a SQL chunk that represents a database identifier (table, column, index, etc.). When used in a query, the identifier will be escaped based on the database engine.string
required
The identifier name to escape
sql.join()
Join multiple SQL chunks with an optional separator:SQLChunk[]
required
Array of SQL chunks to join
SQLChunk
Optional separator to insert between chunks
sql.empty()
Create an empty SQL query:sql.placeholder()
Create a named placeholder for prepared statements:string
required
The name of the placeholder
sql.param()
Create a parameter with an optional encoder:TData
required
The parameter value
DriverValueEncoder<TData, TDriver>
Optional encoder to convert the value to a driver parameter
SQL Instance Methods
.as()
Alias a SQL expression for use in select queries:string
required
The alias name for this SQL expression
.mapWith()
Provide a custom decoder to transform the database value:DriverValueDecoder | function
required
Decoder function or object with mapFromDriverValue method
.inlineParams()
Inline parameters directly into the SQL string instead of using parameter binding:.if()
Conditionally include a SQL chunk in the query:any
required
Condition to check. Returns itself if truthy, undefined otherwise
Using SQL with Table References
Reference tables and columns directly in sql queries:Advanced Examples
Dynamic WHERE Clauses
Custom Aggregations
Window Functions
Array Operations (PostgreSQL)
JSON Operations
Type Safety
Thesql template tag supports TypeScript generics for type-safe results:
SQL Injection Protection
Drizzle automatically protects against SQL injection by:- Parameterizing values: All interpolated values use parameter binding
- Type checking: TypeScript prevents unsafe value types
- Escaping identifiers:
sql.identifier()escapes special characters
Related APIs
- Transactions - Execute SQL within transactions
- Migrations - Use sql for custom migrations
- Query Builder - Type-safe query building