PostgreSQL CONCAT
Function
The CONCAT
function in PostgreSQL is used to combine multiple strings into one. It automatically handles NULL
values by treating them as empty strings (''
).
1. Basic Syntax
- Accepts multiple string arguments.
- Returns a single concatenated string.
Example: Simple Concatenation
✅ Output: 'Hello World'
2. Concatenating Table Columns
You can concatenate columns from a table.
Example: Combine First and Last Name
✅ Output:
first_name | last_name | full_name |
---|---|---|
John | Doe | John Doe |
Jane | Smith | Jane Smith |
3. Handling NULL
Values
CONCAT
treatsNULL
as an empty string (''
).- Use
CONCAT_WS
(explained later) if you want to ignoreNULL
values.
Example: NULL
Handling
✅ Output: 'User: Active'
(NULL is treated as ''
)
4. Using ||
(Alternative String Concatenation)
PostgreSQL allows ||
as a shorthand for CONCAT
.
✅ Output: 'Hello World'
Example: Concatenating Columns
✅ Works the same as CONCAT
but returns NULL
if any column is NULL
.
5. Using CONCAT_WS
(Concatenation with Separator)
CONCAT_WS(separator, string1, string2, ...)
- Ignores
NULL
values (useful when some columns may beNULL
).
Example: Join Name with Comma
✅ Output:
first_name | middle_name | last_name | full_name |
---|---|---|---|
John | A. | Doe | John, A., Doe |
Jane | NULL | Smith | Jane, Smith |
🔹 Unlike CONCAT
, NULL
values are ignored!
6. Concatenating Numbers and Dates
PostgreSQL automatically converts numbers and dates to text when using CONCAT
.
Example: Concatenating Numbers
✅ Output: 'Order #123 - Total: $49.99'
Example: Concatenating Dates
✅ Output: 'Today is 2025-02-01'
(example date)
7. Concatenating with GROUP BY
(List Aggregation)
To concatenate multiple row values into a single string, use STRING_AGG()
.
Example: List Employee Names in One Row
✅ Output: 'John, Jane, Alice, Bob'
8. Summary
Use Case | Query | Notes |
---|---|---|
Basic Concatenation | SELECT CONCAT('Hello', ' ', 'World'); | 'Hello World' |
Concatenating Columns | SELECT CONCAT(first_name, ' ', last_name) FROM employees; | Joins name columns |
Handling NULLs | SELECT CONCAT('User: ', NULL, ' Active'); | NULL treated as '' |
**Alternative (` | `)** | |
Using Separator (CONCAT_WS ) | SELECT CONCAT_WS(', ', first_name, middle_name, last_name); | Ignores NULL values |
Concatenating Numbers/Dates | SELECT CONCAT('Order #', 123, ' - ', CURRENT_DATE); | Automatically converts numbers and dates |
Group Concatenation | SELECT STRING_AGG(first_name, ', ') FROM employees; | Merges multiple rows into one |
Would you like examples for a specific use case? 🚀