title: CTE Execution Order
body: <p>In the following CTE statement:</p>
  
  <pre><code>CREATE TABLE test_table (Field1 INTEGER, Field2 INTEGER);
  CREATE TABLE test_table2 (Field1 INTEGER, Field2 INTEGER);
  
  WITH table_stage1(fld1, fld2) AS
      (SELECT Field1, Field2 from test_table1)
  , table_stage2 AS 
      (SELECT fld1, fld2 FROM table_stage1 GROUP BY fld1, fld2)
  , table_stage3 AS 
      (SELECT fld1 FROM table_stage1 GROUP BY fld1)
  INSERT INTO test_table2(Field1, Field2)
      SELECT t1.fld1, t2.fld2
          FROM table_stage2 t1
          JOIN table_stage3 t2
      ON t1.fld1 = t2.fld1;
  </code></pre>
  
  <p>Can I assume the following order of query execution:</p>
  
  <ol>
  <li><code>SELECT</code> inside WITH statemt</li>
  <li>Concurrent execution of <code>SELECT</code> inside <code>table_stage2</code>, and <code>table_stage3</code> segments</li>
  <li><code>INSERT INTO</code> waits till execution of <code>table_stage2</code>, <code>table_stage3</code> is finished</li>
  </ol>
  
  <p>This question is not related to a particular (presented) statement.</p>
  
  <p>I would like to know if by selecting from a named segment there is a guarantee the current statement will be executed after the particular named segment.
  Meybe what is significat is having a number of select statements folowed by a write CTE that joins results from previous segments</p>
  
  <p>The PostgeSQL <a href="https://www.postgresql.org/docs/9.6/static/queries-with.html" rel="noreferrer">documentations</a> we can read:</p>
  
  <blockquote>
    <p>The sub-statements in WITH are executed concurrently with each other
    and with the main query. Therefore, when using data-modifying
    statements in WITH, the order in which the specified updates actually
    happen is unpredictable.</p>
  </blockquote>
  
  <p>I am working on PostgreSQL 9.6  </p>