Sql Server

SQL | COALESCE Function

SQL | COALESCE Function

SQL | COALESCE Function

The Coalesce function of the SQL server is used to manage Null values. During the expression evaluation process, user-defined values are used to replace the null values. This method always returns the first non-null value after evaluating arguments from the supplied arguments list in a specific sequence.


Properties of the Syntax of SQL Server Coalesce function :
- All expressions must be have same data-type.
- It could have multiple expressions.
- The SQL Coalesce function is a syntactic shortcut for the Case expression


SQL Coalesce in a string concatenation operation


SELECT firstName +' '+COALESCE(MiddleName,'') +' '+ LastName  FROM Person.Person
-- replace any middle name NULL values with a value ‘ ‘ (Char(13)-space). The SQL statement should still
concatenate all three names, but no NULL values will show up in the output.


SQL Coalesce function and pivoting
returns the concatenated non-null values from the table ‘state’.

DECLARE @col nvarchar(MAX);
SELECT @col = COALESCE(@col,'') +''''+CITY +''''+ ',' FROM dbo.STATE WHERE state = 'WI';
   
SELECT substring(@col,1,len(@col)-1)


Data validation using SQL Coalesce function
Find the emergency employee contacts.

SELECT
  firstname+''+lastname fullname,
   relationship,
  COALESCE(homephone, workphone, cellphone, 'NA') phone
FROM
  Contacts
 --select the columns homephone, workphone, and cellphone. In case of NULL values, the value 'NA' (not applicable), a literal string is returned.


-- Similar to Case Statement
SELECT
  firstname+''+lastname fullname,
   relationship,
  CASE
  WHEN homephone is NOT NULL Then homephone
  WHEN cellphone is NOT NULL Then cellphone
  WHEN workphone is NOT NULL Then workphone
   ELSE 'NA'
   END
   EmergencyContactNumber
FROM
  Contacts



Create a computed column using the Coalesce SQL function so that NULL values are efficiently handled.

ALTER TABLE dbo.EMP
ADD Total_Salary AS
      CAST(COALESCE(HOURLYWAGE * 40 * 52,  
   salary,  
   Salary+(COMMISSION * NUMSALES)) AS decimal(10,2))








Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.

Instagram