Use database-specific SQL
A database-specific function, operator, or expression is unavailable through the query builder.
Drizzle ORM · Module
db.execute runs raw SQL through Drizzle ORM. Use the sql template to interpolate schema objects and runtime values while keeping values parameterized.
db.execute runs a raw SQL statement represented by Drizzle’s sql template. Schema tables and columns are converted to escaped SQL identifiers, while interpolated runtime values become bound parameters rather than concatenated SQL text.
await db.execute(statement)| Name | Type | Description |
|---|---|---|
statement | SQL | A raw SQL statement, typically created with Drizzle’s sql tagged template. |
The database driver’s result for the executed SQL statement.
db.execute when a query needs SQL that is not conveniently expressed through Drizzle’s relational or query-builder APIs.sql tagged template and interpolate Drizzle table or column objects directly.sql template for runtime values so the query remains parameterized; do not construct SQL by string concatenation.import { sql } from 'drizzle-orm';
const userId = 69;
const result = await db.execute(
sql`select * from ${users} where ${users.id} = ${userId}`,
);Build a parameterized SQL template with schema objects and a runtime value, then execute it through the database instance.
A database-specific function, operator, or expression is unavailable through the query builder.
A query needs hand-written SQL while still using Drizzle schema objects and bound values.
A statement must be inspected for its generated text and parameters for a particular database.
db.execute used for?db.execute sends a raw SQL statement to the configured database. The recommended form uses Drizzle’s sql template, which supports parameterized interpolation and escaped schema identifiers.
Follow-up: How should a runtime value be inserted safely? Interpolate it inside sql rather than concatenating it into a string; Drizzle emits it as a bound parameter.
sql template?The sql template maps supplied tables and columns to their SQL syntax and escapes their names. It also appends the escaped table name to column references where required.
Follow-up: Why does dialect matter when inspecting generated SQL? SQL placeholder and identifier syntax can differ between database dialects.
await db.execute(...) return?The call returns the result produced by the database driver for the executed statement. The exact result shape is driver- and dialect-dependent, so the page demonstrates awaiting the result rather than prescribing one universal row type.
Follow-up: What should be used when repeatedly executing the same query? Consider Drizzle prepared statements, whose execute method can be invoked repeatedly with placeholder values.
sqlsql.placeholderprepareexecute