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

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'.

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.

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

You can use the ISNULL function
ISNULL ( check_expression , replacement_value )
Docs : http://msdn.microsoft.com/en-us/library/ms184325.aspx

Note that I moved the space separating First and Middle name inside the COALESCE so that you avoid having a trailing space when Middle name is NULL.
..., [Last_Name]+ ','+ [First_Name] + COALESCE(' '+ [Middle_Name],'') as SORT_NAME...

Try
CONCAT(firstname,' ', LastName,' ', MiddleName) AS Full_Name

Related

How to do not null check on LEFT function on the select query

I have a query that returns some demographics like firstName, lastName, MiddleName and i need to use LEFT function on each to filter the First Letter of each column like LEFt(firstName, 1).This is working fine when each column is not a null value. when it is null value
select otherColumns, LEFT(sub.LastName, 1) + ',' + LEFT(sub.FirstName, 1) + ' ' + LEFT(sub.MiddleName, 1) as patientInitials from <table> <inner joins> <some where conditions>;
But when one of demographics like middleName is null and other firstName, lastName are not null , patientInitials are evaulating to NULL, not sure why?
I resolved my issue by adding COALESCE
LEFT(sub.LastName, 1) + ',' + LEFT(sub.FirstName, 1) + ' ' + COALESCE((LEFT(sub.MiddleName, 1)),'') as patientInitials
But is there any other good way to check for notNull on the LEFT function ??
Help Appreciated!
But is there any other good way to check for notNull on the LEFT function ??
CONCAT function ignores NULLs:
SELECT CONCAT(LEFT(sub.LastName, 1), ',' ,
LEFT(sub.FirstName, 1),
' ' + LEFT(sub.MiddleName, 1)) patientInitials
FROM tab;
' ' + LEFT(sub.MiddleName, 1)) using ' ' will remove leading space in case if Middle Name is NULL.
The CONCAT_WS function also has a similar function:CONCAT_WS (Transact-SQL)

how to select only particular value from Name

i have a requirement to select only title from Name.
in the Name how to separate only title value and pass as title.
First_name Last_name Middle_Name Full_Name Title
NANCY HEINICK Null HEINICK,NANCY MD
CHARLES BONISKE H BONISKE,CHARLES H
THOMAS NEAL W NEAL,THOMAS W MD
In the above examples i need to select title and put it in title column if there is no title in full name i need is as NULL
Output
Title
MD
NULL
MD
Assuming the title is everything else, use replace() with a little extra logic:
select nullif(replace(replace(replace(replace(full_name, first_name, ''), last_name, ''), ',', ''), ' ', ''), '') as title
EDIT:
Because of the middle name (which I missed the first time around), it is better to concatenate all together and then replace:
select replace(full_name,
(last_name || ',' || first_name ||
coalesce(concat(' ', middle_name), '') || ' ',
), ''
) as title
Note that the code might vary slightly. Not all databases support the standard || operator for string concatenation.
You can try:
select ltrim(replace(full_name, (last_name + ',' + first_name + coalesce(' ' + middle_name, '')), ''))

Concatenate and format text in SQL

I need to concatenate the City, State and Country columns into something like City, State, Country.
This is my code:
Select City + ', ' + State + ', ' + Country as outputText from Places
However, because City and State allow null (or empty) value, what happen is, (for example) if the City is null/empty, my output will look like , Iowa, USA; or say the State is empty, then the output will look like Seattle, , USA
Is there anyway I can format the output and remove "unnecessary" commas?
Edited: Because of the requirements, I should not use any other mean (such as PL/SQL, Store Procedure) etc., so it has to be plain SQL statement
select
isnull(City, '') +
case when isnull(City, '') != '' then ', ' else '' end +
isnull(State, '') +
case when isnull(State, '') != '' then ', ' else '' end +
isnull(Country, '') as outputText
from
Places
Since adding a string with null will result null so if they are null (not empty string) this will give you teh desired result
Select isnull(City + ', ','') + isnull(State + ', ' ,'') + isnull(Country,'') as outputText from Places
Use the COALESCE (Transact-SQL) function.
SELECT COALESCE(City + ', ', '') + COALESCE(State + ', ', '')...
In SQL Server 2012 you can use CONCAT function:
select concat(City,', ',State,', ',Country ) as outputText from Places
Not elegant by any means...
first changes city, state,country to null values if blank
then interprets that value for null and adds a space before a comma
then replaces any space comma space ( , ) with empty set.
Query:
SELECT replace(coalesce(Replace(City,'',Null),' ') + ', ' +
coalesce(Replace(State,'',Null), ' ' + ', ' +
coalesce(replace(Country,''Null),''), ' , ','') as outputText
FROM Places
Assumes no city state or country will contain space comma space.

Computed Column (COALESCE vs CASE vs ISNULL)

I posted a similar question a while back and now as I need to update this code, I am back to ask a follow-on question. Previous question is here:
Computed column based on nullable columns
My data (Address1, Address2, City, State, Zip, Country) may have incomplete information. I.e. I can't be guaranteed that anything other than State and Country columns will have data.
I would like to have a computed columns for FullAddress.
Previously, I used COALESCE, which worked great if all fields are filled in. Now, as the data requirements have been relaxed, this is no longer an option (because we end with repeated commas in the FullAddress). Here is what I have been using previously (note, I'm just working with SELECT statements here for ease of use - will convert into a computed columns "alter table add" statement once I have something that works for all cases):
SELECT (((((COALESCE([Address1],'')
+ COALESCE(', '+[Address2],''))
+ COALESCE(', '+[City],''))
+ COALESCE(', '+[State],''))
+ COALESCE(', '+[Zip],''))
+ COALESCE(', '+[Country],'')) AS FullAddress
FROM Locations
Now, I have put together an alternative using CASE, but it still doesn't work for the edge case where Address1 is NULL (the problem is that the FullAddress will have ', ' as the first two characters)
SELECT CASE WHEN [Address1] IS NOT NULL THEN [Address1] ELSE '' END
+ CASE WHEN [Address2] IS NOT NULL THEN ', ' + [Address2] ELSE '' END
+ CASE WHEN [City] IS NOT NULL THEN ', ' + [City] ELSE '' END
+ CASE WHEN [State] IS NOT NULL THEN ', ' + [State] ELSE '' END
+ CASE WHEN [Zip] IS NOT NULL THEN ', ' + [Zip] ELSE '' END
+ CASE WHEN [Country] IS NOT NULL THEN ', ' + [Country] ELSE '' END
AS [FullAddress]
FROM Locations
I'm a little stuck at this point. Any recommendations what to try next?
you can use this pattern:
SELECT
ISNULL(Address1 + ', ', '')
+ ISNULL(Address2 + ', ', '')
+ ISNULL(City + ', ', '')
-- ....
AS FullAddress
The result of concation NULL + ', ' is NULL => Address1 + ', ' will be NULL or valid address => ISNULL(Address1 + ', ', '') will be empty string or valid address.
SELECT STUFF(
COALESCE(', ' + Address1, '') + COALESCE(', ' + Address2, '') + ...
1,
2,
''
) AS FullAddress
FROM Locations
The concatenated string will either be empty or start with ,  (a comma and a space). STUFF() will remove the first two characters and return the rest of the string.

How do I get first name and last name as whole name in a MYSQL query?

I want to be able to do something like this
SELECT `first_name` + " " + `last_name` as `whole_name` FROM `users`
So basically I get one column back whole_name which is first_name and last_name concatenated together with a (space).
How do I do that in SQL, or more specifically, MySQL ?
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat-ws
SELECT CONCAT_WS(" ", `first_name`, `last_name`) AS `whole_name` FROM `users`
You can use a query to get the same:
SELECT CONCAT(FirstName , ' ' , MiddleName , ' ' , Lastname) AS Name FROM TableName;
Note: This query return if all columns have some value if anyone is null or empty then it will return null for all, means Name will return "NULL"
To avoid above we can use the IsNull keyword to get the same.
SELECT Concat(Ifnull(FirstName,' ') ,' ', Ifnull(MiddleName,' '),' ', Ifnull(Lastname,' ')) FROM TableName;
If anyone containing null value the ' ' (space) will add with next value.
When you have three columns : first_name, last_name, mid_name:
SELECT CASE
WHEN mid_name IS NULL OR TRIM(mid_name) ='' THEN
CONCAT_WS( " ", first_name, last_name )
ELSE
CONCAT_WS( " ", first_name, mid_name, last_name )
END
FROM USER;
rtrim(lastname)+','+rtrim(firstname) as [Person Name]
from Table
the result will show lastname,firstname as one column header !