title: psycopg2: Will PostgreSQL store a copy of a table on disk if it has run out of memory
body: <p>I am running the following query on 489 million rows (102 gb) on a computer with 2 gb of memory:</p>
  
  <pre><code>select * from table order by x, y, z, h, j, l;
  </code></pre>
  
  <p>I am using psycopg2 with a server cursor ("cursor_unique_name") and fetch 30000 rows at a time. </p>
  
  <p>Obviously the result of the query cannot stay in memory, but my question is whether the following set of queries would be just as fast:</p>
  
  <pre><code>select * into temp_table from table order by x, y, z, h, j, l;
  select * from temp_table
  </code></pre>
  
  <p>This means that I would use a temp_table to store the ordered result and fetch data from that table instead.</p>
  
  <p>The reason for asking this question is that the takes only 36 minutes to complete if run manually using psql, but it took more than 8 hours (never finished) to fetch the first 30000 rows when the query was executed using psycopg2.</p>