You can send raw SQL queries to your database using the raw function that's exposed by your PrismaClient instance. It returns the query results as plain old JavaScript objects:

const result = await prisma.raw('SELECT * FROM User;')

result is an array where each object corresponds to a retrieved database record:

{ id: 1, email: 'sarah@prisma.io', name: 'Sarah' },
{ id: 2, email: 'alice@prisma.io', name: 'Alice' },

Tagged templates

The raw method is implemented as a tagged template. Therefore, you can also call raw as follows:

const result = await prisma.raw`SELECT * FROM User;`

Setting variables

To include variables in your SQL query, you can use JavaScript string interpolation with template literals:

const userId = 42
const result = await prisma.raw`SELECT * FROM User WHERE id = ${userId};`

Typing raw results

The raw function has the following function signature:

raw<T = any>(query: string | TemplateStringsArray): Promise<T>;

The return type of raw is a Promise for the generic type parameter T. This means you can type the result manually by providing T when you invoke raw. If you don't provide any type, the return type of raw defaults to any.

// import the generated `User` type from the `@prisma/client` module
import { User } from '@prisma/client'
const result = await prisma.raw<User[]>('SELECT * FROM User;')
// result is of type: `User[]`

Now, result is statically typed to the generated User type (or rather an array thereof) from Prisma Client.

If you're selecting only specific fields of the model or want to include relations, read the documentation about leveraging Prisma Client's generated types if you want to ensure that the query results are properly typed.

Note that calls to SELECT always return arrays of type T, but other SQL operations (like INSERT or UPDATE) might return single objects.

Edit this page on Github