Search code examples
postgresqlinformation-schema

how to create a postrgres query selecting a column instead of another if former exists


I need to create a query (in php but this does not really matters) for postgresql (9.1+) like this

select (<t1.column1 -if exists- or t2.column2>)::timestamp from t1 join t2 on <join field>

i was writing something along the lines of:

SELECT bytes_in, 
       coalesce((select column_name from information_schema.columns where table_name = 'table2' and column_name = 'override_tetime'), test_endtime)::timestamp as tetime
  FROM table2 t
  JOIN table1 tr ON (tr.id=t.tres_id)
 WHERE tetime BETWEEN '2016-06-01' AND '2017-01-01'

but the problem is that the retrieved field is a string and cannot be coalesced with the field test_endtime that is type timestamp with time zone

P.S. i'll explain a bit better what i need, the query could be between different tables: table1 (in the example above) that will always include a test_endtime column and various other tables table2...tableN where may, or may not, be a override_tetime column; if the joined table has that column then the resulting rowset should use the timestamp from the override_tetime column.

Hope this is a bit more understandable now.


Solution

  • There is no way to do this with a single statement in SQL.

    You'd have to specify the name of t1.column1 somewhere in the query (as identifier, not as string constant), and that will trigger a parse error if t1 doesn't have a column named column1.

    You'll have to check for column existence in a first query (probably querying the information_schema like you did) and then issue a second query that depends on the result of the first one.

    If you don't want that logic in your application code, it would be easy to write a PostgreSQL function that does it for you.