🗄️ Databases

SQL

Structured Query Language

A relational database query language. Manipulates data with commands such as SELECT, INSERT, UPDATE, and DELETE.

📖 Detailed Explanation

What is SQL?

SQL (Structured Query Language) is a standard query language for relational database management systems (RDBMS), developed at IBM in the 1970s. It is a declarative language for defining, manipulating, and controlling data: when you describe "what" you want, the database decides "how" to process it.

Classification of SQL

  • DDL (Data Definition Language): Schema definition - CREATE, ALTER, DROP, TRUNCATE
  • DML (Data Manipulation Language): Data manipulation - SELECT, INSERT, UPDATE, DELETE
  • DCL (Data Control Language): Permission control - GRANT, REVOKE
  • TCL (Transaction Control Language): Transaction control - COMMIT, ROLLBACK, SAVEPOINT

Key concepts

  • Table: A data storage unit composed of rows (Row) and columns (Column)
  • Primary Key: A column that uniquely identifies each row
  • Foreign Key: A column that references the primary key of another table
  • Index: A data structure for increasing search speed
  • Normalization: A design technique that minimizes data redundancy

Types of JOIN

  • INNER JOIN: Returns only the rows that match in both tables
  • LEFT JOIN: All of the left table + matches from the right (NULL if none)
  • RIGHT JOIN: All of the right table + matches from the left
  • FULL OUTER JOIN: All of both tables (NULL if there is no match)
  • CROSS JOIN: All combinations (Cartesian product)

Major RDBMS

  • Open source: PostgreSQL, MySQL, MariaDB, SQLite
  • Commercial: Oracle, Microsoft SQL Server, IBM DB2
  • Cloud: Amazon RDS/Aurora, Google Cloud SQL, Azure SQL

💻 Code Example

Basic CRUD Operations

SQL
-- CREATE: 데이터 삽입
INSERT INTO users (name, email, created_at)
VALUES ('Alice', 'alice@example.com', NOW());

-- READ: 데이터 조회
SELECT id, name, email
FROM users
WHERE created_at >= '2024-01-01'
ORDER BY created_at DESC
LIMIT 10;

-- UPDATE: 데이터 수정
UPDATE users
SET email = 'alice.new@example.com', updated_at = NOW()
WHERE id = 1;

-- DELETE: 데이터 삭제
DELETE FROM users
WHERE id = 1;

JOIN and Aggregation

SQL
-- 주문과 사용자 정보 조인
SELECT
    u.name AS user_name,
    o.order_id,
    o.total_amount,
    o.created_at AS order_date
FROM orders o
INNER JOIN users u ON o.user_id = u.id
WHERE o.status = 'completed'
ORDER BY o.created_at DESC;

-- 집계 함수와 GROUP BY
SELECT
    u.id,
    u.name,
    COUNT(o.id) AS order_count,
    SUM(o.total_amount) AS total_spent,
    AVG(o.total_amount) AS avg_order_value
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
GROUP BY u.id, u.name
HAVING COUNT(o.id) >= 5
ORDER BY total_spent DESC;

Subqueries and CTEs

SQL
-- 서브쿼리: 평균보다 많이 구매한 사용자
SELECT name, email
FROM users
WHERE id IN (
    SELECT user_id
    FROM orders
    GROUP BY user_id
    HAVING SUM(total_amount) > (
        SELECT AVG(total_amount) FROM orders
    )
);

-- CTE (Common Table Expression): 가독성 향상
WITH monthly_sales AS (
    SELECT
        DATE_TRUNC('month', created_at) AS month,
        SUM(total_amount) AS revenue
    FROM orders
    WHERE status = 'completed'
    GROUP BY DATE_TRUNC('month', created_at)
),
growth AS (
    SELECT
        month,
        revenue,
        LAG(revenue) OVER (ORDER BY month) AS prev_revenue
    FROM monthly_sales
)
SELECT
    month,
    revenue,
    ROUND((revenue - prev_revenue) / prev_revenue * 100, 2) AS growth_rate
FROM growth
WHERE prev_revenue IS NOT NULL;

Window Functions

SQL
-- 순위 함수
SELECT
    name,
    department,
    salary,
    RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS dept_rank,
    DENSE_RANK() OVER (ORDER BY salary DESC) AS overall_rank,
    ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS row_num
FROM employees;

-- 누적 합계와 이동 평균
SELECT
    order_date,
    daily_revenue,
    SUM(daily_revenue) OVER (ORDER BY order_date) AS cumulative_revenue,
    AVG(daily_revenue) OVER (
        ORDER BY order_date
        ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
    ) AS moving_avg_7days
FROM daily_sales;

Indexes and Performance Optimization

SQL
-- 인덱스 생성
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_orders_user_date ON orders(user_id, created_at DESC);
CREATE UNIQUE INDEX idx_users_email_unique ON users(email);

-- 복합 인덱스 (왼쪽 컬럼부터 사용됨)
CREATE INDEX idx_orders_status_date ON orders(status, created_at);

-- EXPLAIN으로 실행 계획 확인
EXPLAIN ANALYZE
SELECT * FROM orders
WHERE user_id = 123 AND status = 'completed'
ORDER BY created_at DESC
LIMIT 10;

💬 Real-world conversation examples

Junior Developer
"Why is this query so slow? It's fetching all the data with SELECT *..."
Senior developer
"SELECT * is an anti-pattern. Specify only the columns you need. And run EXPLAIN to check whether it uses the index. If the columns in the WHERE clause have no index, a Full Table Scan occurs."
Backend developer
"What is the N+1 problem? I'm using an ORM and a huge number of queries are being sent."
DBA
"It's a problem that occurs when you fetch related data inside a loop. 1 query + N additional queries. You can solve it by fetching everything at once with a JOIN or by using the ORM's Eager Loading."
Team lead
"Can't I run this report query on the production DB?"
Architect
"Run heavy analytical queries on a Read Replica. If you put load on the production DB, the entire service slows down. And if locks occur, it gets even more serious."

⚠️ Cautions

⚠️ SQL Injection Defense
Do not concatenate user input directly into queries. Always use Prepared Statements/Parameterized Queries. "WHERE id = " + userId is absolutely forbidden.
⚠️ Index Design
Create indexes on columns used in WHERE, JOIN, and ORDER BY. However, having many indexes degrades INSERT/UPDATE performance. For composite indexes, column order matters (Leftmost Prefix).
⚠️ Handling Large Volumes of Data
Run large UPDATE/DELETE operations in chunks. Processing them all at once holds locks for a long time and causes the WAL log to explode. For batch jobs, combine LIMIT with a loop.
⚠️ Handling NULL
NULL cannot be compared with the = operator. Use IS NULL / IS NOT NULL. Operations that include NULL mostly result in NULL. Using COALESCE to handle default values is recommended.

🔗 Related Terms

📚 Learn More