Reuse parameterized queries
A frequently executed query has the same SQL shape but different filter values.
Drizzle ORM · Module
.prepare converts a Drizzle query into a reusable prepared statement. Execute it repeatedly, supplying named placeholder values when runtime inputs are needed.
.prepare turns a Drizzle query into a prepared statement that can be executed repeatedly. Put runtime values in named sql.placeholder(...) expressions and pass their values to execute.
query.prepare(statementName?)| Name | Type | Description |
|---|---|---|
values | object | Object whose properties provide values for named placeholders in the prepared query. |
A prepared statement object that can be executed repeatedly.
.prepare(...) after building it.execute method.execute.import { eq, sql } from "drizzle-orm";
const prepared = db
.select()
.from(customers)
.where(eq(customers.id, sql.placeholder("id")))
.prepare("customer_by_id");
const customer = await prepared.execute({ id: 10 });Creates one reusable query and supplies a different customer ID each time it executes.
A frequently executed query has the same SQL shape but different filter values.
A large query is run repeatedly and parsing overhead matters.
A serverless handler can retain objects between invocations.
.prepare do?.prepare creates a prepared statement from a Drizzle query. Drizzle performs SQL concatenation once, allowing the database driver to reuse precompiled SQL on later executions.
Follow-up: How would you pass changing filter values? Use sql.placeholder("name") in the query and provide the corresponding value to execute, such as { name: "%an%" }.
Call .execute() on the prepared statement for each run. The same prepared object can therefore be executed repeatedly instead of rebuilding the query each time.
Follow-up: Why can this help performance? Reusing precompiled SQL avoids repeatedly parsing the query, with the greatest benefit on large SQL statements.
Use sql.placeholder with a unique name inside the query, then pass an object containing that name to execute. For example, sql.placeholder("id") pairs with execute({ id: 10 }).
Follow-up: Can a query have multiple runtime values? Yes; define multiple named placeholders and provide all corresponding properties in the execution object.
sql.placeholderexecuteselectwhereDrizzle ORM