Remove all except the first character of a string in MySQL?


For this, use the LEFT() method, which returns a specified number of characters from the left of the string.

Let us first create a table −

mysql> create table DemoTable
   -> (
   -> FirstName varchar(100)
   -> );
Query OK, 0 rows affected (0.96 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Sam');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable values('Mike');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable values('David');
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+
| FirstName |
+-----------+
| Sam       |
| Mike      |
| David     |
+-----------+
3 rows in set (0.00 sec)

Following is the query to remove all except the first character of a string −

mysql> update DemoTable set FirstName=left(FirstName,1);
Query OK, 3 rows affected (0.13 sec)
Rows matched: 3 Changed: 3 Warnings: 0

Let us check the table records once again −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+
| FirstName |
+-----------+
|         S |
|         M |
|         D |
+-----------+
3 rows in set (0.00 sec)
raja
Published on 11-Jul-2019 16:33:54
Advertisements