CodexBloom - Programming Q&A Platform

PostgreSQL: Unexpected slow query performance with indexed columns in JOIN operation

👀 Views: 372 đŸ’Ŧ Answers: 1 📅 Created: 2025-05-31
postgresql performance indexing query-optimization SQL

I'm performance testing and I need some guidance on I've searched everywhere and can't find a clear answer. I've been working on this all day and I'm collaborating on a project where Hey everyone, I'm running into an issue that's driving me crazy. I'm encountering a significant performance issue with a query that involves two tables in a JOIN operation, despite having indexes on the columns involved. The query looks something like this: ```sql SELECT a.id, a.name, b.description FROM table_a a JOIN table_b b ON a.id = b.a_id WHERE a.created_at > NOW() - INTERVAL '7 days'; ``` Both `table_a` and `table_b` have the following relevant indexes: ```sql CREATE INDEX idx_table_a_id ON table_a(id); CREATE INDEX idx_table_b_a_id ON table_b(a_id); ``` However, when I run this query, it takes upwards of 10 seconds to complete, which is unacceptable for our application. I've tried using the `EXPLAIN ANALYZE` command to troubleshoot, and the output suggests that the query planner isn't using the indexes effectively: ``` Seq Scan on table_a a (cost=0.00..123.00 rows=1000 width=64) Filter: (created_at > (now() - '7 days'::interval)) Rows: 1000 Seq Scan on table_b b (cost=0.00..150.00 rows=2000 width=128) ``` The output shows that both tables are being scanned sequentially. I've checked the statistics for `table_a` and `table_b` using `ANALYZE`, and even ran `VACUUM` to ensure that there is no bloat. I'm on PostgreSQL 13.3. Additionally, I noticed that `table_a` has about 100,000 rows, and `table_b` has about 200,000 rows. I'm wondering if there are optimizations I can apply to make this query run faster. Are there any specific strategies for improving JOIN performance in PostgreSQL, especially when indexes seem to be ignored? Any insights would be greatly appreciated! For context: I'm using Sql on Linux. My development environment is Windows. Any help would be greatly appreciated! My team is using Sql for this microservice. Any pointers in the right direction? I've been using Sql for about a year now. This is part of a larger application I'm building. What am I doing wrong?