Skip to content

B-tree, hash and inverted indexes

Working knowledgeConcept

An index is not one thing. A B-tree, a hash index and an inverted index each make one kind of question fast: ranges, exact matches, or words. Here is how each is laid out, and so what it can and cannot answer.

01 Three questions, three shapes

A shop's database gets three kinds of question all day. Each is fast with the right index and slow with the wrong one, because each index is built around one shape of question.

queries.sql
-- a range: products between 10 and 30
SELECT * FROM products WHERE price BETWEEN 10 AND 30;
-- an exact match: whose session is this?
SELECT * FROM sessions WHERE token = '51ee';
-- words: which descriptions mention fast boats?
SELECT * FROM products
WHERE to_tsvector('english', description) @@ to_tsquery('english', 'fast & boats');

02 B-tree: keep the keys in order

A B-tree stores the keys sorted, in pages, with a few levels of pages above that point to ranges of keys. Finding one key is a walk from the top, one page per level. Because the bottom level is in order, every key between two values sits in one run, so the same walk answers ranges too.

B-tree leaf entries for price, in order: the range 10 to 30 is one run
B-tree leaves · price, sorted
3
5
8
start12
15
19
22
27
stop31
40
46
58
  • in the range
  • first one past it

Find 12 by walking down the tree, read right until 31, stop. Ordering is what makes ranges, ORDER BY and prefix matches cheap.

This is why B-tree is the default in Postgres, MySQL's InnoDB and most other databases: it answers =, <, >, BETWEEN, ORDER BY and prefix matches, all from one structure. The price is a walk of a few pages per lookup, where a hash index typically reads about one bucket.

03 Hash: jump to one bucket

A hash index runs each key through a hash function and stores it in the bucket the result picks. To look a key up, hash it and read that one bucket. Two keys that collide share a bucket and are told apart by comparing them.

A hash index on session token, 8 buckets, looking up 51ee
hash(token) mod 8 (made-up hash values)
7c2e→bucket 1a91f→bucket 251ee→bucket 2looked upe05b→bucket 43d4a→bucket 5b7c0→bucket 7
Buckets
—0
7c2e1
hasha91f · 51ee2
—3
e05b4
3d4a5
—6
b7c07
  • bucket checked
  • empty bucket

Hash 51ee, go to bucket 2, compare the two tokens there. On average, the cost does not grow with the table. But the buckets are in no useful order, so a range has nowhere to start.

A good hash function scatters keys on purpose: 12 and 13 land in unrelated buckets. That is what spreads the load, and it is also why a hash index cannot answer <, >, BETWEEN or ORDER BY. It knows about equality and nothing else.

04 Inverted: from words to documents

Neither of those helps with words. A B-tree on description sorts whole strings, so a word in the middle of one has no place in the order. An inverted index flips the data around: for each word, it stores the list of documents that contain it, called a posting list. Search engines are built on them, and in Postgres a GIN index over a tsvector is one.

Six toy product descriptions
idtextterms stored
1fast red carsfast red car
2slow blue boatsslow blue boat
3fast boatsfast boat
4red bikes for salered bike sale
5fast bikesfast bike
6fast boats for salefast boat sale

Before storing, the text is split into terms, common words such as for are dropped, and words are reduced to a stem, so boats is stored as boat. A query for several words fetches each posting list and keeps the documents they share.

Searching an inverted index for fast boats
Step 1 of 8
Comparisons 0
Inverted index · word → documents
bike→4, 5blue→2boat→2, 3, 6car→1fast→1, 3, 5, 6red→1, 4sale→4, 6slow→2
Posting list · fast
doc 1
doc 3
doc 5
doc 6
Posting list · boat
doc 2
doc 3
doc 6
Documents with both words
Empty
  • looked up
  • being compared
  • on both lists
  • just added
  • not fetched yet

The query is fast boats. Postgres's English text search turns it into the terms fast and boat, the same way it turned every document into terms when the index was built. Nothing is looked up yet.

fast boats query

05 Which index answers what

Postgres index types against common query shapes
QueryB-treeHashInverted (GIN)
token = '51ee'yesyesno
price BETWEEN 10 AND 30yesnono
ORDER BY price LIMIT 10yes, no sort needednono
name LIKE 'ana%'yes, with text_pattern_ops or C collationnono
doc @@ 'fast & boat'nonoyes
tags @> ARRAY['sale']nonoyes
B-treeRanges and orderThe general choice. Also does exact matches, a few page reads each.
HashExact matches onlyOne bucket per lookup, but B-tree is usually close, so it is rarely worth it.
InvertedWords and elementsAnswers which rows contain a word, an array element or a JSON key.

06 Making each one in Postgres

indexes.sql
-- B-tree is the default
CREATE INDEX products_price_idx ON products (price);
-- hash: equality only
CREATE INDEX sessions_token_idx ON sessions USING hash (token);
-- inverted: GIN over the words of each description
CREATE INDEX products_words_idx ON products
USING gin (to_tsvector('english', description));

On Postgres 16, the hash index is used for = and ignored for a range on the same column:

first_name = 'Jo'
Bitmap Heap Scan on people
Recheck Cond: (first_name = 'Jo'::text)
-> Bitmap Index Scan on people_first_hash
Index Cond: (first_name = 'Jo'::text)
first_name > 'Jo'
Gather
Workers Planned: 1
-> Parallel Seq Scan on people
Filter: ((first_name > 'Jo'::text)
AND (first_name < 'Jp'::text))

A text-search index is only used when the query uses the same expression it was built on. Index to_tsvector('english', description) and then query to_tsvector(description) without the 'english', and Postgres will not match them.

07 When the wrong kind bites

WHERE name LIKE '%boat%'A wildcard at the startNo B-tree helps, and a word index only matches whole terms. For substrings, Postgres has the pg_trgm extension, which builds an inverted index over three-letter pieces.
LIKE 'ana%' with en_US collationPrefix search ignoredUnder most collations, a plain B-tree is not used for LIKE. Build it with text_pattern_ops, or use the C collation.
USING hash ... UNIQUEExpecting hash to do morePostgres hash indexes cover one column and cannot enforce uniqueness. Before Postgres 10 they were not crash-safe either, so old advice says to avoid them.
UPDATE products SET description = ...Inverted indexes are dear to updateChanging one description touches the posting list of every word in it. GIN softens this by queueing new entries in a pending list, which makes some searches slower until it is merged.

08 Check yourself

Question

A dashboard shows orders from the last 24 hours, newest first. Which index on created_at fits?

Question

You look users up only by an API key, always with =. Is a hash index wrong?

Question

Search must find products whose description contains the word waterproof. Which index answers that?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?