Prisma logoPrisma INTERMEDIATE

Prisma ORM Complete Guide

Comprehensive guide to Prisma ORM including schema definition, relations, queries, migrations, and database management

15 min read
prismaormdatabasepostgresqlmysqlsqlitemigrationsschema

Prisma Schema & Models

Schema Definition & Models

Define your database schema using Prisma Schema Language with models, fields, and attributes

typescript
💡 Prisma schema is the single source of truth for your database
⚡ Run npx prisma generate after schema changes
📌 Use npx prisma format to auto-format schema
✅ VSCode extension provides syntax highlighting

Prisma Relations & Associations

Define relationships between models including one-to-one, one-to-many, and many-to-many

typescript
💡 Relations are defined on both sides of the relationship
⚠️ Use @relation to disambiguate multiple relations
📌 Cascade deletes with onDelete: Cascade
✅ Self-relations require explicit relation names

Prisma Client Queries

CRUD Operations

Create, read, update, and delete records using Prisma Client methods

typescript
💡 All operations return Promises
⚡ Use select to fetch only needed fields
📌 Include relations with include or select
✅ findUnique requires unique fields

Advanced Querying & Filtering

Complex queries with filtering, sorting, pagination, and aggregations

typescript
💡 Combine multiple filters with AND, OR, NOT
⚡ Use cursor-based pagination for large datasets
📌 Aggregate functions: count, sum, avg, min, max
✅ Use distinct to remove duplicates

Prisma Migrations & Database Management

Database Migrations

Version control your database schema changes with Prisma Migrate

bash
💡 Always review migration SQL before applying
⚠️ Don't edit migration files after applying
📌 Use --create-only to preview migrations
✅ Reset dev DB with npx prisma migrate reset

Database Configuration & Management

Configure database connections, manage schema, and handle multiple environments

typescript
💡 Use DATABASE_URL environment variable
⚠️ Never commit .env files with credentials
📌 Shadow database required for migrations
✅ Use connection pooling in production

Transactions & Raw Queries

Database Transactions

Ensure data consistency with interactive and sequential transactions

typescript
💡 Transactions auto-rollback on any error
⚠️ Keep transactions short to avoid locks
📌 Use interactive transactions for complex logic
✅ Set appropriate timeout and isolation levels

Raw SQL Queries

Execute raw SQL queries when Prisma Client methods are not sufficient

typescript
💡 Use template literals for safe parameterization
⚠️ $queryRawUnsafe is vulnerable to SQL injection
📌 BigInt values need conversion for JSON
✅ Always validate and sanitize user inputs

Seeding & Development

Database Seeding

Populate your database with initial or test data for development

typescript
💡 Add seed script to package.json prisma config
⚡ Use createMany for bulk inserts
📌 Clean data before seeding to ensure consistency
✅ Use faker for realistic test data

Error Handling & Optimization

Error Handling

Handle Prisma-specific errors and implement proper error recovery

typescript
💡 Check error.code for specific error types
⚠️ P2002 includes constraint name in meta.target
📌 Implement retry logic for connection errors
✅ Log errors but don't expose internals to users

Query Optimization

Optimize database queries for better performance and efficiency

typescript
💡 Use select over include for better performance
⚡ Add database indexes for frequently queried fields
📌 Use cursor pagination for large datasets
✅ Monitor query performance with Prisma metrics