Decide what “combine” means
“Combine” can mean two different things, and the query depends on which one you want:
- Join the values in each row. A first name and a last name become one full name. You concatenate the two columns.
- Stack the values across rows. A work phone and a mobile phone both go into one Phone column, with one row for each phone. You use UNION ALL or UNPIVOT.
If you want one row per record with one combined value, concatenate. If you want one column with more rows, stack.
Join the values in each row
In SQL Server, use + or CONCAT() in the SELECT list:
SELECT FirstName + ' ' + LastName AS FullName
FROM dbo.Employees;
SELECT CONCAT(FirstName, ' ', LastName) AS FullName
FROM dbo.Employees;
CONCAT() works in MySQL and PostgreSQL too. For the || operator used by Oracle, PostgreSQL and other databases, see what is the use of || in SQL.
Two things to watch for:
- NULL values. With
+, a NULL in either column makes the whole result NULL. If LastName is missing for some rows, use CONCAT_WS(’ ’, FirstName, LastName) on SQL Server 2017 or later. It skips the NULL and the extra space. The fuller set of NULL options is in merge two columns in sql server. - Numbers.
+adds two numeric columns instead of joining them. If one column is a number, cast it to text first:
SELECT CAST(OrderId AS VARCHAR(20)) + ' - ' + Status AS OrderLabel
FROM dbo.Orders;
Stack the values across rows
UNION ALL stacks the results of two SELECT statements. Each SELECT has to return the same number of columns, with compatible data types:
SELECT CustomerId, WorkPhone AS Phone
FROM dbo.Customers
UNION ALL
SELECT CustomerId, MobilePhone
FROM dbo.Customers;
UNION ALL keeps every row. A plain UNION also removes duplicate rows, which takes extra work, so use it only when you need the removal.
Missing phone numbers come through as NULL rows. To skip them, add WHERE WorkPhone IS NOT NULL to the first SELECT, and the same test for MobilePhone to the second.
Use UNPIVOT in SQL Server
UNPIVOT does the same stacking in one step. It’s specific to T-SQL:
SELECT CustomerId, PhoneType, Phone
FROM dbo.Customers
UNPIVOT (
Phone FOR PhoneType IN (WorkPhone, MobilePhone)
) AS u;
The column names in the IN list become values in the PhoneType column. UNPIVOT drops rows where the value is NULL, so missing phone numbers don’t appear. The columns you unpivot need compatible data types. In databases without UNPIVOT, use UNION ALL instead.
Pick a method
If you want one combined value per row, use + or CONCAT(). If you want one column that holds several rows’ worth of values, use UNION ALL, or UNPIVOT on SQL Server.