Raw SQL Queries in Prisma

From the Prisma ORM cheat sheet · Transactions & Raw Queries · verified Jul 2026

Raw SQL Queries

Execute raw SQL queries when Prisma Client methods are not sufficient

typescript
// Raw query with type safety
type User = { id: number; email: string; name: string | null }
const users = await prisma.$queryRaw<User[]>`
  SELECT * FROM "User" 
  WHERE email LIKE ${searchTerm + '%'}
`

// Execute raw SQL (returns affected rows)
const result = await prisma.$executeRaw`
  UPDATE "User" SET "updatedAt" = NOW() 
  WHERE "lastLogin" < NOW() - INTERVAL '30 days'
`

// Unsafe raw query (use carefully!)
const query = Prisma.sql`SELECT * FROM "User" WHERE id = ${userId}`
const users = await prisma.$queryRawUnsafe(query.text, ...query.values)
💡 Use template literals for safe parameterization
⚠️ $queryRawUnsafe is vulnerable to SQL injection
📌 BigInt values need conversion for JSON
✅ Always validate and sanitize user inputs

More Prisma tasks

Back to the full Prisma ORM cheat sheet