Skip to main content
Documents
Basic SyntaxMath FunctionsDate FunctionsJSON FunctionsDatabasesTables & Schema ManagementString FunctionsTriggersIndexes

PostgreSQL CONCAT

The `CONCAT` string function in PostgreSQL is used to concatenate two or more strings into a single string. It simplifies combining multiple text values or columns into a cohesive result.

Usage

The `CONCAT` function is employed when you need to merge strings or columns, often in situations where a full name or a complete address is required. It accepts a variable number of string arguments and returns a single concatenated string. The `CONCAT` function is available from PostgreSQL 9.1 onwards.

CONCAT(string1, string2, ..., stringN);

Here, each `string` argument represents a value or column to be joined into a single string.

Examples

1. Basic Concatenation

SELECT CONCAT('Hello', ' ', 'World!');

This example combines the strings into "Hello World!", illustrating the basic use of the function.

2. Concatenating Columns

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

This syntax concatenates the `first_name` and `last_name` columns with a space in between, generating a full name for each record in the `employees` table.

3. Concatenating with Mixed Types

SELECT CONCAT('Order ID: ', order_id, ' - ', 'Amount: ', amount::text) AS order_details FROM orders;

In this example, string literals are combined with integer and numeric columns, demonstrating the ability to concatenate mixed data types. The `amount` is cast to text using `::text`. Type casting in PostgreSQL can be done using `::type`, which converts a value to a specified type, such as `text`.

Tips and Best Practices

  • Use casting where necessary. Ensure non-string values are cast to text to avoid errors when using `CONCAT`.
  • Avoid using `+` for string concatenation. In PostgreSQL, always use `CONCAT` or `||` to concatenate strings.
  • Handle NULL values carefully. `CONCAT` treats `NULL` as an empty string, so ensure this behavior aligns with your data requirements.
  • Consider performance on large datasets. While `CONCAT` is efficient, avoid excessive concatenation operations on large datasets to maintain performance.