Skip to main content
The 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

The sql template tag allows you to write raw SQL with automatic parameter escaping:
Parameters passed into the template are automatically bound and escaped, preventing SQL injection attacks.

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
WARNING: sql.raw() does not offer any protection against SQL injection. You must validate any user input beforehand.

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
WARNING: This function does not offer any protection against SQL injections. You must validate any user input beforehand.

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
Without separator:

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:
Use with caution. Only use with trusted values to avoid SQL injection.

.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

The sql template tag supports TypeScript generics for type-safe results:

SQL Injection Protection

Drizzle automatically protects against SQL injection by:
  1. Parameterizing values: All interpolated values use parameter binding
  2. Type checking: TypeScript prevents unsafe value types
  3. Escaping identifiers: sql.identifier() escapes special characters