Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL: Select one of two fields depending on which is empty

Hello I have a query where I want to select the value of one of two fields depending if one is empty.

field1 and field2 

I want to select them as complete_field

IF field1 is empty, then complete_field is field2 ELSE complete_field is field1 

In php it would be done like:

$complete_field = $field1 == '' ? $field2 : $field1; 

How would I do this in PostgreSQL?

I tried:

SELECT (IF field1 = '' THEN field2 ELSE field1) AS complete_field FROM table 

But it doesnt work.

Please help me :) Thanks

like image 692
Ozzy Avatar asked Dec 05 '12 12:12

Ozzy


People also ask

How do I use coalesce in PostgreSQL?

In PostgreSQL, the COALESCE function returns the first non-null argument. It is generally used with the SELECT statement to handle null values effectively. Syntax: COALESCE (argument_1, argument_2, …); The COALESCE function accepts an unlimited number of arguments.

How do I select two columns in PostgreSQL?

PostgreSQL SELECT statement syntax If you specify a list of columns, you need to place a comma ( , ) between two columns to separate them. If you want to select data from all the columns of the table, you can use an asterisk ( * ) shorthand instead of specifying all the column names.

What does <> mean in PostgreSQL?

<> is the standard SQL operator meaning "not equal". Many databases, including postgresql, supports != as a synonym for <> . They're exactly the same in postgresql.

What is Ifnull in PostgreSQL?

SQL Server supports ISNULL function that replaces NULL with a specified replacement value: ISNULL(expression, replacement) If the expression is NULL, then the ISNULL function returns the replacement . Otherwise, it returns the result of the expression . PostgreSQL does not have the ISNULL function.


2 Answers

Use CASE WHEN .. THEN .. ELSE .. END, e.g.:

SELECT  (CASE WHEN (field1 IS NULL OR field1 = '') THEN field2 ELSE field1 END) FROM table; 

Check it out at the official docs.

like image 102
Marcelo Zabani Avatar answered Oct 02 '22 23:10

Marcelo Zabani


Try COALESCE with NULLIF:

SELECT COALESCE(NULLIF(field1, ''), field2) AS the_field FROM my_table; 
like image 33
dezso Avatar answered Oct 02 '22 21:10

dezso