Use advanced SQL capabilities
A query requires database-specific syntax or advanced SQL features unavailable in Prisma Client's model API.
Prisma · Const
TypedSQL lets you write SQL in .sql files and use generated, fully typed functions from Prisma Client. It combines SQL flexibility with typed inputs and outputs.
TypedSQL lets you author SQL in .sql files and use generated TypeScript functions with typed inputs and outputs. Enable the preview feature, generate Prisma Client with the --sql flag against a reachable database, then execute the generated function with $queryRawTyped.
prisma generate --sql
await prisma.$queryRawTyped(generatedQuery(...args))| Name | Type | Description |
|---|---|---|
query arguments | inferred typed parameters | Arguments defined by placeholders in the SQL query; generated with inferred types. |
A generated, typed query result inferred from the SQL and database schema.
// prisma/sql/getUsers.sql
SELECT id, email FROM User WHERE email = $1;
// src/main.ts
import { PrismaClient } from '@prisma/client';
import { getUsers } from './generated/prisma/sql';
const prisma = new PrismaClient();
const users = await prisma.$queryRawTyped(getUsers('ada@example.com'));
console.log(users);This example places SQL in a dedicated file, generates its typed function, and executes that function through Prisma Client.
A query requires database-specific syntax or advanced SQL features unavailable in Prisma Client's model API.
A team wants SQL files with editor support while retaining compile-time input and result types.
Existing SQL workflows need to run through Prisma Client and its surrounding ecosystem.
TypedSQL stores SQL in .sql files, then Prisma generates TypeScript functions and types for those queries. The generated functions are executed through Prisma Client with $queryRawTyped.
Follow-up: Why does generation need a database connection? Prisma connects to the database to infer the input and output types of each SQL query.
Add typedSql to the generator's previewFeatures, place queries in the Prisma SQL directory, and run prisma generate --sql. The generated query function can then be imported into TypeScript.
Follow-up: What should be checked if the generated function is missing? Verify the preview flag, SQL location and filename, and that generation was run with --sql.
TypedSQL keeps SQL's expressive power while providing typed arguments and results in TypeScript. It also supports editor features such as SQL syntax highlighting, error checking, and autocompletion.
Follow-up: When is TypedSQL preferable to Prisma Client's model API? Use it when a query needs SQL-specific features or control that the higher-level Client API cannot express.
Prisma Client$queryRawTypedprisma generate --sqltypedSqlPrisma SchemaPrisma Migrate