Skip to content

Query timeout: statement took too long

Quick summary

Your query ran longer than the configured timeout — the database cancelled it and returned a timeout error.

Why this happens

  • The query scans a large table without an appropriate index, causing a slow full table scan

  • The statement timeout is set too low for legitimate long-running analytical queries

  • A missing WHERE clause or overly broad filter returns far more rows than expected

Minimal example

✗ Broken code
const result = await db.query('SELECT * FROM orders JOIN items ON orders.id = items.order_id');
// No WHERE clause, no index on items.order_id — full scan, times out
✓ Fixed code
// Add index: CREATE INDEX idx_items_order_id ON items(order_id);
const result = await db.query(
  'SELECT * FROM orders JOIN items ON orders.id = items.order_id WHERE orders.date >= $1 LIMIT 100',
  ['2024-01-01']
);

Adding an index on the join column and a WHERE clause with LIMIT reduces the query scope, making it complete within the timeout.

How to diagnose

  • Run EXPLAIN ANALYZE on the query to identify the slow operation (seq scan, nested loop, etc.)

  • Check if appropriate indexes exist on the columns used in WHERE, JOIN, and ORDER BY clauses

  • Review the statement timeout setting and compare with the expected query duration

How to fix

  • Add indexes on the columns used in filtering and joining to speed up the query

  • Increase the statement timeout for known long-running analytical queries

  • Optimize the query by adding WHERE clauses, limiting results, or rewriting joins

How to prevent

  • Create indexes on frequently queried columns and monitor slow query logs

  • Set appropriate statement timeouts and use pagination for large result sets

Related Resources

Related Glossary

Related Lessons

← Back to language