Introduction
Use CONCAT and CONCAT_WS to join multiple pieces of text into one string. This helps combine names, addresses, or any text parts easily.
CONCAT(string1, string2, ...) CONCAT_WS(separator, string1, string2, ...)
SELECT CONCAT('Hello', ' ', 'World');
SELECT CONCAT_WS('-', '2024', '06', '15');
SELECT CONCAT('Name: ', first_name, ' ', last_name) FROM users;
SELECT CONCAT_WS(', ', city, state, zip) FROM addresses;
CREATE TABLE people ( first_name VARCHAR(20), last_name VARCHAR(20), city VARCHAR(30), state VARCHAR(20) ); INSERT INTO people VALUES ('John', 'Doe', 'New York', 'NY'), ('Jane', 'Smith', 'Los Angeles', 'CA'); SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM people; SELECT CONCAT_WS(', ', city, state) AS location FROM people;
CONCAT and CONCAT_WS in MySQL?CONCAT behaviorCONCAT joins strings directly but returns NULL if any input is NULL.CONCAT_WS behaviorCONCAT_WS joins strings with a separator and ignores NULL values instead of returning NULL.CONCAT returns NULL if any argument is NULL; CONCAT_WS skips NULLs and uses a separator. -> Option ACONCAT returns NULL if any argument is NULL; CONCAT_WS skips NULLs and uses a separator. [OK]CONCAT_WS?CONCAT_WS syntaxCONCAT_WS takes the separator as the first argument, then the strings to join.users with columns first_name, middle_name, and last_name, what is the output of this query?SELECT CONCAT_WS(' ', first_name, middle_name, last_name) AS full_name FROM users WHERE id = 1;id=1 has first_name='John', middle_name=NULL, and last_name='Doe'.CONCAT_WS with NULL valuesCONCAT_WS skips NULL values and joins remaining strings with the separator.middle_name is NULL, it is skipped. The result joins 'John' and 'Doe' with a space.SELECT CONCAT('Name: ', first_name, middle_name, last_name) AS full_name FROM users;CONCAT returns NULL if any argument is NULL.CONCAT on columns that may contain NULL, so the entire result for full_name will be NULL if any column is NULL.street, city, and zipcode in a table, separated by commas. Some rows have NULL in zipcode. Which query correctly creates the address without extra commas for NULL values?CONCAT_WS joins strings with a separator and skips NULL values, avoiding extra separators.CONCAT_WS with ', ' separator and all columns, so NULL zipcode is skipped without extra commas. SELECT CONCAT(street, ', ', city, ', ', zipcode) AS full_address FROM addresses; uses CONCAT which returns NULL if any argument is NULL, causing missing addresses. SELECT CONCAT_WS(', ', street, city) || ', ' || zipcode AS full_address FROM addresses; uses invalid syntax with || operator in MySQL. SELECT CONCAT(street, city, zipcode) AS full_address FROM addresses; concatenates without separators and returns NULL if any NULL present.Pass the test and this pattern moves unknown