Skip to content
Advertisement

How to select column 1 value if exists else column 2 value in PostgresQL?

I want to merge two columns in PostgresQL query by the following rule:

select (column_1 or column_2) as column_3 from my_table

Is there a way to achieve it? Though quite clear, I want to prefer column_1 value as column_3 but if it is null, I would like column_2 value as column_3.

Sorry if this sounds naive, thanks!

Advertisement

Answer

Use COALESCE(). From the manual 9.18.2. COALESCE:

The COALESCE function returns the first of its arguments that is not null. Null is returned only if all arguments are null.

For example:

select coalesce(column_1, column_2) as column_3 from t
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement