DEV Community

丁久
丁久

Posted on • Originally published at dingjiu1989-hue.github.io

Database Indexing Strategies

This article was originally published on AI Study Room. For the full version with working code examples and related articles, visit the original post.

Database Indexing Strategies

Database Indexing Strategies

Database Indexing Strategies

Database Indexing Strategies

Database Indexing Strategies

Database Indexing Strategies

Database Indexing Strategies

Database Indexing Strategies

What Is Database Indexing?

A database index is a data structure that improves the speed of data retrieval operations on a table at the cost of additional writes and storage space. Think of it like a book's index: instead of flipping through every page to find a topic, you look up the topic in the index and go directly to the right page.

How Indexes Work

Without an index, the database performs a sequential scan, reading every row until it finds matches. With an index, the database navigates a balanced tree structure to locate data in O(log n) time instead of O(n).

Sequential Scan: [Row1] [Row2] [Row3] ... [Row1M] = 1,000,000 reads

B-Tree Index: [Root] -> [Branch] -> [Leaf] -> [Row] = 3-4 reads

Index Types

B-Tree Index

The default and most common index type. Works well for equality and range queries.

CREATE INDEX idx_users_email ON users(email);

CREATE INDEX idx_users_created ON users(created_at);

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\-- Used for:

SELECT * FROM users WHERE email = 'alice@example.com';

SELECT * FROM users WHERE created_at > '2026-01-01';

SELECT * FROM users WHERE email LIKE 'alice%';

Hash Index

Optimized for equality comparisons. Not suitable for range queries or sorting.

CREATE INDEX idx_sessions_token ON sessions USING HASH(session_token);

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\-- Good for:

SELECT * FROM sessions WHERE session_token = 'abc123';

GiST Index

Generalized Search Tree, useful for full-text search and geometric data.

CREATE INDEX idx_posts_content ON posts USING GIST(to_tsvector('english', content));

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\-- Used for:

SELECT * FROM posts

WHERE to_tsvector('english', content) @@ to_tsquery('database & indexing');

GIN Index

Generalized Inverted Index, optimized for composite types and arrays.

CREATE INDEX idx_article_tags ON articles USING GIN(tags);

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\-- Used for:

SELECT * FROM articles WHERE tags @> ARRAY['postgresql'];

SELECT * FROM articles WHERE tags && ARRAY['database', 'sql'];

BRIN Index

Block Range INdex, efficient for very large tables with naturally ordered data.

CREATE INDEX idx_logs_created ON logs USING BRIN(created_at)

WITH (pages_per_range = 32);

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\-- Best for:


Read the full article on AI Study Room for complete code examples, comparison tables, and related resources.

Found this useful? Check out more developer guides and tool comparisons on AI Study Room.

Top comments (0)