Execute custom updates or deletes
A write operation needs SQL that Prisma Client's model API does not express conveniently.
Prisma · Module
$executeRawUnsafe executes a raw SQL string or template string and resolves to the number of affected rows. Its flexibility comes with a significant SQL-injection risk, especially when SQL text includes untrusted input.
$executeRawUnsafe sends a raw SQL string or template string through Prisma Client for a write operation. It returns the number of affected rows rather than records, and it can also receive separately supplied values for database-specific parameter placeholders.
$executeRawUnsafe<T = unknown>(query: string, ...values: any[]): PrismaPromise<number>;| Name | Type | Description |
|---|---|---|
query | string | Raw SQL text or a template string to execute. |
values | any[] | Optional values supplied to the raw statement; placeholder syntax depends on the database. |
PrismaPromise<number> resolving to the number of rows affected.
PrismaPromise<number>.import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
async function main() {
const active = true;
const emailValidated = true;
const updated = await prisma.$executeRawUnsafe(
`UPDATE User SET active = ${active} WHERE emailValidated = ${emailValidated}`,
);
console.log(updated);
}
main().finally(() => prisma.$disconnect());Updates matching rows and logs the number affected.
A write operation needs SQL that Prisma Client's model API does not express conveniently.
A statement must use database-specific SQL syntax and should report its write impact.
The application has a controlled SQL statement and needs to pass standard database parameters.
$executeRawUnsafe return?It accepts a raw SQL string or template string and returns a Prisma promise resolving to the number of affected rows. It is intended for operations such as updates or deletes rather than returning records.
Follow-up: How would you reduce injection risk? Prefer $executeRaw with a tagged template and avoid interpolating untrusted values into SQL.
The method is called unsafe because raw SQL can be assembled flexibly, including from values that may be controlled by users. If those values are inserted into the SQL text, attackers may be able to inject SQL.
Follow-up: What should be used when the operation must return rows? Use $queryRaw or $queryRawUnsafe, depending on how the query is parameterized.
Its signature is $executeRawUnsafe<T = unknown>(query: string, ...values: any[]): PrismaPromise<number>. The first argument is the SQL text, optional subsequent values can supply parameters, and the resolved number represents affected rows.
Follow-up: Which placeholder syntax is used? It depends on the database, such as ? for MySQL or $1, $2, and so on for PostgreSQL.
$executeRaw$queryRaw$queryRawUnsafeTypedSQL