Write a query to update the value of a column using concatenation
Description: Change the name of every student into the form “Name (City)”. Do it on a copy of the table.
Tables: the exercises use the students (id, name, city, marks, course_id) and courses (id, course_name) tables, with the data from our MySQL INSERT chapter. The students are: Robin (Delhi, 85), Maria (Mumbai, 92), John (Pune, 78), Asha (Jaipur, 88), Vikram (Delhi, 65), Neha (Mumbai, 45).
Hint:
- Make a copy of the table first, so the original data stays safe.
- Use
UPDATE ... SET name = CONCAT(...).
MySQL query to update a column with CONCAT
CREATE TABLE students_copy AS SELECT * FROM students;
UPDATE students_copy
SET name = CONCAT(name, ' (', city, ')');
SELECT id, name FROM students_copy LIMIT 3;
Output:
Tutorials Class - Output Window
| id | name |
|---|---|
| 1 | Robin (Delhi) |
| 2 | Maria (Mumbai) |
| 3 | John (Pune) |
How it works
CONCAT()joins the old name, a space, the city in brackets.- Because we used a copy, the real
studentstable is not changed. Remove the copy withDROP TABLE students_copy;.
Read String Functions.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |