Skip to main content
SQL Intermediate Practical Coding Topic: Indexing & Query Tuning

How do composite B-Tree indexes and the leftmost prefix rule optimize SQL queries?

Quick Summary: A composite B-Tree index on (col_a, col_b, col_c) sorts entries hierarchically by col_a first, then col_b, then col_c—accelerating filters on col_a or (col_a, col_b) directly, whereas filtering on col_b alone usually cannot seek efficiently.

Written by Ravi Shankar Mishra (Founder & Lead Systems Architect, MockAttempt Academy) Reviewed by MockAttempt Engineering Editorial Desk
Last verified:

Direct Interview Answer

Like a phone directory sorted by (LastName, FirstName), a composite index ON orders (tenant_id, status, created_at) lets PostgreSQL or MySQL seek immediately when queries filter from the leftmost column onward.

Place high-equality columns (tenant_id = ?) before inequality or sort columns (created_at >= ? ORDER BY created_at DESC) so the engine stops scanning once an equality range ends.

Detailed Technical Explanation

Avoid wrapping indexed columns in functions such as WHERE LOWER(email) = ? or WHERE YEAR(created_at) = 2026 unless you build a matching functional index—otherwise the planner falls back to a slow full sequential table scan.

Practical Walkthrough

High-selectivity composite index paired with an sargable date-range predicate.

Code Example — SQL
CREATE INDEX idx_orders_tenant_status_created
    ON orders (tenant_id, status, created_at DESC);

-- Uses the composite index efficiently (SARGable):
EXPLAIN ANALYZE
SELECT id, total_paise, created_at
FROM orders
WHERE tenant_id = 12
  AND status = 'PAID'
  AND created_at >= '2026-01-01'
ORDER BY created_at DESC
LIMIT 20;
Expected Output / Verification
Index Scan using idx_orders_tenant_status_created (sub-millisecond on 10M rows).

Real-World Production Use Case

Multi-tenant SaaS dashboards paginating active orders per workspace without CPU exhaustion under load.

Common Interview Mistakes to Avoid

  • Putting a low-cardinality range column before equality columns, blocking narrow index seeks.
  • Adding overlapping single-column indexes everywhere, slowing INSERT/UPDATE write throughput.
Topics: #sql #postgresql #indexing #btree #performance
Learn. Practise. Prove. Get Career-Ready.

Ready to Build Your IT Career?

Explore industry-led programmes and develop practical skills through training, assessments and interview preparation.