Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redshift - how to use listagg with information_schema.columns table

I'm using redshift and would like to create a comma separated list of columns. I'm trying to grab the column names from information schema using listagg:

SELECT  
listagg(column_name,',') within group (order by ordinal_position) 
FROM    information_schema.columns
WHERE   table_schema = 'my_schema'
AND     table_name = 'my table';

I'm getting the following error:

[Amazon](500310) Invalid operation: Function (listagg(text,text)) must be applied on at least one user created tables;
like image 777
noober Avatar asked Apr 22 '16 01:04

noober


1 Answers

Here is a work around I tested..

select listagg(column_name, ', ') within group (order by column_name)
from 
(
    select  
        a.attname::varchar as column_name, typname::varchar as data_type
    from
        pg_type t, 
        pg_attribute a,
        pg_class c,
        pg_namespace ns,
        (select top 1 1 from my_schema.my_table)
    where 
        t.oid=a.atttypid
        and a.attrelid = c.oid
        and c.relnamespace = ns.oid
        and typname NOT IN ('oid','xid','tid','cid')
        and attname not in ('deletexid', 'insertxid')
        and trim(relname) = 'my_table'
        and ns.nspname = 'my_schema'
)
like image 155
Faiz Avatar answered Oct 05 '22 00:10

Faiz