🗄️ Databases

Database

Database

An organized repository of structured data. Divided into relational (RDBMS) and non-relational (NoSQL), and data is efficiently stored, retrieved, modified, and deleted through a DBMS.

📖 Detailed Explanation

A database is a collection of systematically structured data, managed through a DBMS (Database Management System). It provides core functions such as persistent data storage for applications, fast retrieval, concurrency control, and data integrity assurance.

Database Classification

Relational Database (RDBMS)

Table-based (rows/columns), uses SQL queries, requires schema definition, guarantees ACID transactions. Suited for structured data and complex JOIN operations.

PostgreSQL
Open source, scalability
MySQL
Most widely used
Oracle
Enterprise
SQL Server
Microsoft

Non-Relational Database (NoSQL)

Flexible schema, easy horizontal scaling, BASE properties. Suited for large volumes of unstructured data and high write throughput.

MongoDB
Document
Redis
Key-Value (In-Memory)
Cassandra
Wide-Column
Neo4j
Graph

ACID vs BASE

Characteristics ACID (Relational) BASE (NoSQL)
Consistency Strong Consistency Eventual Consistency
Availability Consistency First Availability First
Scaling Vertical Scaling (Scale-up) Horizontal Scaling (Scale-out)
Suitable Cases Finance, order systems Logs, social, IoT

💻 Code Example

PostgreSQL - Table Design and CRUD
-- 테이블 생성 (정규화된 스키마) CREATE TABLE users ( id SERIAL PRIMARY KEY, email VARCHAR(255) UNIQUE NOT NULL, name VARCHAR(100) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE orders ( id SERIAL PRIMARY KEY, user_id INTEGER REFERENCES users(id) ON DELETE CASCADE, total_amount DECIMAL(10, 2) NOT NULL, status VARCHAR(20) DEFAULT 'pending', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); -- 인덱스 생성 CREATE INDEX idx_orders_user_id ON orders(user_id); CREATE INDEX idx_orders_status ON orders(status); -- CRUD 작업 INSERT INTO users (email, name) VALUES ('user@example.com', '홍길동'); SELECT u.name, COUNT(o.id) AS order_count, SUM(o.total_amount) AS total_spent FROM users u LEFT JOIN orders o ON u.id = o.user_id GROUP BY u.id HAVING COUNT(o.id) > 0;
MongoDB - Document-Based Schema and Aggregation
// 컬렉션에 문서 삽입 db.users.insertOne({ email: "user@example.com", name: "홍길동", profile: { age: 30, interests: ["AI", "Database"] }, orders: [ { product: "서버", amount: 1000000, date: new Date() } ], created_at: new Date() }); // 집계 파이프라인 - 사용자별 총 주문 금액 db.users.aggregate([ { $unwind: "$orders" }, { $group: { _id: "$email", total_spent: { $sum: "$orders.amount" }, order_count: { $sum: 1 } }}, { $sort: { total_spent: -1 } }, { $limit: 10 } ]);
Python - ORM Pattern Using SQLAlchemy
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, relationship # 데이터베이스 연결 DATABASE_URL = "postgresql://user:password@localhost:5432/mydb" engine = create_engine(DATABASE_URL) Session = sessionmaker(bind=engine) Base = declarative_base() # 모델 정의 class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) email = Column(String(255), unique=True, nullable=False) name = Column(String(100), nullable=False) orders = relationship("Order", back_populates="user", lazy="selectin") class Order(Base): __tablename__ = 'orders' id = Column(Integer, primary_key=True) user_id = Column(Integer, ForeignKey('users.id')) total_amount = Column(Integer) user = relationship("User", back_populates="orders") # CRUD 작업 session = Session() # Create new_user = User(email="test@example.com", name="테스트") session.add(new_user) session.commit() # Read with relationship (N+1 방지) users = session.query(User).options( selectinload(User.orders) ).filter(User.name.like('%테스트%')).all() # Transaction try: session.begin() user = session.query(User).filter_by(id=1).first() user.name = "수정된 이름" session.commit() except Exception: session.rollback() raise
Redis - Caching and Session Storage
import redis import json r = redis.Redis(host='localhost', port=6379, db=0) # 캐시 패턴: Cache-Aside def get_user(user_id: int): cache_key = f"user:{user_id}" # 1. 캐시 확인 cached = r.get(cache_key) if cached: return json.loads(cached) # 2. DB 조회 (캐시 미스) user = db.query(User).get(user_id) # SQLAlchemy # 3. 캐시 저장 (TTL 1시간) r.setex(cache_key, 3600, json.dumps(user.to_dict())) return user # 세션 저장 r.hset("session:abc123", mapping={ "user_id": "1", "email": "user@example.com", "login_at": "2024-01-01T00:00:00" }) r.expire("session:abc123", 86400) # 24시간 만료

💬 Real-world conversation examples

Junior Developer
"Which DB should we use for this service? PostgreSQL? MongoDB?"
Senior developer
"Start with the data model. If relationships are complex and transactions matter, go with PostgreSQL; if the schema changes often and document-level queries are common, go with MongoDB. Our service is an order-payment system, so ACID is a must — let's go with PostgreSQL."
Backend developer
"The DB response is slow. Where should I start looking?"
DBA
"Run EXPLAIN ANALYZE first. Just because it uses an index doesn't mean it's all fast. You need to check whether it's a Full Table Scan, whether there's an index but it isn't being used, and whether it can be optimized with a covering index."
Architect
"We expect traffic to increase 10x. Can the DB hold up?"
Team Lead
"Add replicas for Read, and put a Redis cache layer in front for hot data. If Write is the bottleneck, we'd need to consider sharding, but before that, let's start with Connection Pool settings and query optimization."

⚠️ Cautions

⚠️ N+1 Query Problem

Beware of the N+1 problem, where an ORM issues an additional query on every loop iteration when retrieving related data! Use Eager Loading (selectinload, joinedload) or the DataLoader pattern.

⚠️ Excessive Index Creation

The more indexes you have, the slower INSERT/UPDATE becomes. Analyze actual query patterns, create only the indexes you need, and carefully decide the column order of composite indexes (higher selectivity first).

⚠️ Connection Pool Exhaustion

Database connections are an expensive resource. Configure the Connection Pool appropriately, and always return the connection after a query. Long-running transactions hold on to connections, so they should be avoided.

🔗 Related Terms

📚 Learn More