🗄️ Databases

Database

Database

A system that stores, manages, and retrieves structured data in an organized way. Through a DBMS (Database Management System), it handles creating, reading, updating, and deleting data (CRUD), as well as concurrency control, security, and backup/recovery.

📖 Detailed Explanation

A database is a system that systematically manages data, an organization's core asset. Unlike a file system, it minimizes data redundancy, guarantees integrity, and controls concurrent access. It is the foundation of every modern application.

An RDBMS (relational database) stores data in tables and uses SQL. PostgreSQL, MySQL, Oracle, and SQL Server are representative examples. By guaranteeing ACID transactions, it is well suited to data where consistency is important, such as finance and orders.

NoSQL refers to non-relational databases, whose strengths are flexible schemas and horizontal scaling. There are various types, such as document (MongoDB), key-value (Redis), column-family (Cassandra), and graph (Neo4j). It is suitable when large volumes of data, rapid change, and flexible structures are needed.

NewSQL is a database that combines the ACID guarantees of an RDBMS with the scalability of NoSQL. Examples include CockroachDB, YugabyteDB, and Google Spanner, and it is used when strong consistency is needed even in a distributed environment.

Considerations when choosing a database: you should comprehensively review the data structure (structured/unstructured), the required level of consistency, the scaling method (vertical/horizontal), query patterns (complex joins/simple lookups), whether transactions are needed, the team's technical proficiency, and so on.

💻 Code Example

# PostgreSQL 연결 및 CRUD - Python + psycopg2
import psycopg2
from contextlib import contextmanager

class DatabaseService:
    """PostgreSQL 데이터베이스 서비스"""

    def __init__(self, connection_string: str):
        self.conn_string = connection_string

    @contextmanager
    def get_connection(self):
        """연결 관리 (Context Manager)"""
        conn = psycopg2.connect(self.conn_string)
        try:
            yield conn
            conn.commit()
        except Exception as e:
            conn.rollback()
            raise e
        finally:
            conn.close()

    def create_user(self, name: str, email: str) -> int:
        """사용자 생성 (Create)"""
        with self.get_connection() as conn:
            with conn.cursor() as cur:
                cur.execute(
                    """INSERT INTO users (name, email, created_at)
                       VALUES (%s, %s, NOW())
                       RETURNING id""",
                    (name, email)
                )
                return cur.fetchone()[0]

    def get_user(self, user_id: int) -> dict:
        """사용자 조회 (Read)"""
        with self.get_connection() as conn:
            with conn.cursor() as cur:
                cur.execute(
                    "SELECT id, name, email FROM users WHERE id = %s",
                    (user_id,)
                )
                row = cur.fetchone()
                if row:
                    return {"id": row[0], "name": row[1], "email": row[2]}
                return None

    def update_user(self, user_id: int, name: str) -> bool:
        """사용자 수정 (Update)"""
        with self.get_connection() as conn:
            with conn.cursor() as cur:
                cur.execute(
                    "UPDATE users SET name = %s WHERE id = %s",
                    (name, user_id)
                )
                return cur.rowcount > 0

    def delete_user(self, user_id: int) -> bool:
        """사용자 삭제 (Delete)"""
        with self.get_connection() as conn:
            with conn.cursor() as cur:
                cur.execute("DELETE FROM users WHERE id = %s", (user_id,))
                return cur.rowcount > 0


# 사용 예시
db = DatabaseService("postgresql://admin:secret@localhost/myapp")

# CRUD 작업
user_id = db.create_user("홍길동", "hong@example.com")
user = db.get_user(user_id)
print(f"생성된 사용자: {user}")
// MongoDB 연결 및 CRUD - Node.js + Mongoose
const mongoose = require('mongoose');

// 스키마 정의
const userSchema = new mongoose.Schema({
    name: { type: String, required: true },
    email: { type: String, required: true, unique: true },
    createdAt: { type: Date, default: Date.now }
});

const User = mongoose.model('User', userSchema);

class DatabaseService {
    /**
     * MongoDB 연결
     */
    async connect(connectionString) {
        await mongoose.connect(connectionString);
        console.log('MongoDB 연결 성공');
    }

    /**
     * 사용자 생성 (Create)
     */
    async createUser(name, email) {
        const user = new User({ name, email });
        await user.save();
        return user;
    }

    /**
     * 사용자 조회 (Read)
     */
    async getUser(userId) {
        return await User.findById(userId);
    }

    /**
     * 조건 검색
     */
    async findUsers(query) {
        return await User.find(query).sort({ createdAt: -1 });
    }

    /**
     * 사용자 수정 (Update)
     */
    async updateUser(userId, updates) {
        return await User.findByIdAndUpdate(
            userId,
            updates,
            { new: true }  // 수정된 문서 반환
        );
    }

    /**
     * 사용자 삭제 (Delete)
     */
    async deleteUser(userId) {
        const result = await User.findByIdAndDelete(userId);
        return result !== null;
    }
}

// 사용 예시
const db = new DatabaseService();
await db.connect('mongodb://localhost:27017/myapp');

// CRUD 작업
const user = await db.createUser('홍길동', 'hong@example.com');
console.log(`생성된 사용자: ${user.name}`);
-- ============================================
-- 데이터베이스 및 테이블 생성
-- ============================================
CREATE DATABASE myapp;

CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(255) UNIQUE NOT NULL,
    status VARCHAR(20) DEFAULT 'active',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_users_status ON users(status);


-- ============================================
-- CRUD 기본 작업
-- ============================================

-- Create (생성)
INSERT INTO users (name, email)
VALUES ('홍길동', 'hong@example.com');

-- Read (조회)
SELECT * FROM users WHERE status = 'active';

-- Update (수정)
UPDATE users
SET name = '김철수'
WHERE id = 1;

-- Delete (삭제)
DELETE FROM users WHERE id = 1;


-- ============================================
-- 고급 쿼리
-- ============================================

-- 조인 (JOIN)
SELECT u.name, o.order_id, o.total
FROM users u
JOIN orders o ON u.id = o.user_id
WHERE o.created_at > '2024-01-01';

-- 집계 함수
SELECT status, COUNT(*) as user_count
FROM users
GROUP BY status
HAVING COUNT(*) > 10;

-- 서브쿼리
SELECT name, email
FROM users
WHERE id IN (
    SELECT user_id FROM orders
    WHERE total > 100000
);


-- ============================================
-- 트랜잭션
-- ============================================
BEGIN;

UPDATE accounts SET balance = balance - 50000
WHERE id = 'A001';

UPDATE accounts SET balance = balance + 50000
WHERE id = 'A002';

COMMIT;  -- 성공 시
-- ROLLBACK;  -- 실패 시

🗣️ Say It Like This in Practice

💬 In a meeting to choose the DB for a new project
"For core business data, PostgreSQL guarantees transactions; for sessions and cache, Redis; and for logs and analytics data, MongoDB would be good. It's a polyglot persistence pattern that makes the most of each DB's strengths."
💬 When asked about DB selection criteria in an interview
"An RDBMS has a fixed schema and guarantees ACID transactions, so it is suitable for important data such as finance and orders. NoSQL has a flexible schema and scales horizontally with ease, so it is suitable for data that requires large volumes and rapid change. In practice, in commerce, we combined PostgreSQL for products/orders, Elasticsearch for search, and Redis for sessions."
💬 In a code review, feedback on DB usage patterns
"You're embedding all the data in a single MongoDB collection, but this data is frequently changing reference data. One option is to separate it into its own collection and use lookup, or to move this part out to an RDBMS altogether. Try redesigning it to fit the characteristics of the data."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Cautions & Best Practices

❌
No Over-Engineering

A complex DB stack is unnecessary for a simple CRUD app. Start simple and scale when needed. Remember the YAGNI principle.

❌
Lack of Backup/Recovery

Regular backups and recovery tests are essential. Define the recovery time (RTO) and the tolerable data loss (RPO) for failures, and prepare accordingly.

❌
Insufficient Security Settings

Connection encryption (SSL/TLS), access control (principle of least privilege), and SQL Injection prevention (parameter binding) are essential.

✅
Best Practices

Use connection pooling, optimize index design, analyze query execution plans, set up monitoring and alerts, and establish a migration strategy.

🔗 Related Terms

📚 Learn More