Logo of Microsoft SQL Server

SQL Server - Coalesce

Usage of Coalesce with an example

Scenario

If you want to pick a column from TableA, but if it’s NULL, use a column from TableB, you need to use the COALESCE built-in function in SQL Server.

Code

1
2
3
4
5
6
SELECT
    COALESCE(a.ColumnName, b.ColumnName) AS PreferredColumn
FROM
    TableA a
JOIN
    TableB b ON a.ID = b.ID;

COALESCE returns the first non-null value from the list.

Documentation

Reference: Microsoft Learn.

Follow me

Thanks for reading this article. Make sure to follow me on X, subscribe to my Substack publication and bookmark my blog to read more in the future.

Credits: Image from Microsoft Server

License GPLv3 | Terms
Built with Hugo
Theme Stack designed by Jimmy