Thread: Supplying a default on read, if a column does not exist in DB

Supplying a default on read, if a column does not exist in DB

From
Bryce Nesbitt
Date:
Is there a clean way in Postgres to specify a default return value, if a 
column does not exist in a database?  In pseudocode:

select p_email,
CASE WHEN EXISTS("p_email_alt") THEN p_email_alt ELSE 'none' END
from eg_application;

I can kind of almost get there with:

select p_email,
CASE WHEN EXISTS(SELECT * FROM information_schema.columns
WHERE table_schema='public' and table_catalog='stage' and 
table_name='eg_application' and column_name='p_email_alt')
THEN p_email_alt ELSE 'none' END
from eg_application;

Except that Postgres evaluates the non-existent column name in the 
"THEN", and errors out, even though the test will be false.

Note that use of stored procedures won't work for my particular use case.
            -Bryce

Google Keywords: "if column exists", "if column defined", test for 
existence of column, default column value, defaults, information schema, 
existence, definition, missing column.