Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining two column's data into one column in SQL?

Tags:

sql

sql-server

I am trying to combine Last name, first name and middle name into single sort name column in a SQL statement. Sometime middle name will be NULL, and if that's the case, the sort name is showing NULL.

How to handle this?

SELECT TOP 500
  Last_Name, First_Name, Middle_Name,
  [Last_Name] + ',' + [First_Name] + ' ' + [Middle_Name] AS SORT_NAME
FROM [dbo].[usr_CUSTOMER]
ORDER BY SORT_NAME

Results:

Last_Name  First_Name   MiddleName  Sort_Name
Aa         Robert       NULL        NULL

But I want to see sort_name to be 'Aa,Robert'.

like image 984
James123 Avatar asked Dec 28 '25 15:12

James123


2 Answers

COALESCE:

  COALESCE([Last_Name], '') + ',' + COALESCE([First_Name], '') + ' ' + 
  COALESCE( 
          [Middle_Name], '') AS SORT_NAME

Of course, this will leave ugly commas when last name or both first and middle are empty, so your actual code will need to be a bit more clever.

like image 123
drdwilcox Avatar answered Dec 31 '25 06:12

drdwilcox


Use the ISNULL() function - it replaces a NULL value with something you define:

SELECT TOP 500 
    Last_Name, First_Name, Middle_Name, 
    [Last_Name] + ',' + [First_Name] + ' ' + ISNULL([Middle_Name], '') as SORT_NAME   
FROM [dbo].[usr_CUSTOMER]  
ORDER BY SORT_NAME
like image 20
marc_s Avatar answered Dec 31 '25 05:12

marc_s



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!