Database8 min

PostgreSQL B-Tree Indexing and Database Query Acceleration

An index architecture that brings queries down to milliseconds: the B-Tree structure, using EXPLAIN ANALYZE and composite index strategies.

AuthorŞakir Ortataş

PostgreSQL B-Tree Indexing and Database Query Acceleration — Interactive System Model

PostgreSQL & Prisma

Explore the isometric model, or switch between tabs to discover different architectures.

Once a database holds hundreds of thousands of records, every SELECT query on a table without an index triggers a full table scan (Seq Scan). This sends disk I/O load through the roof and can lock up the entire system.

How Does the B-Tree (Balanced Tree) Architecture Work?

PostgreSQL uses B-Tree indexing by default. A B-Tree keeps data in a sorted, balanced tree structure, reducing search complexity from O(N) to O(log N). A single record among millions of rows is located with just 3-4 disk reads.

Column Order in Composite Indexes

In composite indexes that span multiple columns, the order in which the columns are written is vital. Columns with equality conditions should come first, while range or ordering (order by) conditions should come after.

Reading Execution Plans with EXPLAIN ANALYZE

When optimizing queries, look not at guesses but at the real timings and index scan types in the EXPLAIN ANALYZE output. With the right index, a heavy reporting query that takes 1200ms can be brought down to around 4ms.

PostgreSQL B-Tree Indexing and Database Query Acceleration · Live Code BlockDatabase · TS 5.x
PostgreSQL B-Tree Indexing and Database Query Acceleration · Live Code Block
60 FPS · TS 5.x · Running
1// Prisma schema and query optimization
2// CREATE INDEX idx_users_active_created ON "User" ("status", "createdAt" DESC);
3export async function getActiveUsersCursor(cursor?: string, take = 25) {
4 return prisma.user.findMany({
5 take,
6 skip: cursor ? 1 : 0,
7 cursor: cursor ? { id: cursor } : undefined,
8 where: {
9 status: "ACTIVE",
10 deletedAt: null,
11 },
12 select: {
13 id: true,
14 email: true,
15 displayName: true,
16 createdAt: true,
17 },
18 orderBy: { createdAt: "desc" },
19 });
20}
Contact

Let's turn your technical vision into a working product

TypeScript · React Native · React · NestJS · Node.js