PostgreSQL CONCAT() Function
Summary: in this tutorial, you will learn how to use the PostgreSQL CONCAT()
function to concatenate two or more strings into one.
Introduction to PostgreSQL CONCAT() function
To concatenate two or more strings into a single string, you can use the string concatenation operator || as shown in the following example:
Output:
The following statement uses the concatenation operator (||
) to concatenate a string with NULL
:
It returns NULL
.
Since version 9.1, PostgreSQL has introduced a built-in string function called CONCAT()
to concatenate two or more strings into one.
Here’s the basic syntax of the CONCAT()
function:
The CONCAT
function accepts a list of input strings, which can be any string type including CHAR
, VARCHAR
, and TEXT
.
The CONCAT()
function returns a new string that results from concatenating the input strings.
Unlike the concatenation operator ||
, the CONCAT
function ignores NULL
arguments.
To concatenate two or more strings into one using a specified separator, you can use the CONCAT_WS() function.
PostgreSQL CONCAT() function examples
Let’s take some examples of using the PostgreSQL CONCAT()
function.
1) Basic PostgreSQL CONCAT() function example
The following example uses the CONCAT()
function to concatenate three literal strings into one:
Output:
2) Using the CONCAT() function with table data example
We’ll use the customer
table from the sample database:
The following statement uses the CONCAT()
function to concatenate values in the first_name
, a space, and values in the last_name
columns of the customer
table into a single string:
Output:
3) Using the CONCAT() function with NULL
First, create a table called contacts
and insert some rows into it:
Output:
Second, use the CONCAT()
function to concatenate the values in the name
, email
, and phone
columns of the contacts
table:
Output:
The output indicates that the CONCAT()
function ignores NULL
.
Summary
- Use the PostgreSQL
CONCAT()
function to concatenate two or more strings into one.