PostgreSQL B-Tree Index Not Used Fix
In this tutorial, you'll learn about PostgreSQL B. We cover key concepts, practical examples, and best practices.
A B-Tree index exists on a column but queries still perform sequential scans because the WHERE clause wraps the column in a function like EXTRACT or LOWER.
The Wrong Way
CREATE INDEX idx_orders_date ON orders(created_at);
EXPLAIN ANALYZE SELECT * FROM orders WHERE EXTRACT(YEAR FROM created_at) = 2025;
Output:
Seq Scan on orders ...
Time: 2340.567 ms
The Right Way
CREATE INDEX idx_orders_date ON orders(created_at);
EXPLAIN ANALYZE SELECT * FROM orders WHERE created_at >= '2025-01-01' AND created_at < '2026-01-01';
Output:
Index Scan using idx_orders_date on orders ...
Time: 15.234 ms
Step-by-Step Fix
1. Identify function calls on indexed columns in WHERE clauses
2. Rewrite the query to use a range condition instead of a function wrapper
3. Alternatively create an expression index: CREATE INDEX ON orders(EXTRACT(YEAR FROM created_at))
4. Verify with EXPLAIN ANALYZE that the index is now used
5. Use pg_stat_user_indexes below to track index scan counts over time
Prevention Tips
- Test all queries with the database's explain plan tool before deploying to production.
- Monitor query performance trends using built-in monitoring tools.
- Set up automated index usage analysis in CI/CD pipelines.
- Review database configuration quarterly against workload patterns.
- Keep database statistics up to date with regular maintenance operations.
- Use DodaTech's monitoring tools to track query performance regressions.
Common Mistakes with index btree
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world POSTGRESQL code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro