Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Coalesce" multiple columns

Tags:

sql

postgresql

If I have a simple query

SELECT row FROM table WHERE id=my_id

and I want a row with a NULL instead of an empty row if my_id isn't found, I can use coalesce

COALESCE( (SELECT row FROM table WHERE id=my_id), NULL)

What do I do if my query returns multiple columns and I want a row of NULLs?

SELECT row1,row2,row3 FROM table WHERE id=my_id
like image 343
Dahn Avatar asked Dec 15 '17 12:12

Dahn


People also ask

How do you coalesce multiple rows in SQL?

Concatenate Rows Using COALESCE All you have to do is, declare a varchar variable and inside the coalesce, concat the variable with comma and the column, then assign the COALESCE to the variable.

Can you group by coalesce?

Because the COALESCE is an expression, you can use it in any clause that accepts an expression such as SELECT , WHERE , GROUP BY , and HAVING .

How many arguments can coalesce take?

The COALESCE scalar function takes two or more arguments and returns the first nonnull argument, starting from the left in the expression list. The COALESCE function returns the value of one of the expressions in the list.

Is coalesce better than Isnull?

COALESCE promotes its argument to the higher data type. In the first SQL query, we have used ISNULL and the first data type is INT but because of its NULL, it also converts 3.00 to INT and performed integer arithmetic, but COALESCE correctly promotes the 19 to FLOAT and performed floating-point arithmetic.


2 Answers

You can create a pseudo table with UNNEST for your parameter and do a left outer join:

SELECT t.row1, t.row2, t.row3 
FROM UNNEST(ARRAY[my_id]) i LEFT OUTER JOIN table t ON t.id = i;
like image 107
clemens Avatar answered Oct 18 '22 20:10

clemens


Another solution would be to simply search the table three times

SELECT 
COALESCE( (SELECT row1 FROM table WHERE id=my_id), NULL),
COALESCE( (SELECT row2 FROM table WHERE id=my_id), NULL),
COALESCE( (SELECT row3 FROM table WHERE id=my_id), NULL)
like image 26
Dahn Avatar answered Oct 18 '22 20:10

Dahn