Skip to content

Out of Memory

Error message

                out of memory
              

Quick summary

The database server exhausted available memory, often due to a query that returns or processes too much data.

Why this happens

  • A query without LIMIT returns millions of rows

  • A complex join or aggregation creates a huge intermediate result

  • The server has insufficient memory for the workload

  • Too many concurrent connections each using large work areas

Minimal example

✗ Broken code
-- Loading all rows into memory
SELECT * FROM huge_table;
-- millions of rows → out of memory
✓ Fixed code
-- Process in batches
SELECT * FROM huge_table LIMIT 1000 OFFSET 0;

Adding LIMIT prevents the query from loading all rows into memory at once.

How to diagnose

  • Check the server's memory usage and configuration (work_mem, shared_buffers)

  • Identify the query that triggered the error — it likely processes too much data

  • Check the number of concurrent connections

How to fix

  • Add a LIMIT to the query to reduce the result set size

  • Optimize the query to use indexes and avoid large intermediate results

  • Increase the server's available memory or tune memory settings

  • Reduce the number of concurrent connections

How to prevent

  • Always use LIMIT for queries that might return large result sets

  • Use pagination instead of loading all rows at once

  • Monitor memory usage and set alerts

  • Tune work_mem and shared_buffers for your workload

Related Resources

Related Glossary

Related Lessons

← Back to language