52

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

1
  • 1
    SELECT COALESCE(field1, field2) AS the_field FROM my_table; would work if the fields were NULL. Are they really empty strings instead of being NULL? Commented Dec 5, 2012 at 12:34

3 Answers 3

84

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.

Sign up to request clarification or add additional context in comments.

Comments

53

Try COALESCE with NULLIF:

SELECT COALESCE(NULLIF(field1, ''), field2) AS the_field FROM my_table;

Comments

10

The ANSI SQL function Coalesce() is what you want.

 select Coalesce(field1,field2)
 from   table;

4 Comments

Apparently field1 may be an empty string, in which case the OP does not want its value, but field2's value instead.
Ugh. Recently converted from Oracle and I don't like this empty-string-is-not-null malarkey.
Dude, no other language (including other SQLs) treats null as an empty string. (And that's not malarkey. Why should null exist in the first place if it's just an empty string?)
I guess it's just what happens when a product predates the earliest standards for that type of product, and the standards take a different approach, and the product doesn't change to adopt the standard. Or something.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.