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
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.
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.
<> is the standard SQL operator meaning "not equal". Many databases, including postgresql, supports != as a synonym for <> . They're exactly the same 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.
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.
Try COALESCE
with NULLIF
:
SELECT COALESCE(NULLIF(field1, ''), field2) AS the_field FROM my_table;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With