Mysql concatenation operator
In MySQL, we use the CONCAT()
function to merge, or "concatenate", strings:
Which returns "Hello, World!".
If a string is NULL
, the result is NULL
. CONCAT_WS()
helps here -- it skips NULL
s and insists on a separator:
Voila! We have "2023-01", the NULL
disappearing like Houdini.
Mastering concatenation in MySQL: A deeper dive
When pipes aren't just pipes: setting sql_mode
Some SQL dialects use ||
for string concatenation, but MySQL sees it as logical OR
. The SQL mode PIPES_AS_CONCAT
can change this:
This swaps MySQL's thinking cap for an ANSI standard one, and ||
acts for string connection like Lego bricks.
Mixing and matching data types
Though its name implies stringiness, CONCAT()
can handle different data types, by automatically converting them into a lovely text string:
This transforms the integer 100
into string '100'
, and combines both, giving us a price tag: 'Price: $100'
. You're now a retailer (kinda 😇)!
Null Beware! Concat's hidden pitfalls
CONCAT()
sees a NULL
value as a party pooper, returning NULL
. Luckily, CONCAT_WS()
is more forgiving, skipping NULL
values:
This gets us 'First Last'
. The NULL
has left the building!
Maintain peak Performance
Proper usage of CONCAT()
will keep your SQL running faster than Usain Bolt. Overuse, especially in loops or huge queries, may slow it down more than a sleepy sloth. Be wary!
Proper Alias: Be a SQL superhero
Adding an alias to your CONCAT()
output is like putting a label -- it makes your SQL results easier to comprehend and debug:
This part just makes it clear that fullName
is the splendid union of firstName
and lastName
!
Navigating SQL dialects: Beware of differences
Worlds collide when SQL syntax differs across platforms. For instance, MS SQL Server laughs at ||
for string concatenation, using the +
operator instead, like a mathematical rebel. So, remember to use the desired syntax based on your SQL playground!
Was this article helpful?