Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
B-trees
5. How the database uses an index – sample 1
Summary

Instruction

But what does an index look like inside the database? Databases use various kinds of data structures to create indexes. The most popular are B-trees. They are called trees because the structure resembles an upside-down tree.

Let's say we've got ten players in the player table. Each player has a points total ranging from 1 to 42. Our index on the column points may look like this:

LEAD

How does this structure work? Suppose we've got the following query:

SELECT
  *
FROM player
WHERE points = 30;

Normally, the database would check each and every row in the table to list the players with 30 points. But the index structure can help us do it quicker. The database first looks at the top level of the tree: there are the numbers 13 and 30. The pink circles are used to move downwards. Which route should we take? The circle to the left of number 13 indicates players with less than 13 points. The circle between numbers 13 and 30 indicates players with at least 13 points, but fewer than 30. The circle to the right of the number 30 indicates players with at least 30 points. Since we're looking for players with 30 points, we choose the rightmost circle and go deeper.

LEAD

We're now at level two and we can see a single number: 38. The circle to the left will take us to players with less than 38 points. The circle to the right will take us to players with at least 38 points. As we're looking for players with 30 points, we're taking the left circle, going deeper... and there we go! At the lowest level, we can find a single row with exactly 30 points (a player with the nickname 'shadow'). We can return that row and finish the query.

LEAD

By using the index, we only had to do a few quick checks to reach the row we were looking for. That's why the performance of the entire query was better.

Exercise

Click Next exercise to continue.