SQL Coalesce

The SQL Coalesce function is used to return the first nonnull expression among its arguments.

Note: If all the arguments are null, then it returns null value.

SQL Coalesce Function Syntax

Coalesce(value1, value2, value3, ...)

SQL Coalesce Function Example

Table: Users

UserId userName screenName
203 Mazojys null
204 Jozzh Lnanyo
205 null Dfaafk
206 null Srlkrt
302 Jssme null

Select userId and userName, if userName is null then select screenName as userName:

SELECT userId, Coalesce(userName, screenName) AS userName
FROM Users

The result will look like:

UserId userName
203 Mazojys
204 Jozzh
205 Dfaafk
206 Srlkrt
302 Jssme

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>