Explain Codes LogoExplain Codes Logo

Sql UPDATE all values in a field with appended string CONCAT not working

sql
null-values
concat-function
mysql-quirks
Nikita BarsukovbyNikita Barsukov·Oct 12, 2024
TLDR

Update all rows in a column to suffix a string using:

UPDATE table_name SET column_name = CONCAT(column_name, 'append_string');

Make sure table_name and column_name match your schema. This command appends 'append_string' to the current value of column_name.

NULL values handling: IFNULL vs COALESCE

Handling NULL values is crucial. Sounds scary? Not really, just use:

UPDATE table_name SET column_name = IFNULL(CONCAT(column_name, 'append_string'), 'append_string');

But there’s more than one way to skin a NULL! Try COALESCE() for the same result:

UPDATE table_name SET column_name = COALESCE(CONCAT(column_name, 'append_string'), 'append_string');

Feel the power, yet? That's how you battle the NULLs on the field! ⚔️

Verify MySQL version

Fully qualified column names, table_name.column_name, may be needed for MySQL 4.1:

UPDATE table_name SET table_name.column_name = CONCAT(table_name.column_name, 'append_string');

Yeah, you read it right, twice the table name, it's not a typo! MySQL has its strange quirks for version compatibility. 😉

Error-checking: Look out for warnings

Sure enough, we've got you covered with error debugging:

SHOW WARNINGS;

Just like a mother-in-law visit, always be prepared for warnings. But unlike mother-in-law visits, MySQL warnings can be helpful (no offense to all the amazing mothers-in-law out there)! 👀

Alternatives: CONCAT_WS

No joy with CONCAT? Meet CONCAT_WS, CONCAT's cool cousin:

UPDATE table_name SET column_name = CONCAT_WS('', column_name, 'append_string');

Empty string '' as the separator spaces out appendix directly. Trust CONCAT_WS, this one's a lifesaver in the field.

RDBMS Cross-compatibility

Universal SQL fan? Know your syntax with PostgreSQL and Oracle. Some things are universal, like love or pizza, but sadly SQL syntax is not. 😄