Fetch the first letter of a column value and insert it in another column with MySQL

MySQLMySQLi Database

For this, use the concept of LEFT() function. Let us first create a table −

mysql> create table DemoTable2036
   -> (
   -> FirstLetter varchar(20),
   -> Title varchar(20)
   -> );
Query OK, 0 rows affected (1.01 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable2036(Title) values('Chris');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable2036(Title) values('John');
Query OK, 1 row affected (0.10 sec)

mysql> insert into DemoTable2036(Title) values('Adam');
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable2036;

This will produce the following output −

+-------------+-------+
| FirstLetter | Title |
+-------------+-------+
| NULL        | Chris |
| NULL        | John  |
| NULL        | Adam  |
+-------------+-------+
3 rows in set (0.00 sec)

Following is the query to fetch the first letter of a column value and place it to another column −

mysql> update DemoTable2036
   -> set FirstLetter=left(Title,1);
Query OK, 3 rows affected (0.23 sec)
Rows matched: 3 Changed: 3 Warnings: 0

Let us check the table records once again −

mysql> select *from DemoTable2036;

This will produce the following output −

+-------------+-------+
| FirstLetter | Title |
+-------------+-------+
| C           | Chris |
| J           | John  |
| A           | Adam  |
+-------------+-------+
3 rows in set (0.00 sec)
raja
Published on 07-Apr-2020 15:09:57
Advertisements