Database-specific SQL
A query uses database-specific SQL that is unavailable through Prisma's model query API.
Prisma · Function
$queryRaw executes one parameterized SQL statement and returns its records as an array. Use its tagged-template form, or Prisma.sql, to interpolate values more safely.
Use $queryRaw when a relational-database query must return records that Prisma's model API does not express conveniently. It is invoked as a tagged template, so interpolated values are parameterized and the result is an array of database-record objects.
prisma.$queryRaw<T>(query: TemplateStringsArray | Prisma.Sql, ...values: any[]): PrismaPromise<T>| Name | Type | Description |
|---|---|---|
query | TemplateStringsArray / Prisma.Sql | A tagged template containing one SQL statement, with values interpolated as parameters, or a Prisma.sql helper. |
A promise resolving to an array of database-record objects; the exact field shape depends on the SQL query.
$queryRaw belongs to Prisma Client's relational raw-query API.$queryRaw for record-producing SQL such as SELECT, rather than write-oriented statements.Prisma.sql; a plain runtime string is not accepted by this method.import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
const userId = 1;
const users = await prisma.$queryRaw<Array<{ id: number; email: string }>>`
SELECT id, email
FROM "User"
WHERE id = ${userId}
`;
console.log(users);
await prisma.$disconnect();Runs a parameterized SELECT and receives the matching rows as an array.
A query uses database-specific SQL that is unavailable through Prisma's model query API.
A SELECT needs to return rows from a relational database.
A query must work with fields or expressions that are difficult to represent through generated Prisma queries.
$queryRaw return and when would you use it?$queryRaw is Prisma Client's raw SQL method for returning records from a relational database. It is used as a tagged template, and its result is an array in which each object represents a database record.
Follow-up: How are interpolated values handled? Tagged-template interpolation is converted into prepared-statement parameters, which helps mitigate SQL injection; SQL syntax itself must still be valid for the target database.
The method accepts a template string or the Prisma.sql helper. Interpolated variables are escaped and sent through prepared statements, rather than concatenated into the SQL text.
Follow-up: Can a variable represent a table name? Not for PostgreSQL with $queryRaw; dynamic identifiers are not supported by this method.
Each call can execute only one query. A string containing multiple statements, such as select 1; select 2;, will not work.
Follow-up: What should be done when several statements are required? Issue separate calls, while considering transaction requirements and the database's behavior between them.
$executeRaw$queryRawUnsafe$executeRawUnsafePrisma.sqlTypedSQL