CodexBloom - Programming Q&A Platform

Optimizing slow complex queries in PostgreSQL on Linux - how to reduce execution time?

šŸ‘€ Views: 1340 šŸ’¬ Answers: 1 šŸ“… Created: 2025-09-07
PostgreSQL optimization Linux SQL

I'm stuck on something that should probably be simple. I'm testing a new approach and I'm working on a project and hit a roadblock. In the process of optimizing a PostgreSQL database running on a Linux server, I've come across several slow queries that are impacting performance significantly. Recently, I executed a complex join across multiple tables, and even though the tables are indexed appropriately, the query execution time still exceeds a few seconds. For instance, here's the SQL query I’m working with: ```sql SELECT u.id, u.name, COUNT(o.id) AS order_count FROM users u JOIN orders o ON u.id = o.user_id WHERE o.created_at > NOW() - INTERVAL '30 days' GROUP BY u.id, u.name ORDER BY order_count DESC LIMIT 10; ``` To tackle the issue, I first analyzed the execution plan using `EXPLAIN ANALYZE`, which indicated that a sequential scan was being performed rather than utilizing the indexes I created. My indexes are defined as follows: ```sql CREATE INDEX idx_users_id ON users (id); CREATE INDEX idx_orders_user_id ON orders (user_id); CREATE INDEX idx_orders_created_at ON orders (created_at); ``` I've tried adjusting the `work_mem` parameter in the PostgreSQL configuration, raising it from the default 4MB to 64MB, which resulted in a slight improvement. However, the query still lags behind my expectations. Considering that the database is running on Ubuntu 22.04 with PostgreSQL version 14, I’m wondering if there are specific configurations or query modifications that could further enhance performance. Should I consider implementing materialized views or utilizing further indexing strategies? Additionally, any insights into partitioning the `orders` table based on the `created_at` column could be helpful. Looking forward to your recommendations! Thanks in advance! My development environment is macOS. Any help would be greatly appreciated! The stack includes Sql and several other technologies. I'm open to any suggestions.