Filter column value by the first character in MySQL

MySQLMySQLi Database

You can use LEFT() from MySQL. Let us first create a −

mysql> create table DemoTable1428
   -> (
   -> EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> EmployeeName varchar(20)
   -> );
Query OK, 0 rows affected (1.05 sec)

Insert some records in the table using insert −

mysql> insert into DemoTable1428(EmployeeName) values('Chris Brown');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1428(EmployeeName) values('Bob Brown');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1428(EmployeeName) values('John Smith');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable1428(EmployeeName) values('David Miller');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1428(EmployeeName) values('John Doe');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable1428(EmployeeName) values('Carol Johnson');
Query OK, 1 row affected (0.16 sec)

Display all records from the table using select −

mysql> select * from DemoTable1428;

This will produce the following output −

+------------+---------------+
| EmployeeId | EmployeeName  |
+------------+---------------+
|          1 | Chris Brown   |
|          2 | Bob Brown     |
|          3 | John Smith    |
|          4 | David Miller  |
|          5 | John Doe      |
|          6 | Carol Johnson |
+------------+---------------+
6 rows in set (0.00 sec)

Following is the query to filter column value by the first character −

mysql> select * from DemoTable1428 where left(EmployeeName,1)='J';

This will produce the following output −

+------------+--------------+
| EmployeeId | EmployeeName |
+------------+--------------+
|          3 | John Smith   |
|          5 | John Doe     |
+------------+--------------+
2 rows in set (0.00 sec)
raja
Published on 12-Nov-2019 06:21:32
Advertisements