๐Ÿ—„๏ธ Databases

Join

Join

A SQL operation that combines two or more tables on a specific condition to query data, with various types such as INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN.

๐Ÿ“– Detailed Explanation

Join is a core operation in relational databases that combines data from multiple normalized tables. Based on the relationships between tables (mainly foreign keys), it builds related data into a single result set, making it possible to efficiently query complex information without data duplication.

The most commonly used INNER JOIN returns only the rows that satisfy the join condition in both tables. LEFT JOIN (LEFT OUTER JOIN) returns all rows from the left table along with the matching rows from the right table, and fills in NULL where there is no match. RIGHT JOIN is the opposite, and FULL OUTER JOIN returns all rows from both tables.

Join performance optimization is at the core of database tuning. Performance improves when you create indexes on join columns, SELECT only the necessary columns, and filter data first with a WHERE clause. By analyzing the query execution plan (EXPLAIN), you can check which algorithm among Nested Loop, Hash Join, and Merge Join is being used and optimize accordingly.

In modern ORMs (Object-Relational Mapping), joins are provided in an abstracted form. Examples include SQLAlchemy's join(), Django ORM's select_related(), and JPA's @JoinColumn. However, to avoid the N+1 problem and write efficient queries, it is important to understand the SQL that is actually generated.

๐Ÿ’ป Code Example

SQL Join Examples by Type

-- ์˜ˆ์ œ ํ…Œ์ด๋ธ” ๊ตฌ์กฐ
-- users: id, name, email
-- orders: id, user_id, product_name, amount, created_at

-- ============================================
-- INNER JOIN: ๋‘ ํ…Œ์ด๋ธ”์— ๋ชจ๋‘ ์žˆ๋Š” ๋ฐ์ดํ„ฐ๋งŒ
-- ============================================
SELECT
    u.name,
    u.email,
    o.product_name,
    o.amount
FROM users u
INNER JOIN orders o ON u.id = o.user_id
WHERE o.created_at >= '2024-01-01';
-- ๊ฒฐ๊ณผ: ์ฃผ๋ฌธ์ด ์žˆ๋Š” ์‚ฌ์šฉ์ž๋งŒ ์กฐํšŒ๋จ

-- ============================================
-- LEFT JOIN: ์™ผ์ชฝ ํ…Œ์ด๋ธ”(users)์˜ ๋ชจ๋“  ํ–‰ ํฌํ•จ
-- ============================================
SELECT
    u.name,
    u.email,
    COALESCE(o.product_name, '์ฃผ๋ฌธ ์—†์Œ') AS product,
    COALESCE(o.amount, 0) AS amount
FROM users u
LEFT JOIN orders o ON u.id = o.user_id;
-- ๊ฒฐ๊ณผ: ์ฃผ๋ฌธ์ด ์—†๋Š” ์‚ฌ์šฉ์ž๋„ NULL ๊ฐ’๊ณผ ํ•จ๊ป˜ ์กฐํšŒ๋จ

-- ============================================
-- ๋‹ค์ค‘ ํ…Œ์ด๋ธ” JOIN
-- ============================================
-- products: id, name, category_id, price
-- categories: id, name

SELECT
    u.name AS customer_name,
    o.created_at AS order_date,
    p.name AS product_name,
    c.name AS category_name,
    o.amount
FROM users u
INNER JOIN orders o ON u.id = o.user_id
INNER JOIN products p ON o.product_id = p.id
INNER JOIN categories c ON p.category_id = c.id
WHERE o.amount > 100
ORDER BY o.created_at DESC;

-- ============================================
-- SELF JOIN: ๊ฐ™์€ ํ…Œ์ด๋ธ”์„ ์ž๊ธฐ ์ž์‹ ๊ณผ ์กฐ์ธ
-- ============================================
-- employees: id, name, manager_id

SELECT
    e.name AS employee_name,
    m.name AS manager_name
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id;
-- ๊ฒฐ๊ณผ: ์ง์›๊ณผ ๊ทธ ์ง์›์˜ ๋งค๋‹ˆ์ € ์ด๋ฆ„์„ ํ•จ๊ป˜ ์กฐํšŒ

-- ============================================
-- ์ง‘๊ณ„์™€ ํ•จ๊ป˜ ์‚ฌ์šฉํ•˜๋Š” JOIN
-- ============================================
SELECT
    u.name,
    COUNT(o.id) AS order_count,
    SUM(o.amount) AS total_spent,
    AVG(o.amount) AS avg_order_amount
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;

Using Join in Python SQLAlchemy

from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, func
from sqlalchemy.orm import declarative_base, relationship, Session, joinedload
from sqlalchemy import select

Base = declarative_base()

# ๋ชจ๋ธ ์ •์˜
class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String(100))
    email = Column(String(255))
    orders = relationship("Order", back_populates="user")

class Order(Base):
    __tablename__ = 'orders'
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('users.id'))
    product_name = Column(String(255))
    amount = Column(Integer)
    user = relationship("User", back_populates="orders")


# ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์—ฐ๊ฒฐ
engine = create_engine("postgresql://user:pass@localhost/mydb")

with Session(engine) as session:
    # ================================
    # 1. ๊ธฐ๋ณธ INNER JOIN
    # ================================
    stmt = (
        select(User.name, Order.product_name, Order.amount)
        .join(Order, User.id == Order.user_id)
        .where(Order.amount > 100)
    )
    results = session.execute(stmt).all()
    for name, product, amount in results:
        print(f"{name}: {product} - {amount}์›")

    # ================================
    # 2. LEFT OUTER JOIN
    # ================================
    stmt = (
        select(User.name, Order.product_name)
        .outerjoin(Order, User.id == Order.user_id)  # LEFT JOIN
    )
    results = session.execute(stmt).all()
    for name, product in results:
        product = product or "์ฃผ๋ฌธ ์—†์Œ"
        print(f"{name}: {product}")

    # ================================
    # 3. Eager Loading์œผ๋กœ N+1 ๋ฌธ์ œ ํ•ด๊ฒฐ
    # ================================
    # joinedload: ํ•œ ๋ฒˆ์˜ JOIN ์ฟผ๋ฆฌ๋กœ ๊ด€๋ จ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜ด
    stmt = (
        select(User)
        .options(joinedload(User.orders))
        .where(User.name.like('๊น€%'))
    )
    users = session.scalars(stmt).unique().all()
    for user in users:
        print(f"{user.name}์˜ ์ฃผ๋ฌธ:")
        for order in user.orders:  # ์ถ”๊ฐ€ ์ฟผ๋ฆฌ ๋ฐœ์ƒํ•˜์ง€ ์•Š์Œ
            print(f"  - {order.product_name}")

    # ================================
    # 4. ์ง‘๊ณ„ ํ•จ์ˆ˜์™€ GROUP BY
    # ================================
    stmt = (
        select(
            User.name,
            func.count(Order.id).label('order_count'),
            func.sum(Order.amount).label('total_spent')
        )
        .outerjoin(Order)
        .group_by(User.id, User.name)
        .having(func.count(Order.id) >= 3)
        .order_by(func.sum(Order.amount).desc())
    )
    results = session.execute(stmt).all()
    for name, count, total in results:
        print(f"{name}: {count}๊ฑด, ์ด {total or 0:,}์›")

    # ================================
    # 5. ์„œ๋ธŒ์ฟผ๋ฆฌ๋ฅผ ํ™œ์šฉํ•œ ๋ณต์žกํ•œ JOIN
    # ================================
    # ์ตœ๊ทผ ์ฃผ๋ฌธ์ด ์žˆ๋Š” ์‚ฌ์šฉ์ž๋งŒ ์กฐํšŒ
    subquery = (
        select(Order.user_id)
        .where(Order.created_at >= '2024-01-01')
        .distinct()
        .subquery()
    )

    stmt = (
        select(User)
        .join(subquery, User.id == subquery.c.user_id)
    )
    active_users = session.scalars(stmt).all()

๐Ÿ—ฃ๏ธ How It's Said in Practice

Backend Developer "The order history API is slow. Looking at the logs, there's an N+1 problem. It's querying user information separately for each order."
Senior Developer "Use select_related or joinedload to fetch everything at once with a JOIN. Check the execution plan with EXPLAIN, and also check whether the join columns have indexes."
DBA "For joins on large tables, a Hash Join may be more efficient. Check the work_mem setting as well."
Interviewer "Please explain the differences between INNER JOIN and LEFT JOIN, and when to use each."
Candidate "INNER JOIN returns only the data that matches in both tables, while LEFT JOIN includes all rows from the left table and returns NULL where there is no match. For example, a 'list of customers who placed orders' uses INNER JOIN, and 'all customers and their order status (showing none if there are no orders)' uses LEFT JOIN."

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

Reviewer "A CROSS JOIN may occur in this query. If you list multiple tables in FROM without an ON clause, it becomes a Cartesian product."
Author "Right, although it does filter in WHERE, I'll change it to an explicit INNER JOIN ON. It improves readability and helps prevent mistakes too."

โš ๏ธ Cautions

  • Check indexes: If the columns used in join conditions (foreign keys, primary keys) have no index, a Full Table Scan occurs and performance degrades sharply. It is especially essential for large tables.
  • N+1 problem: When an ORM fetches related data with Lazy Loading, a query is issued on every loop iteration. Use Eager Loading (joinedload, select_related).
  • Join order: When joining multiple tables, join the smaller tables first, or keep statistics up to date so that the optimizer can choose the optimal order.

๐Ÿ“š Learn More