B-Treeインデックスの基礎
PostgreSQLで最も一般的なインデックス形式であるB-Treeインデックスの構造と動作原理を理解します。
「B-Treeインデックスの基礎」はCoddyKit上の無料PostgreSQL Performance & Query Optimizationレッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはPostgreSQL Performance & Query Optimization学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 PostgreSQL Performance & Query Optimizationコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
What are Database Indexes?
Ever looked up a word in a dictionary? You don't read every page; you use the alphabetical index to jump straight to the letter, then the word.
Database indexes work similarly. They are special lookup tables that the database search engine can use to speed up data retrieval. Without them, finding specific data in a large table can be like reading every page of a book to find one word.
Meet the B-Tree Index
In PostgreSQL, the B-Tree index is the most common and default type. It's so fundamental that when you create a PRIMARY KEY, PostgreSQL automatically builds a B-Tree index for it!
The 'B' often stands for 'balanced,' referring to how the tree keeps all its 'leaves' (where data pointers are) at roughly the same depth, ensuring efficient searches.
B-Tree Structure: The Nodes
Think of a B-Tree as a hierarchical structure, like an upside-down tree. It's made up of different types of nodes:
- Root Node: The very top node; every search starts here.
- Branch Nodes: Intermediate nodes that point towards other branch nodes or leaf nodes. They guide the search path.
- Leaf Nodes: The bottom-most nodes. These contain the actual index entries and pointers to the rows in your table.
How Keys are Stored
Each node in a B-Tree contains a sorted list of keys and pointers. The keys are the values from the indexed column (e.g., user IDs, product names).
Branch nodes have keys that define ranges, pointing to the next node in the path. Leaf nodes contain the actual indexed key values and a Tuple ID (TID), which is a physical pointer to the exact location of the row in the table.
Searching a B-Tree
When you query for a specific value, PostgreSQL traverses the B-Tree:
- It starts at the root node.
- Compares your search value with the keys in the current node to decide which child pointer to follow.
- It moves down through branch nodes until it reaches a leaf node.
- Once in the leaf node, it finds the key and uses its associated TID to fetch the full row directly from the table.
A Query's Journey
Let's see a simple query that benefits from an index. When you create a PRIMARY KEY, PostgreSQL automatically creates a B-Tree index behind the scenes.
Try running this SQL. Notice how quickly it finds the specific user:
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(100)
);
INSERT INTO users (name) VALUES
('Alice'), ('Bob'), ('Charlie'), ('David'), ('Eve');
SELECT * FROM users WHERE id = 3;The Primary Key's Secret
In the previous example, the query for id = 3 was very fast because the PRIMARY KEY constraint on the id column automatically created a B-Tree index.
This index allows PostgreSQL to avoid scanning every single row in the users table. Instead, it uses the B-Tree to quickly locate the specific id=3 entry and then fetches the corresponding row.
B-Trees for Range Queries
B-Tree indexes aren't just great for finding exact matches (like id = 3). Because the keys in the leaf nodes are stored in sorted order and linked together, B-Trees are also highly efficient for range queries.
Queries using operators like >, <, >=, <=, or BETWEEN can quickly traverse the leaf nodes to find all values within a specified range.
B-Trees and ORDER BY
Another significant benefit of B-Trees is their ability to speed up sorting operations. Since the index entries are already stored in sorted order, if your query includes an ORDER BY clause on the indexed column, PostgreSQL can often use the index to return results already sorted.
This can save the database from performing a separate, potentially expensive, sort operation on the entire dataset.
Quick Check on B-Trees
Let's test your understanding of B-Tree indexes.
Recap: B-Tree Fundamentals
Great job! In this lesson, you learned about the fundamentals of B-Tree indexes:
- They are the most common index type in PostgreSQL.
- They are 'balanced' trees made of root, branch, and leaf nodes.
- Nodes store sorted keys and pointers (TIDs) to actual table rows.
- B-Trees dramatically speed up finding specific data (equality searches).
- They are also very efficient for range queries and can help with
ORDER BYclauses.
Understanding these basics is key to optimizing your PostgreSQL queries!
よくある質問
「B-Treeインデックスの基礎」レッスンは無料ですか?
はい。「B-Treeインデックスの基礎」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、PostgreSQL Performance & Query Optimizationコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 PostgreSQL Performance & Query Optimizationコースには全4レッスンが含まれています。
「B-Treeインデックスの基礎」で何を学びますか?
PostgreSQLで最も一般的なインデックス形式であるB-Treeインデックスの構造と動作原理を理解します。 ブラウザで直接実行するハンズオンコードでPostgreSQL Performance & Query Optimizationを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
PostgreSQL Performance & Query Optimizationを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのPostgreSQL Performance & Query Optimizationは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/4です。
「B-Treeインデックスの基礎」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このPostgreSQL Performance & Query Optimizationレッスンでコードを書いて実行できますか?
はい。すべてのPostgreSQL Performance & Query Optimizationレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- B-Treeインデックスの基礎
- インデックスの作成と利用
- インデックスを付けるタイミングと方法
- 複合インデックスとカバリングインデックス