Execute raw SQL with Prisma for complex queries
✓Works with OpenClaudeYou are a database developer using Prisma ORM. The user wants to execute raw SQL queries directly within Prisma for complex operations that can't be built with the standard query builder.
What to check first
- Verify
@prisma/clientis installed:npm list @prisma/client - Check your
.envfile contains a validDATABASE_URLconnection string - Confirm your Prisma schema is synced with your database:
npx prisma db pushornpx prisma migrate dev
Steps
- Import
PrismaClientand instantiate it in your application file - Use
prisma.$queryRawfor SELECT queries that return data rows - Use
prisma.$executeRawfor INSERT, UPDATE, DELETE queries that modify data - Pass SQL as a template literal with backticks to enable parameter binding
- Use
Prisma.sqlfor proper SQL escaping and type safety in dynamic queries - Handle the returned data:
$queryRawreturns an array of objects matching your query shape - Catch
PrismaClientKnownRequestErrorfor database-specific errors - Test parameter binding by logging the SQL before executing in production
Code
import { PrismaClient, Prisma } from '@prisma/client';
const prisma = new PrismaClient();
// SELECT query with $queryRaw — returns typed array of results
async function getComplexUserReport(minAge: number, countryCode: string) {
const results = await prisma.$queryRaw<
Array<{ id: number; name: string; totalOrders: bigint }>
>`
SELECT
u.id,
u.name,
COUNT(o.id) as "totalOrders"
FROM "User" u
LEFT JOIN "Order" o ON u.id = o.userId
WHERE u.age > ${minAge}
AND u.country = ${countryCode}
GROUP BY u.id, u.name
HAVING COUNT(o.id) > 0
ORDER BY "totalOrders" DESC
`;
return results;
}
// UPDATE query with $executeRaw — returns number of rows affected
async function bulkUpdateUserStatus(userIds: number[], newStatus: string) {
const rowsAffected = await prisma.$executeRaw`
UPDATE "User"
SET status = ${newStatus}, "updatedAt" = NOW()
WHERE id IN (${Prisma.join(userIds)})
`;
return rowsAffected;
}
// Dynamic SQL with Prisma.sql for safe interpolation
async function dynamicSearch(tableName: string, searchTerm: string) {
const identifier = Prisma.raw(`"${tableName}"`);
const results = await prisma.$queryRaw`
SELECT * FROM ${identifier}
WHERE "name" ILIKE ${
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Database Skills
Other Claude Code skills in the same category — free to download.
Migration Generator
Generate database migration files
Query Optimizer
Analyze and optimize slow database queries
Schema Designer
Design database schema from requirements
Seed Data Generator
Generate database seed/sample data
Index Advisor
Suggest database indexes based on query patterns
ORM Model Generator
Generate ORM models from database schema
SQL to ORM
Convert raw SQL queries to ORM syntax
Database Backup Script
Create database backup and restore scripts
Want a Database skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.