Isaac.

Prisma ORM Getting Started

Build type-safe applications with Prisma ORM.

By EMEPublished: February 20, 2025
prismaormtypescriptdatabasetype-safe

A Simple Analogy

Prisma is like a GPS for your database. It knows the routes (schema) and gets you where you need to go (queries).


Why Prisma?

  • Type-safe: Full TypeScript support
  • Auto-complete: IDE suggestions work great
  • Migrations: Version control for schema
  • Intuitive: Easy to learn and use
  • Multi-database: Works with many databases

Installation

npm install @prisma/client
npm install -D prisma
npx prisma init

Schema Definition

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
  posts Post[]
}

model Post {
  id      Int     @id @default(autoincrement())
  title   String
  content String?
  author  User    @relation(fields: [authorId], references: [id])
  authorId Int
}

Basic Queries

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

// Create
const user = await prisma.user.create({
  data: {
    email: 'alice@example.com',
    name: 'Alice'
  }
});

// Read
const users = await prisma.user.findMany();
const user = await prisma.user.findUnique({
  where: { email: 'alice@example.com' }
});

// Update
const updated = await prisma.user.update({
  where: { id: 1 },
  data: { name: 'Alice Updated' }
});

// Delete
await prisma.user.delete({ where: { id: 1 } });

Relationships

// Create with relation
const user = await prisma.user.create({
  data: {
    email: 'bob@example.com',
    posts: {
      create: [
        { title: 'First Post' },
        { title: 'Second Post' }
      ]
    }
  }
});

// Include related data
const userWithPosts = await prisma.user.findUnique({
  where: { id: 1 },
  include: { posts: true }
});

Best Practices

  1. Type safety: Leverage TypeScript
  2. Migrations: Use Prisma migrate
  3. Seeding: Define seed data
  4. Error handling: Catch Prisma errors
  5. Connection pooling: Use via datasource

Related Concepts

  • Drizzle ORM
  • TypeORM
  • Sequelize
  • Raw SQL

Summary

Prisma provides type-safe database access with intuitive queries and automatic migrations.