🗄️ Databases

CRUD

Create, Read, Update, Delete

Refers to the four basic data operations (Create, Read, Update, Delete). Most applications and REST APIs are designed around the CRUD pattern, which maps directly to a database's INSERT, SELECT, UPDATE, and DELETE.

📖 Detailed Explanation

Create: Creates new data. It corresponds to INSERT in SQL and the POST method in HTTP. Typical examples are user sign-up, writing a post, and creating an order.

Read: Retrieves existing data. It corresponds to SELECT in SQL and the GET method in HTTP. It is divided into single retrieval (getById) and list retrieval (getAll, search, filtering).

Update: Changes existing data. It corresponds to UPDATE in SQL and to PUT (full replacement) or PATCH (partial update) in HTTP. Examples include editing a profile and changing product information.

Delete: Removes data. It corresponds to DELETE in SQL and the DELETE method in HTTP. It is divided into actual deletion (Hard Delete) and logical deletion (Soft Delete: is_deleted flag).

Mapping CRUD to REST API: This is the foundation of RESTful API design. CRUD is expressed by combining HTTP methods with a resource URL (e.g., /users). GET /users (list), GET /users/:id (detail), POST /users (create), PUT /users/:id (update), DELETE /users/:id (delete).

💻 Code Example

# CRUD API 예제 - Python FastAPI + SQLAlchemy
from fastapi import FastAPI, HTTPException, Depends
from sqlalchemy import create_engine, Column, Integer, String, Boolean, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session
from pydantic import BaseModel, EmailStr
from datetime import datetime
from typing import List, Optional

# 데이터베이스 설정
DATABASE_URL = "postgresql://user:pass@localhost/mydb"
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(bind=engine)
Base = declarative_base()


# 모델 정의
class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    email = Column(String(255), unique=True, nullable=False)
    username = Column(String(100), nullable=False)
    is_active = Column(Boolean, default=True)
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, onupdate=datetime.utcnow)


# Pydantic 스키마
class UserCreate(BaseModel):
    email: EmailStr
    username: str

class UserUpdate(BaseModel):
    email: Optional[EmailStr] = None
    username: Optional[str] = None
    is_active: Optional[bool] = None

class UserResponse(BaseModel):
    id: int
    email: str
    username: str
    is_active: bool
    created_at: datetime

    class Config:
        from_attributes = True


# FastAPI 앱
app = FastAPI()


def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


# ==============================================
# CREATE - 새 사용자 생성
# ==============================================
@app.post("/users", response_model=UserResponse, status_code=201)
def create_user(user: UserCreate, db: Session = Depends(get_db)):
    """
    Create: 새로운 리소스 생성
    - HTTP Method: POST
    - SQL: INSERT INTO users (email, username) VALUES (...)
    """
    # 중복 체크
    existing = db.query(User).filter(User.email == user.email).first()
    if existing:
        raise HTTPException(status_code=400, detail="Email already registered")

    db_user = User(email=user.email, username=user.username)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user


# ==============================================
# READ - 사용자 조회
# ==============================================
@app.get("/users", response_model=List[UserResponse])
def get_users(
    skip: int = 0,
    limit: int = 100,
    is_active: Optional[bool] = None,
    db: Session = Depends(get_db)
):
    """
    Read (List): 목록 조회 + 페이지네이션 + 필터링
    - HTTP Method: GET
    - SQL: SELECT * FROM users WHERE ... LIMIT ... OFFSET ...
    """
    query = db.query(User)

    if is_active is not None:
        query = query.filter(User.is_active == is_active)

    return query.offset(skip).limit(limit).all()


@app.get("/users/{user_id}", response_model=UserResponse)
def get_user(user_id: int, db: Session = Depends(get_db)):
    """
    Read (Detail): 단일 리소스 조회
    - HTTP Method: GET
    - SQL: SELECT * FROM users WHERE id = ?
    """
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return user


# ==============================================
# UPDATE - 사용자 정보 수정
# ==============================================
@app.put("/users/{user_id}", response_model=UserResponse)
def update_user(user_id: int, user_update: UserUpdate, db: Session = Depends(get_db)):
    """
    Update: 리소스 수정
    - HTTP Method: PUT (전체 교체) / PATCH (부분 수정)
    - SQL: UPDATE users SET ... WHERE id = ?
    """
    db_user = db.query(User).filter(User.id == user_id).first()
    if not db_user:
        raise HTTPException(status_code=404, detail="User not found")

    # None이 아닌 필드만 업데이트
    update_data = user_update.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(db_user, field, value)

    db.commit()
    db.refresh(db_user)
    return db_user


# ==============================================
# DELETE - 사용자 삭제
# ==============================================
@app.delete("/users/{user_id}", status_code=204)
def delete_user(user_id: int, db: Session = Depends(get_db)):
    """
    Delete: 리소스 삭제 (Hard Delete)
    - HTTP Method: DELETE
    - SQL: DELETE FROM users WHERE id = ?
    """
    db_user = db.query(User).filter(User.id == user_id).first()
    if not db_user:
        raise HTTPException(status_code=404, detail="User not found")

    db.delete(db_user)
    db.commit()
    return None  # 204 No Content


# Soft Delete (논리적 삭제) 버전
@app.delete("/users/{user_id}/soft")
def soft_delete_user(user_id: int, db: Session = Depends(get_db)):
    """
    Soft Delete: 실제 삭제하지 않고 비활성화
    - is_active = False 또는 deleted_at 타임스탬프 설정
    - 데이터 복구 가능, 감사 추적 용이
    """
    db_user = db.query(User).filter(User.id == user_id).first()
    if not db_user:
        raise HTTPException(status_code=404, detail="User not found")

    db_user.is_active = False
    db.commit()
    return {"message": "User deactivated"}
// CRUD API 예제 - Node.js Express + Prisma
const express = require('express');
const { PrismaClient } = require('@prisma/client');

const app = express();
const prisma = new PrismaClient();

app.use(express.json());

// ==============================================
// CREATE - 새 사용자 생성
// ==============================================
app.post('/users', async (req, res) => {
    /**
     * Create: POST /users
     * SQL: INSERT INTO users (email, username) VALUES ($1, $2)
     */
    try {
        const { email, username } = req.body;

        // 유효성 검사
        if (!email || !username) {
            return res.status(400).json({
                error: 'email and username are required'
            });
        }

        const user = await prisma.user.create({
            data: { email, username }
        });

        res.status(201).json(user);

    } catch (error) {
        if (error.code === 'P2002') {  // Unique constraint violation
            return res.status(400).json({ error: 'Email already exists' });
        }
        res.status(500).json({ error: error.message });
    }
});


// ==============================================
// READ - 사용자 목록 조회
// ==============================================
app.get('/users', async (req, res) => {
    /**
     * Read (List): GET /users?page=1&limit=10&search=john
     * SQL: SELECT * FROM users WHERE ... LIMIT ... OFFSET ...
     */
    try {
        const {
            page = 1,
            limit = 10,
            search,
            isActive
        } = req.query;

        const skip = (parseInt(page) - 1) * parseInt(limit);
        const take = parseInt(limit);

        // 필터 조건 구성
        const where = {};
        if (search) {
            where.OR = [
                { email: { contains: search, mode: 'insensitive' } },
                { username: { contains: search, mode: 'insensitive' } }
            ];
        }
        if (isActive !== undefined) {
            where.isActive = isActive === 'true';
        }

        // 병렬로 데이터와 총 개수 조회
        const [users, total] = await Promise.all([
            prisma.user.findMany({
                where,
                skip,
                take,
                orderBy: { createdAt: 'desc' }
            }),
            prisma.user.count({ where })
        ]);

        res.json({
            data: users,
            pagination: {
                page: parseInt(page),
                limit: parseInt(limit),
                total,
                totalPages: Math.ceil(total / take)
            }
        });

    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});


// ==============================================
// READ - 단일 사용자 조회
// ==============================================
app.get('/users/:id', async (req, res) => {
    /**
     * Read (Detail): GET /users/:id
     * SQL: SELECT * FROM users WHERE id = $1
     */
    try {
        const { id } = req.params;

        const user = await prisma.user.findUnique({
            where: { id: parseInt(id) },
            include: {
                posts: true,     // 관계 데이터 포함
                profile: true
            }
        });

        if (!user) {
            return res.status(404).json({ error: 'User not found' });
        }

        res.json(user);

    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});


// ==============================================
// UPDATE - 사용자 정보 수정
// ==============================================
app.put('/users/:id', async (req, res) => {
    /**
     * Update (Full): PUT /users/:id
     * SQL: UPDATE users SET email=$1, username=$2 WHERE id=$3
     */
    try {
        const { id } = req.params;
        const { email, username, isActive } = req.body;

        const user = await prisma.user.update({
            where: { id: parseInt(id) },
            data: { email, username, isActive }
        });

        res.json(user);

    } catch (error) {
        if (error.code === 'P2025') {  // Record not found
            return res.status(404).json({ error: 'User not found' });
        }
        res.status(500).json({ error: error.message });
    }
});

// PATCH - 부분 수정
app.patch('/users/:id', async (req, res) => {
    /**
     * Update (Partial): PATCH /users/:id
     * 전달된 필드만 업데이트
     */
    try {
        const { id } = req.params;

        // undefined 필드 제외
        const data = Object.fromEntries(
            Object.entries(req.body).filter(([_, v]) => v !== undefined)
        );

        const user = await prisma.user.update({
            where: { id: parseInt(id) },
            data
        });

        res.json(user);

    } catch (error) {
        if (error.code === 'P2025') {
            return res.status(404).json({ error: 'User not found' });
        }
        res.status(500).json({ error: error.message });
    }
});


// ==============================================
// DELETE - 사용자 삭제
// ==============================================
app.delete('/users/:id', async (req, res) => {
    /**
     * Delete (Hard): DELETE /users/:id
     * SQL: DELETE FROM users WHERE id = $1
     */
    try {
        const { id } = req.params;

        await prisma.user.delete({
            where: { id: parseInt(id) }
        });

        res.status(204).send();  // No Content

    } catch (error) {
        if (error.code === 'P2025') {
            return res.status(404).json({ error: 'User not found' });
        }
        res.status(500).json({ error: error.message });
    }
});

// Soft Delete
app.delete('/users/:id/soft', async (req, res) => {
    try {
        const { id } = req.params;

        const user = await prisma.user.update({
            where: { id: parseInt(id) },
            data: {
                isActive: false,
                deletedAt: new Date()
            }
        });

        res.json({ message: 'User soft deleted', user });

    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});


app.listen(3000, () => console.log('Server running on port 3000'));
-- ============================================
-- CRUD SQL 예제 (PostgreSQL)
-- ============================================

-- 테이블 생성
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    email VARCHAR(255) UNIQUE NOT NULL,
    username VARCHAR(100) NOT NULL,
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    deleted_at TIMESTAMP  -- Soft Delete용
);


-- ============================================
-- CREATE (INSERT)
-- ============================================

-- 단일 레코드 삽입
INSERT INTO users (email, username)
VALUES ('john@example.com', 'john_doe')
RETURNING *;  -- 삽입된 레코드 반환 (PostgreSQL)

-- 다중 레코드 삽입
INSERT INTO users (email, username) VALUES
    ('alice@example.com', 'alice'),
    ('bob@example.com', 'bob'),
    ('charlie@example.com', 'charlie');

-- UPSERT (있으면 업데이트, 없으면 삽입)
INSERT INTO users (email, username)
VALUES ('john@example.com', 'john_updated')
ON CONFLICT (email) DO UPDATE SET
    username = EXCLUDED.username,
    updated_at = CURRENT_TIMESTAMP;


-- ============================================
-- READ (SELECT)
-- ============================================

-- 전체 조회
SELECT * FROM users;

-- 조건 조회
SELECT * FROM users WHERE is_active = TRUE;

-- 단일 레코드 조회
SELECT * FROM users WHERE id = 1;
SELECT * FROM users WHERE email = 'john@example.com';

-- 검색 (부분 일치)
SELECT * FROM users
WHERE username ILIKE '%john%'  -- 대소문자 무시 (PostgreSQL)
   OR email ILIKE '%john%';

-- 페이지네이션
SELECT * FROM users
ORDER BY created_at DESC
LIMIT 10 OFFSET 0;  -- 1페이지 (0~9)

SELECT * FROM users
ORDER BY created_at DESC
LIMIT 10 OFFSET 10;  -- 2페이지 (10~19)

-- 커서 기반 페이지네이션 (대용량에 효율적)
SELECT * FROM users
WHERE id > 100  -- 마지막 조회 ID
ORDER BY id ASC
LIMIT 10;

-- 집계와 함께 조회
SELECT
    COUNT(*) as total,
    COUNT(*) FILTER (WHERE is_active) as active_count
FROM users;


-- ============================================
-- UPDATE
-- ============================================

-- 단일 필드 업데이트
UPDATE users
SET username = 'john_updated'
WHERE id = 1
RETURNING *;

-- 다중 필드 업데이트
UPDATE users SET
    username = 'john_updated',
    is_active = FALSE,
    updated_at = CURRENT_TIMESTAMP
WHERE id = 1;

-- 조건부 업데이트
UPDATE users SET
    is_active = FALSE
WHERE created_at < NOW() - INTERVAL '1 year'
  AND is_active = TRUE;

-- CASE를 이용한 조건부 값 설정
UPDATE users SET
    is_active = CASE
        WHEN last_login_at < NOW() - INTERVAL '6 months' THEN FALSE
        ELSE is_active
    END;


-- ============================================
-- DELETE
-- ============================================

-- Hard Delete (물리적 삭제)
DELETE FROM users WHERE id = 1;

-- 조건부 삭제
DELETE FROM users
WHERE is_active = FALSE
  AND created_at < NOW() - INTERVAL '1 year';

-- 관련 데이터도 함께 삭제 (CASCADE 설정 필요)
DELETE FROM users WHERE id = 1;  -- posts, profiles도 삭제됨

-- Soft Delete (논리적 삭제)
UPDATE users SET
    is_active = FALSE,
    deleted_at = CURRENT_TIMESTAMP
WHERE id = 1;

-- Soft Delete된 데이터 제외하고 조회
SELECT * FROM users
WHERE deleted_at IS NULL;

-- Soft Delete 복구
UPDATE users SET
    is_active = TRUE,
    deleted_at = NULL
WHERE id = 1;


-- ============================================
-- CRUD 매핑 요약
-- ============================================
-- | CRUD   | SQL      | HTTP   | 설명           |
-- |--------|----------|--------|----------------|
-- | Create | INSERT   | POST   | 새 리소스 생성   |
-- | Read   | SELECT   | GET    | 리소스 조회      |
-- | Update | UPDATE   | PUT    | 전체 리소스 교체  |
-- | Update | UPDATE   | PATCH  | 부분 리소스 수정  |
-- | Delete | DELETE   | DELETE | 리소스 삭제      |

🗣️ Say It Like This in Practice

💬 In an API Design Meeting
"Let's define the CRUD API for this resource first. Create with POST /products, read with GET /products/:id, full update with PUT, partial update with PATCH, and delete with DELETE. We just need to follow RESTful conventions."
💬 In a Data Deletion Policy Discussion
"Let's go with Soft Delete for user deletion. With the is_deleted flag, we can restore data later, and audit log tracing is easy too. I think the actual physical deletion should be handled by a batch job after 90 days."
💬 In a Performance Optimization Review
"Since the Read ratio is over 90%, we should focus on read optimization. Let's add appropriate indexes to SELECT queries and add a caching layer for frequently queried data. Write can be handled asynchronously."

⚠️ Cautions & Best Practices

❌
Changing Data with GET Requests

GET is for retrieval only. You must not delete with GET, as in GET /users/1/delete. Crawlers or prefetching can trigger unintended deletions.

❌
UPDATE/DELETE Without WHERE

Running UPDATE or DELETE without a WHERE clause changes/deletes all data. Always check the condition clause, and wrap it in a transaction in production.

❌
The N+1 Problem

When retrieving a list, querying each item's related data with individual queries drastically degrades performance. Use JOIN or Eager Loading.

✅
CRUD Best Practices

Ensure idempotency (PUT and DELETE give the same result even when called multiple times), return appropriate HTTP status codes, pagination is required, consider Soft Delete, and validate input.

🔗 Related Terms

📚 Learn More