1

I'm trying to do a Case-statment in postgres to do different things depending on if a column exist or not,

CASE 
WHEN select exists (select * from information_schema.columns where 
table_name = 'mytable' and column_name = 'mycolumnt')
THEN select mycolumn from mytable where mycolumnt = true
ELSE select mycolumn from mytable
END

After executing the case statement I got below error

ERROR: syntax error at or near "case"

Any tips what I'm doing wrong? My postgres-knowledge is pretty basic.

Elmseld
  • 83
  • 12

1 Answers1

0

Your query should start with SELECT. Like:

SELECT mycolumn
FROM mytable
WHERE CASE WHEN exists (
     select * 
     from information_schema.columns 
     where table_name = 'mytable' and column_name = 'mycolumnt')
   THEN mycolumnt = true
   ELSE true
   END

Also, I would recommend you to always have mycolumnt, just set it to false when there is no translation. This would simplify your query to this:

SELECT mycolumn
FROM mytable
WHERE mycolumnt = true
Max
  • 915
  • 10
  • 28
  • That sound right, but when I wright it like that I get ERROR: column "mycolumnt" does not exist when the column is'nt. – Elmseld Aug 08 '17 at 09:06
  • So mytable may not have mycolumn in some cases? – Max Aug 08 '17 at 09:09
  • no exactly my bad, mycolumn always exist but not mycolumnt, mycolumnt is a translate-column for a boolean-value if a value in mycolumn should be translated or not, but if all the values should be translated there isn't a mycolumnt. – Elmseld Aug 08 '17 at 09:14
  • Yes it had absolute been easier to always have mycolumnt, but the code is meant to be for many tables and columns and if every column has a translate-column it would be a lot of columns. – Elmseld Aug 08 '17 at 12:29