I googled a lot but did not find understandable answer for my question. It is interesting 4 me when do I have to use COALESCE function in query. Thank you in advance for your answer.
1 Answers
When you want the first non-NULL value for a "column" (column in this sense means in your query output, not your table).
One example might be a company's contact person. Say you have three columns:
CompanyRep
CompanySecretary
CompanyOwner
and you want to store all three. But, in a query that lets you know who you should contact, you want to deliver one of those in the order given. But any or all of them may be NULL.
The query:
select coalesce (CompanyRep, CompanySecretary, CompanyOwner, '???') as contact
from blah blah blah
would give you the value you want. It will give you the first value it finds that isn't NULL. If all the possible table columns are NULL, you'll get '???'
since that's obviously not NULL.
Another example, let's say you have an accounting database that has separate columns for debit and credit value - never mind that this is usually a bad design and you should have one column with a sign - let's assume it was set up by someone with less accounting knowledge than me :-)
So, if you then wanted to sum up all transactions to ensure credits and debits are equal, you could use something like:
select sum (coalesce (credit, -debit, 0)) from txns ...
That way, it will select the credit value if it's not NULL, otherwise it will select the negation of the debit value (all values are positive). If they're both NULL, it will give you zero.
What happens when they're both non-NULL I hear you ask. Well, that's why it's a bad design :-)