w3resource

Concatenating Strings in PostgreSQL: ||, CONCAT, and CONCAT_WS


Concatenating Strings in PostgreSQL

In PostgreSQL, you can concatenate strings to combine text values from one or more columns or add literal strings to column values. PostgreSQL offers multiple ways to perform string concatenation, including using the || operator, the CONCAT function, and CONCAT_WS for strings with separators.

Description

String concatenation in PostgreSQL allows you to join two or more text strings together. This is useful for creating full names from first and last name columns, constructing addresses, or appending additional information to existing text fields.

Syntax:

There are three main ways to concatenate strings in PostgreSQL:

Using the || operator:

column1 || column2 || 'some text'

Using the CONCAT function:

CONCAT(column1, column2, 'some text')

Using the CONCAT_WS function (concatenation with separator):

CONCAT_WS('separator', column1, column2, 'some text')

Example:

Using the || Operator

Code:

-- Concatenate first and last name columns with a space in between
SELECT first_name || ' ' || last_name AS full_name
FROM employees;

Explanation:

  • first_name || ' ' || last_name: Joins first_name and last_name columns with a space between them.
  • AS full_name: Renames the concatenated result to full_name.

Using the CONCAT Function

Code:

-- Concatenate strings with the CONCAT function
SELECT CONCAT(first_name, ' ', last_name) AS full_name
FROM employees;

Explanation:

  • CONCAT(first_name, ' ', last_name): Joins first_name and last_name with a space between them.
  • AS full_name: Renames the output as full_name.

Using the CONCAT_WS Function

Code:

-- Concatenate strings with a comma separator
SELECT CONCAT_WS(', ', city, state, country) AS location
FROM addresses;

Explanation:

  • CONCAT_WS(', ', city, state, country): Concatenates city, state, and country with a comma and space as a separator.
  • AS location: Renames the result as location.

Tips:

  • || Operator vs. CONCAT: The || operator is a straightforward way to concatenate without function calls. The CONCAT function, however, is more flexible as it handles NULL values and multiple arguments gracefully.
  • CONCAT_WS: Use CONCAT_WS when you need a specific separator between each value, which helps maintain formatting without extra code.

All PostgreSQL Questions, Answers, and Code Snippets Collection.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/PostgreSQL/snippets/postgresql-string-concat.php