What is the difference between a B tree and a B+ tree?
MediumConceptIndexing & Query Optimization
Answer
Both are balanced search trees in which every node holds many keys, so the tree stays shallow and each node fits in one disk page. The difference is where the data is stored.
- B tree: keys and their data pointers are stored in every node, internal and leaf, so a search can stop early at an internal node.
- B+ tree: internal nodes hold only keys for routing; all data pointers (or the rows themselves) are in the leaves, and the leaves are linked in key order.
- Because B+ tree internal nodes carry no data, more keys fit in each node, so the tree is shorter.
- The linked leaves make range queries and ordered scans fast, which is why MySQL InnoDB, PostgreSQL, Oracle and SQL Server use B+ trees.
Example: Keys 10 to 50 in a small B+ tree:
[30]
/ \
[10 | 20] --> [30 | 40 | 50]
For WHERE key BETWEEN 20 AND 40, the database finds 20 in the left leaf, then follows the leaf link to the right: 20, 30, 40. A B tree would have to move up and down the tree instead.
More in Indexing & Query Optimization
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | What is indexing in DBMS, and why does it make queries faster? | Concept | Easy | Read the answer to What is indexing in DBMS, and why does it make queries faster? | |||
| 2 | What is the difference between a B tree and a B+ tree? | Concept | Medium | Read the answer to What is the difference between a B tree and a B+ tree? | |||
| 3 | What is the difference between a clustered and a non-clustered index? | Concept | Medium | Read the answer to What is the difference between a clustered and a non-clustered index? | |||
| 4 | What is the difference between a dense index and a sparse index? | Concept | Medium | Read the answer to What is the difference between a dense index and a sparse index? | |||
| 5 | How would you find and fix a slow SQL query? | Concept | Hard | Read the answer to How would you find and fix a slow SQL query? |