In PostgreSQL, I want to use an SQL statement to combine two columns and create a new column from them.
I’m thinking about using concat(...), but is there a better way?
What’s the best way to do this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Generally, I agree with @kgrittn’s advice. Go for it.
But to address your basic question about
concat(): it is useful if you need to deal with null values – and null has neither been ruled out in your question nor in the one you refer to.If you can rule out null values, the good old (SQL standard) concatenation operator
||is still the best choice, and @luis’ answer is just fine:If either of your columns can be null, the result would be null in that case. You could defend with
COALESCE:But that gets tedious quickly with more arguments. That’s where
concat()comes in, which never returns null, not even if all arguments are null. The manual:The remaining corner case for both alternatives is where all input columns are null in which case we still get an empty string
''. To get null instead:This gets more complex with more columns quickly. Again, use
concat(), but add a check for the special condition:How does this work?
(col_a, col_b)is shorthand forROW (col_a, col_b). And a row type is only null if all columns are null. Detailed explanation:Also, use
concat_ws()to add separators between elements (wsfor "with separator").An expression like the one in Kevin’s answer:
is tedious to prepare for null values in PostgreSQL 8.3 (without
concat()). One way (of many):Function volatility is only
STABLEconcat()andconcat_ws()areSTABLEfunctions, notIMMUTABLEbecause they can invoke datatype output functions (liketimestamptz_out) that depend on locale settings.Explanation by Tom Lane.
This prohibits their direct use in index expressions. If you know that the result is actually immutable in your case, you can work around this with an
IMMUTABLEfunction wrapper. Example here: