I know exactly what coalesce does and I have used it once. Literally, once. It can be used to replace a null value with some other value like zero. But as someone who is new to working with data, what I don't understand is why I would want to do that. Why do I want to replace a null value with zero instead of just letting it be null in the data?
Videos
What does the COALESCE function do in SQL?
The COALESCE function returns the first non-NULL value from a list of expressions, making it useful for handling missing or incomplete data.
When should you NOT use the SQL COALESCE function?
Avoid using the SQL COALESCE function when replacing NULL(s) – it could change the meaning of your data, especially in analytics or reporting where NULL represents unknown values.
What is the syntax of COALESCE?
The basic syntax is:
COALESCE(value1, value2, ..., valueN)
It evaluates each value in order and returns the first one that is not NULL.
You must have a typo, or some other simple reason.
It is very easy to verify, just return both a.id and COALESCE(a.id, a.id) in the same query together. Make sure to use aliases, so that you know that you are looking at a.id and not id from some other table.
SELECT
a.id AS a_id,
COALESCE(a.id, a.id) AS filled_id,
a.name, a.website, a.lat, a.long, a.primary_poc, a.sales_rep_id, o.*
FROM accounts a
LEFT JOIN orders o
ON a.id = o.account_id
WHERE o.total IS NULL;
For this example you've provided, if a.id is null of course the second a.id will be null.
COALESCE is helpful with left joins for e.g
select coalesce(DE.user_id, KBU.user_id, OUD.user_id) as User_ID
LEFT JOIN dm.EDW.DIM_Employee DE
ON de.user_id = RIGHT(SubQuery.[UserID], LEN(SubQuery.[UserID]) - 5)
AND de.dss_current_flag = 'Y'
AND de.Dss_Deleted_Flag = 'N'
-- Some of the users are missing from our Dim Table so need to use other sources
LEFT JOIN tts..load_KBNetwork_Users KBU
ON KBU.UID = RIGHT(SubQuery.[UserID], LEN(SubQuery.[UserID]) - 5)
LEFT JOIN dm.dbo.organisationunitdimension OUD
ON oud.OrgUnitLevel5SourceId = RIGHT(SubQuery.[UserID], LEN(SubQuery.[UserID]) - 5)
AND oud.dss_current_flag = 'Y'
if DE is null then I can get the first null value from the next two (if possible)