AI Hints
Home›PostgreSQL Tutorial›Indexes and EXPLAIN
PostgreSQL · Lesson 50 of 120

B-tree Indexes

The default index.

⏱ 2 min read▶ Video at 43:50🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Create index makes a B tree unless you ask for something else. B trees keep values sorted, so they help with equals, ranges, and sorting.

  • Equals
  • Ranges
  • Sorting

Ranges and sorting

We index viewed at. Now a filter on the last day can use the index. And order by viewed at descending with a limit reads the newest rows straight from the index, with no sorting. Run it. Both plans use the index.

query.sqlsql
CREATE INDEX views_time_idx ON page_views (viewed_at);

EXPLAIN (COSTS OFF)
SELECT count(*) FROM page_views
WHERE viewed_at >= '2025-12-13';

EXPLAIN (COSTS OFF)
SELECT * FROM page_views ORDER BY viewed_at DESC LIMIT 5;
Output
CREATE INDEX
                                      QUERY PLAN
---------------------------------------------------------------------------------------
 Aggregate
   ->  Index Only Scan using views_time_idx on page_views
         Index Cond: (viewed_at >= '2025-12-13 00:00:00+00'::timestamp with time zone)
(3 rows)

                          QUERY PLAN
--------------------------------------------------------------
 Limit
   ->  Index Scan Backward using views_time_idx on page_views
(2 rows)
Also uses _setup.sql
SELECT setseed(0.42);
CREATE TABLE page_views (
  view_id     bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  customer_id integer NOT NULL,
  book_id     integer NOT NULL,
  device      text NOT NULL,
  viewed_at   timestamptz NOT NULL,
  ms          integer NOT NULL);
INSERT INTO page_views (customer_id, book_id, device, viewed_at, ms)
SELECT 1 + (random() * 499)::int, 1 + (random() * 29)::int,
       (ARRAY['web','web','web','app','app'])[1 + (random() * 4)::int],
       timestamptz '2025-01-01' + (g * interval '100 seconds'),
       50 + (random() * 900)::int
FROM generate_series(1, 300000) g;
VACUUM ANALYZE page_views;
ALTER DATABASE riverside SET max_parallel_workers_per_gather = 0;

B-tree helps with

Equals, less than and greater than. Between and in. Order by, in either direction. And like with a fixed start, like a prefix. It doesn't help with like starting with a percent sign.

keyvalue
= < > BETWEENyes
ORDER BYyes, no sort
LIKE 'abc%'yes, with text_pattern_ops
LIKE '%abc'no

Summary

B tree indexes help with equals, ranges and sorting. Next, reading query plans with explain.

Key takeaways
  • B-tree
  • Ranges
  • ORDER BY
Next up: EXPLAIN — read the plan