Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is column order guaranteed in SELECT * also within a CTE

This was already answered for queries taking directly from a table, where there is an ordinal_position metadata to draw from. My question is whether the same applies for CTEs (which may or may not have their own ordinal_position, I genuinely do not know).

WITH
cte_a AS (
SELECT 
    col_a_1 AS col_1,
    col_a_2 AS col_2
FROM table_a
),

cte_b AS (
SELECT 
    col_b_1 * 10 AS col_1,
    0            AS col_2
FROM table_b
),

unioned AS (
SELECT * FROM cte_a
UNION ALL
SELECT * FROM cte_b
),
-- more CTEs follow
-- Ultimately, a closing SELECT follows

Are the two SELECT * above guaranteed to preserve the order defined in the CTEs they draw from?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The order of columns would not change, the CTE "inherits" the metadata for the ordinal position.
Think of a CTE in this case as a regular view, views have their ordinal positions too.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading