Mysql SELECT AS combine two columns into one
Here is how to combine columns col1
and col2
into combined_col
using CONCAT()
:
And here is how to do that with a separator while skipping NULL values with CONCAT_WS()
:
Handling pesky data types and NULL values
Be alert when dealing with incompatible data types. Here's how you can concatenate a numeric and a string column by casting:
Beware of length overflows to avoid getting cut off:
When it comes to NULLs,CONCAT_WS()
skips them while CONCAT()
yields NULL if any argument is NULL:
Picking an alias like choosing your superhero name
An alias makes it simple to identify our new combined column. Look at this example of using meaningful alias:
This can be a lifesaver when exporting data to CSV files (AKA 'The Spreadsheet Gotham').
Wrangling with sweet and sour scenarios
Sometimes, you'll meet two columns that might be NULL, or you may need to work with date and time types:
- If both columns might be NULL, take
IFNULL()
. It's like getting a guaranteed lucky draw:
- To mix date and time columns into a single timestamp, use this approach:
- Combining multilingual data? Pay attention to character encoding:
Was this article helpful?