1

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!

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

Comments

1

You can simply use coalesce. It will first select the non null value from the options.

select coalesce(column_1,column_2) as column_3 from my_table

You can also use case when

select (case when column_1 is null then column_2 else column1 end) as column_3 from my_table

I would prefer first option.

1 Comment

It is worth saying that the types of columns are important. If they are not compatible, then there will be an error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.