title: How to repeat a query in postgreSQL, and add the results to a table
body: <p>I need to run a query 1000 times, and add the results to a table. I have the following code which is what I would like to be repeated:</p>
  
  <pre><code>Select max_gridco, count(max_gridco) as TaxLots, sum(population) as pop_sum
  from
  (
      Select tlid, max_gridco, population
      from (
          select tlid, max_gridco, population, st_intersects(tle.geom, acres025.geom)
          from tle, acres025
          where max_gridco not in (0, 1)
          order by RANDOM()
          limit 1000
      ) as count
      where st_intersects = 't'
      order by max_gridco
  ) as gridcode_count
  group by max_gridco;
  </code></pre>
  
  <p>Is there a way that I can run this 1000 times automatically, and in the output table have a column that includes the run number? So my table would look like the following:</p>
  
  <p>Run number | max_gridco | TaxLots | pop_sum</p>
  
  <p>I am trying to do a Loop command in PgAdmin3, but cannot seem to get the syntax correct.</p>