Home > Database > Mysql Tutorial > How to Concatenate String Columns in PostgreSQL SELECT Queries?

How to Concatenate String Columns in PostgreSQL SELECT Queries?

Linda Hamilton
Release: 2025-01-12 10:28:43
Original
575 people have browsed it

How to Concatenate String Columns in PostgreSQL SELECT Queries?

Concatenate string columns in PostgreSQL SELECT query

In PostgreSQL, concatenating string columns directly in a SELECT query is not trivial. Consider the following example:

select a || b from foo;
Copy after login

Where a and b are columns of character(2) type. This will return NULL instead of the expected concatenation of the a and b values.

The simplest solution for concatenating string columns is to cast at least one column to type text:

SELECT a::text || b AS ab FROM foo;
Copy after login

Alternatively, you can use the concat_ws() function, which accepts any number of arguments and ignores NULL values:

SELECT concat_ws(', ', a, b) AS ab FROM foo;
Copy after login

If you don't need separators, you can use the concat() function:

SELECT concat(a, b) AS ab FROM foo;
Copy after login

concat() and concat_ws() are both volatile functions and therefore not suitable for use in indexed or generated columns. If immutability is required, you can create a custom immutable function.

Please note that the operator is not a valid string concatenation operator in Postgres. It is a unique addition by Microsoft to its products.

The above is the detailed content of How to Concatenate String Columns in PostgreSQL SELECT Queries?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template