Update a table in MySQL and display only the initials name in a new column

MySQLMySQLi Database

To get the initial, use the concept of left() along with substring_index().

Let us create a table −

mysql> create table demo13
−> (
−> full_name varchar(100),
−> short_name varchar(20)
−> );
Query OK, 0 rows affected (1.18 sec)

Insert some records into the table with the help of insert command −

mysql> insert into demo13(full_name) values('John Smith');
Query OK, 1 row affected (0.27 sec)

mysql> insert into demo13(full_name) values('David Miller');
Query OK, 1 row affected (0.13 sec)

mysql> insert into demo13(full_name) values('Chris Brown');
Query OK, 1 row affected (0.28 sec)

Display records from the table using select statement −

mysql> select *from demo13;

This will produce the following output −

+--------------+------------+
| full_name    | short_name |
+--------------+------------+
| John Smith   | NULL       |
| David Miller | NULL       |
| Chris Brown  | NULL       |
+--------------+------------+
3 rows in set (0.00 sec)

Following is the query to update table and get the initials name −

mysql> update demo13
−> set short_name= concat(
−> left(full_name, 1),
−> left(substring_index(full_name, ' ', −1), 1)
−> );
Query OK, 3 rows affected (0.14 sec)
Rows matched: 3 Changed: 3 Warnings: 0

Display records from the table using select statement −

mysql> select *from demo13;

This will produce the following output −

+--------------+------------+
| full_name    | short_name |
+--------------+------------+
| John Smith   | JS         |
| David Miller | DM         |
| Chris Brown  | CB         |
+--------------+------------+
3 rows in set (0.00 sec)
raja
Published on 19-Nov-2020 15:46:54
Advertisements