How to Combine Two Columns in SQL

In SQL, combining two or more columns into a single column is a common task. This is often used to create a full name from first and last name columns, or to create a full address from street, city, and state columns. The most common way to do this is by using the CONCAT() function.

Using the CONCAT() function

The CONCAT() function takes two or more strings as arguments and concatenates them into a single string. Here is an example of how to use the CONCAT() function to combine the first_name and last_name columns into a single full_name column:

SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM your_table;

In this example, we are concatenating the first_name column, a space, and the last_name column. The AS full_name part gives the new column the name full_name.

Using the + operator

In some SQL dialects, such as SQL Server, you can use the + operator to concatenate strings. Here is an example of how to use the + operator to combine the first_name and last_name columns:

SELECT first_name + ' ' + last_name AS full_name FROM your_table;

Using the || operator

In other SQL dialects, such as PostgreSQL and Oracle, you can use the || operator to concatenate strings. Here is an example of how to use the || operator to combine the first_name and last_name columns:

SELECT first_name || ' ' || last_name AS full_name FROM your_table;
bannerAds