Reputation: 377
I have a table with more than 20 columns, I want to get all columns except for one which I'll use in a conditional expression.
SELECT s.* (BUT NOT column1),
CASE WHEN column1 is null THEN 1 ELSE 2 END AS column1
from tb_sample s;
Can I achieve it in postgresql given the logic above?
Upvotes: 5
Views: 7981
Reputation: 1
I have created a request for my own use, that I use in 2 times :
Don't know if I can change it into a function, because in most of time I need to change a column type (for exemple, transforming the SCR or 'the_geom")
WITH param AS (
SELECT
'public' AS my_schema, -- enter the schema name
'my_table' AS my_table, -- enter the table name
ARRAY['the_geom'] AS excluded_fields -- enter the field(s) you want to exclude, separated with commas
)
SELECT format('SELECT %s FROM %I.%I;',
string_agg(quote_ident(column_name), ', '),
param.my_schema,
param.my_table)
FROM information_schema.columns, param
WHERE table_schema = param.my_schema
AND table_name = param.my_table
AND column_name <> ALL (param.excluded_fields )
GROUP BY param.my_schema, param.my_table;
Upvotes: 0
Reputation: 129
It may not be ideal, but you can use information_schema to get the columns and use the column to exclude in the where clause.
That gives you a list of all the column names you DO want, which you can copy/paste into your select query:
select textcat(column_name, ',')
from information_schema.columns
where table_name ='table_name' and column_name !='column_to_exclude';
Upvotes: 2