SQL Cookbook Lesson
How to concatenate strings in SQL
Learn how to concatenate strings in SQL with examples and explanations from SQLPad.
Problem
You need to concatenate, or join, two or more strings together in a SQL query.
Sample Data
Let's imagine we have a table called "users" with the following data:
| id | first_name | last_name |
|---|---|---|
| 1 | John | Doe |
| 2 | Jane | Doe |
| 3 | Mary | Johnson |
And we want to concatenate the 'first_name' and 'last_name' fields to display full names.
MySQL Solution
SELECT CONCAT(first_name, ' ', last_name) AS 'Full Name'
FROM users;
Explanation - MySQL
In MySQL, the CONCAT() function is used to concatenate two or more strings. We're using it to combine 'first_name' and 'last_name' fields, with a space (' ') in between to separate them. The result is aliased as 'Full Name'. For each row in 'users' table, it will return the full name.
PostgreSQL Solution
SELECT first_name || ' ' || last_name AS "Full Name"
FROM users;
Explanation - PostgreSQL
In PostgreSQL, the || operator is used to concatenate two or more strings. We're using it to combine 'first_name' and 'last_name' fields, with a space (' ') in between to separate them. The result is aliased as 'Full Name'. For each row in 'users' table, it will return the full name.