PostgreSQL Indexing thực chiến: khi nào index giúp, khi nào không, và đọc EXPLAIN ANALYZE

Query chậm là nguồn gốc của rất nhiều "tại sao app lag?". Phần lớn performance issues trên PostgreSQL giải quyết được bằng index đúng chỗ — nhưng cũng không ít trường hợp index được tạo nhưng Postgres chọn không dùng. Bài này đi vào thực tế: loại index nào dùng khi nào, đọc EXPLAIN ANALYZE không sợ, và các bẫy phổ biến.

B-tree index — loại index mặc định

Khi bạn CREATE INDEX không specify loại, PostgreSQL tạo B-tree. Hoạt động tốt với: equality (=), range queries (>, <, BETWEEN), IN, ORDER BY, IS NULL.

-- Index đơn column
CREATE INDEX idx_orders_user_id ON orders(user_id);
CREATE INDEX idx_orders_created_at ON orders(created_at);

-- Composite index (thứ tự columns quan trọng)
-- Dùng được cho: (status), (status, created_at), KHÔNG cho (created_at) alone
CREATE INDEX idx_orders_status_created ON orders(status, created_at);

-- Query tận dụng composite index
SELECT * FROM orders
WHERE status = 'pending'
AND created_at > NOW() - INTERVAL '7 days'
ORDER BY created_at DESC;

Rule of thumb composite index: Đặt columns có high selectivity (nhiều giá trị distinct) và thường dùng trong equality filter lên đầu. Columns dùng cho range query đặt cuối.

GIN index — cho JSONB, arrays, và fulltext search

-- Ví dụ: table products với metadata JSONB
CREATE TABLE products (
    id       SERIAL PRIMARY KEY,
    name     TEXT,
    metadata JSONB,
    tags     TEXT[]
);

-- GIN index cho JSONB (hỗ trợ @>, ?, ?|, ?& operators)
CREATE INDEX idx_products_metadata ON products USING GIN (metadata);

-- GIN index cho array column
CREATE INDEX idx_products_tags ON products USING GIN (tags);

-- Query dùng GIN index trên JSONB
SELECT * FROM products WHERE metadata @> '{"brand": "Apple"}';
SELECT * FROM products WHERE metadata ? 'discount_price';  -- key tồn tại không

-- Query dùng GIN index trên array
SELECT * FROM products WHERE tags @> ARRAY['laptop', 'gaming'];  -- chứa cả hai

-- GIN index cho fulltext search
CREATE INDEX idx_products_fts ON products USING GIN (to_tsvector('english', name));
SELECT * FROM products
WHERE to_tsvector('english', name) @@ plainto_tsquery('english', 'gaming laptop');

Partial index — index chọn lọc, nhỏ hơn, nhanh hơn

-- Chỉ index orders chưa xử lý — đây thường là subset nhỏ
CREATE INDEX idx_orders_pending ON orders(created_at)
WHERE status = 'pending';

-- Query phải include WHERE condition y chang để dùng partial index
SELECT * FROM orders
WHERE status = 'pending'
AND created_at < NOW() - INTERVAL '1 day'
ORDER BY created_at;

-- Partial index cho soft delete pattern
CREATE INDEX idx_users_active ON users(email)
WHERE deleted_at IS NULL;

-- Unique partial index: email unique trong active users (cho phép nhiều deleted)
CREATE UNIQUE INDEX idx_users_email_unique ON users(email)
WHERE deleted_at IS NULL;

Đọc EXPLAIN ANALYZE

EXPLAIN ANALYZE
SELECT * FROM orders
WHERE user_id = 42
AND status = 'completed'
ORDER BY created_at DESC
LIMIT 20;

Output điển hình:

Limit  (cost=0.43..45.21 rows=20 width=156) (actual time=0.125..0.892 rows=20 loops=1)
  ->  Index Scan using idx_orders_user_status on orders
        (cost=0.43..891.23 rows=395 width=156) (actual time=0.121..0.881 rows=20 loops=1)
        Index Cond: ((user_id = 42) AND (status = 'completed'))
        Filter: ...
Planning Time: 0.234 ms
Execution Time: 0.921 ms

Những gì cần chú ý:

  • Index Scan vs Seq Scan: Index Scan = dùng index. Seq Scan = quét toàn bộ bảng. Seq Scan không phải lúc nào cũng xấu — với table nhỏ hoặc trả về nhiều rows, Seq Scan có thể nhanh hơn.
  • rows estimate vs actual: Nếu estimate và actual chênh nhau nhiều lần (ví dụ estimate 5 nhưng actual 50000), statistics outdated. Chạy ANALYZE orders;
  • actual time: Thời gian thực tế. Nếu loops > 1, nhân actual time với loops để ra tổng.
  • Rows Removed by Filter: Số rows bị loại bỏ sau khi lấy từ index. Số này lớn = index condition không đủ selective, cân nhắc thêm column vào index.

Tại sao function trên column phá index

-- Index tồn tại trên column email
CREATE INDEX idx_users_email ON users(email);

-- Query này KHÔNG dùng index — vì WHERE áp dụng function lên indexed column
SELECT * FROM users WHERE LOWER(email) = 'alice@example.com';

-- Fix 1: Index trên expression
CREATE INDEX idx_users_email_lower ON users(LOWER(email));
-- Bây giờ query với LOWER(email) = '...' sẽ dùng được index

-- Fix 2: Lưu normalized value khi insert/update
-- Fix 3: Dùng citext extension cho case-insensitive matching không cần function

-- Tương tự: DATE() trên TIMESTAMPTZ phá index
-- Thay vì:
WHERE DATE(created_at) = '2025-06-27'
-- Dùng:
WHERE created_at >= '2025-06-27' AND created_at < '2025-06-28'

Phát hiện index không được dùng

-- pg_stat_user_indexes: thống kê usage của indexes
SELECT
    schemaname,
    tablename,
    indexname,
    idx_scan,      -- số lần index được dùng để scan
    idx_tup_read,  -- số index entries được đọc
    idx_tup_fetch  -- số heap rows được fetch qua index
FROM pg_stat_user_indexes
WHERE schemaname = 'public'
ORDER BY idx_scan ASC;

-- Index có idx_scan = 0 hoặc rất thấp là candidate để xóa
-- (nhưng check xem có phải table mới hoặc stats reset không)

-- Index size
SELECT
    indexname,
    pg_size_pretty(pg_relation_size(indexrelid)) AS index_size
FROM pg_stat_user_indexes
WHERE schemaname = 'public'
ORDER BY pg_relation_size(indexrelid) DESC;

Index có cost — không phải cứ nhiều là tốt

Mỗi index:

  • Tốn disk space
  • Làm chậm INSERT/UPDATE/DELETE (phải update index)
  • Tốn RAM (PostgreSQL cache index pages trong shared_buffers)

Với table write-heavy (nhiều INSERT/UPDATE hơn SELECT), mỗi index thêm vào là trade-off nghiêm túc. Xóa index không dùng (sau khi verify qua pg_stat_user_indexes) sẽ cải thiện write performance.

CONCURRENTLY — tạo index không lock table

-- Tạo index thông thường: lock table, block reads/writes trong production
CREATE INDEX idx_orders_user ON orders(user_id);

-- Tạo index CONCURRENTLY: không lock, nhưng mất nhiều thời gian hơn
-- Safe để chạy trên production table đang có traffic
CREATE INDEX CONCURRENTLY idx_orders_user ON orders(user_id);
← Về danh sách Blog