How to prepend a string to a column value in MySQL?

MySQLMySQLi Database

To prepend a string to a column value in MySQL, we can use the function CONCAT. The CONCAT function can be used with UPDATE statement.

Creating a table.

mysql> create table PrependStringOnCOlumnName
   -> (
   -> Id int,
   -> Name varchar(200)
   -> );
Query OK, 0 rows affected (1.35 sec)

Inserting some records.

mysql> insert into PrependStringOnCOlumnName values(1,'John');
Query OK, 1 row affected (0.12 sec)

mysql> insert into PrependStringOnCOlumnName values(2,'Carol');
Query OK, 1 row affected (0.18 sec)

mysql> insert into PrependStringOnCOlumnName values(3,'Johnson');
Query OK, 1 row affected (0.45 sec)

Displaying all the records.

mysql> select *from PrependStringOnCOlumnName;

The following is the output.

+------+---------+
| Id   | Name    |
+------+---------+
|    1 | John    |
|    2 | Carol   |
|    3 | Johnson |
+------+---------+
3 rows in set (0.00 sec)

Syntax to prepend a string to column value.

UPDATE yourTableName SET yourColumnName = CONCAT(Value,yourColumnName);

Applying the above query to prepend a string ‘First’ to a column ‘Name’

mysql> UPDATE PrependStringOnCOlumnName SET Name=CONCAT('First',Name);
Query OK, 3 rows affected (0.13 sec)
Rows matched: 3  Changed: 3  Warnings: 0

Let us check what we did above.

mysql> select *from PrependStringOnCOlumnName;

The following is the output that displays we have successfully concatenated a string to column value.

+------+--------------+
| Id   | Name         |
+------+--------------+
|    1 | FirstJohn    |
|    2 | FirstCarol   |
|    3 | FirstJohnson |
+------+--------------+
3 rows in set (0.00 sec)
raja
Published on 29-Nov-2018 05:57:37
Advertisements