🗄️ Databases

B-Tree

Balanced Tree - Self-balancing Tree Data Structure

A B-Tree is a balanced multiway search tree and the core data structure of database indexes. All leaf nodes stay at the same depth, guaranteeing O(log n) performance, and each node stores multiple keys to optimize disk I/O. It underlies all RDBMSs, including MySQL and PostgreSQL.

📖 Detailed Explanation

The Birth and Design Philosophy of the B-Tree - Invented in 1970 by Rudolf Bayer and Edward McCreight, the B-Tree was named after the B in "Balanced" (or the B in Bayer). It was designed to minimize disk accesses, which are much slower than main memory, and because multiple keys can be compared in a single disk read, search efficiency is high.

B-Tree vs B+Tree - Most real-world databases use B+Trees. In a B+Tree, all data is stored only in leaf nodes, and the leaf nodes are connected to one another by a linked list. This structure is overwhelmingly advantageous for range queries (BETWEEN, ORDER BY). Internal nodes contain only routing keys, so they can have more children.

Order and Structure - The order m of a B-Tree is the maximum number of children each node can have. Each node must have at least ⌈m/2⌉ children and stores at most m-1 keys. For example, a B-Tree of order 4 has 2-4 children and 1-3 keys. Databases typically use orders in the hundreds to thousands.

Insertion and Splitting (Split) - When a node is full as a new key is inserted, it is split in two around the median value. The middle key moves up to the parent, and this process can propagate up to the root, increasing the height of the tree. On deletion, the opposite occurs: a merge (Merge).

Use in Databases - InnoDB's clustered index (Primary Key) stores data directly in a B+Tree, and secondary indexes refer to the Primary Key. PostgreSQL's default index is also a B-Tree, applied by default when CREATE INDEX is used. Index size, page splits, and the buffer pool are key to performance.

💻 Code Example

# B-Tree 핵심 개념 구현 (교육용)
from dataclasses import dataclass, field
from typing import List, Optional


@dataclass
class BTreeNode:
    """B-Tree 노드"""
    keys: List[int] = field(default_factory=list)
    children: List['BTreeNode'] = field(default_factory=list)
    is_leaf: bool = True


class BTree:
    """
    B-Tree 구현
    - 차수 t: 각 노드는 t-1 ~ 2t-1개의 키를 가짐
    """

    def __init__(self, t: int = 2):
        self.t = t  # 최소 차수
        self.root = BTreeNode()

    def search(self, key: int, node: BTreeNode = None) -> Optional[tuple]:
        """키 검색: O(log n)"""
        if node is None:
            node = self.root

        i = 0
        while i < len(node.keys) and key > node.keys[i]:
            i += 1

        if i < len(node.keys) and key == node.keys[i]:
            return (node, i)

        if node.is_leaf:
            return None

        return self.search(key, node.children[i])

    def insert(self, key: int):
        """키 삽입: O(log n)"""
        root = self.root

        if len(root.keys) == 2 * self.t - 1:
            new_root = BTreeNode(is_leaf=False)
            new_root.children.append(self.root)
            self._split_child(new_root, 0)
            self.root = new_root

        self._insert_non_full(self.root, key)

    def _split_child(self, parent: BTreeNode, idx: int):
        """자식 노드 분할 (핵심 연산)"""
        t = self.t
        full_child = parent.children[idx]
        new_child = BTreeNode(is_leaf=full_child.is_leaf)

        mid_key = full_child.keys[t - 1]

        new_child.keys = full_child.keys[t:]
        full_child.keys = full_child.keys[:t - 1]

        if not full_child.is_leaf:
            new_child.children = full_child.children[t:]
            full_child.children = full_child.children[:t]

        parent.keys.insert(idx, mid_key)
        parent.children.insert(idx + 1, new_child)

    def _insert_non_full(self, node: BTreeNode, key: int):
        """가득 차지 않은 노드에 삽입"""
        i = len(node.keys) - 1

        if node.is_leaf:
            node.keys.append(None)
            while i >= 0 and key < node.keys[i]:
                node.keys[i + 1] = node.keys[i]
                i -= 1
            node.keys[i + 1] = key
        else:
            while i >= 0 and key < node.keys[i]:
                i -= 1
            i += 1

            if len(node.children[i].keys) == 2 * self.t - 1:
                self._split_child(node, i)
                if key > node.keys[i]:
                    i += 1

            self._insert_non_full(node.children[i], key)


# 사용 예제
if __name__ == "__main__":
    btree = BTree(t=3)

    for key in [10, 20, 5, 6, 12, 30, 7, 17]:
        btree.insert(key)

    # 검색
    result = btree.search(12)
    print(f"12 검색: {'발견' if result else '없음'}")

    # 시간 복잡도
    print("\nB-Tree 시간 복잡도:")
    print("- 검색: O(log n)")
    print("- 삽입: O(log n)")
    print("- 삭제: O(log n)")
-- B-Tree 인덱스 활용 SQL

-- ============================================
-- 1. 인덱스 생성 (B-Tree가 기본)
-- ============================================

-- 단일 컬럼 인덱스
CREATE INDEX idx_users_email ON users(email);

-- 복합 인덱스 (왼쪽부터 순서대로 사용됨)
CREATE INDEX idx_orders_composite
ON orders(customer_id, order_date DESC, status);

-- 커버링 인덱스 (테이블 접근 없이 해결)
CREATE INDEX idx_products_covering
ON products(category_id, price, name);


-- ============================================
-- 2. 인덱스 사용 최적화
-- ============================================

-- ✅ 좋은 예: 인덱스 사용
SELECT * FROM users WHERE email = 'user@example.com';
SELECT * FROM orders WHERE customer_id = 100;
SELECT * FROM orders
WHERE customer_id = 100 AND order_date > '2024-01-01';

-- ❌ 나쁜 예: 인덱스 미사용
SELECT * FROM users WHERE LOWER(email) = 'user@example.com';
SELECT * FROM orders WHERE status = 'shipped';
SELECT * FROM products WHERE name LIKE '%phone%';


-- ============================================
-- 3. 클러스터드 vs 세컨더리
-- ============================================

CREATE TABLE orders (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,  -- 클러스터드
    customer_id INT,
    order_date DATETIME,
    INDEX idx_customer (customer_id)       -- 세컨더리
);


-- ============================================
-- 4. 인덱스 통계 확인
-- ============================================

-- MySQL
SHOW INDEX FROM orders;

-- PostgreSQL
SELECT indexrelname, idx_scan, idx_tup_read
FROM pg_stat_user_indexes
WHERE schemaname = 'public';
-- EXPLAIN으로 B-Tree 인덱스 사용 분석

-- ============================================
-- 1. MySQL EXPLAIN
-- ============================================

EXPLAIN SELECT * FROM orders
WHERE customer_id = 100 AND order_date > '2024-01-01';

/*
확인 항목:
- type: const, ref, range (좋음) / ALL (나쁨)
- key: 사용된 인덱스 이름
- rows: 예상 스캔 행 수
- Extra: Using index (커버링 인덱스)
*/


-- ============================================
-- 2. PostgreSQL EXPLAIN ANALYZE
-- ============================================

EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE customer_id = 100;

/*
Index Scan using idx_orders_customer
  (cost=0.43..8.45 rows=1)
  (actual time=0.015..0.017 rows=1)
  Buffers: shared hit=3
*/


-- ============================================
-- 3. 인덱스 힌트
-- ============================================

-- MySQL: 특정 인덱스 강제 사용
SELECT * FROM orders
USE INDEX (idx_orders_customer)
WHERE customer_id = 100;

-- 인덱스 제외
SELECT * FROM orders
IGNORE INDEX (idx_orders_date)
WHERE order_date > '2024-01-01';

💬 Real-world conversation examples

A DBA in a Performance Tuning Meeting

"The reason this query is slow is that the selectivity of the B-Tree index is too low. The status column has only 3 values, so it scans 33% of the whole table. If we put customer_id first in a composite index, the B-Tree will be able to search much more efficiently."

A Senior Developer in a Code Review

"It's ORDER BY id DESC LIMIT 10, so why is there a filesort? Since the Primary Key is a B+Tree, a reverse scan should be fast too... Oh, because of the WHERE condition it goes through the secondary index to find the Primary Key. Let's solve it with a covering index."

An Architect in a Design Review

"Using a UUID as the Primary Key causes problems in a B-Tree. Because the values are random, page splits occur frequently with every insertion. If you use a ULID or Snowflake ID, inserts go only to the right side of the B-Tree, so splits are minimized."

⚠️ Cautions

🔍
Do Not Apply Functions to Indexed Columns

WHERE YEAR(created_at) = 2024 cannot use an index. Write it as WHERE created_at >= '2024-01-01' instead.

📊
Composite Index Order Matters

With INDEX(a, b, c), searching by b alone is not possible. Place the most frequently used column first.

💾
Excessive Indexes Degrade Write Performance

Every INSERT/UPDATE requires modifying the B-Tree of every index. Clean up unused indexes.

📈
LIKE '%keyword%' Invalidates the Index

A B-Tree is sorted by prefix. If you need full-text search, use a Full-Text Index.

🔗 Related Terms

📚 Learn More