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

How to retain column order using listagg in snowflake

I have a Snowflake table A as below:

CREATE or replace table TABLEA
(
    Address VARCHAR(50),
    Zip VARCHAR(50),
    HASH VARCHAR(50));

insert into TABLEA (Address, Zip, HASH) values
    ('ABC', '20987', 'XX'),
    ('XYZ', '20989', 'XY'),
    ('CBZ', '20980', 'XZ');

I want to get all the column names from information schema as a string seperated by comma
exactly like the below query outputs

select listagg(COLUMN_NAME, ',') from db.information_schema.columns 
              where table_schema = 'schema' and TABLE_NAME = 'TABLEA'

but the problem with the above query is it doesnot retain the column order meaning when I execute the query 1st time, it outputs

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

ZIP,HASH,ADDRESS

whereas if I execute the same query again, it outputs

ADDRESS,ZIP,HASH

The column order is not the same, I want the column order to be consistent (as in the table) every time the query is executed

UPDATE

Adding order by ORDINAL_POSITION worked

select listagg(COLUMN_NAME, ',') WITHIN GROUP (ORDER BY ORDINAL_POSITION) from db.information_schema.columns 
                  where table_schema = 'schema' and TABLE_NAME = 'TABLEA'

>Solution :

you just need to ORDER BY ORDINAL_POSITION

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