Display records where first and last name begins with the same letter in MySQL


To check for the 1st letter of the first and last name, you need to use the LEFT().

Let us first create a table −

mysql> create table DemoTable789 (
   FirstName varchar(100),
   LastName varchar(100)
);
Query OK, 0 rows affected (0.78 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable789 values('Adam','Smith');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable789 values('Tom','Taylor');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable789 values('Bob','Brown');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable789 values('David','Miller');
Query OK, 1 row affected (0.22 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable789;

This will produce the following output -

+-----------+----------+
| FirstName | LastName |
+-----------+----------+
| Adam      | Smith    |
| Tom       | Taylor   |
| Bob       | Brown    |
| David     | Miller   |
+-----------+----------+
4 rows in set (0.00 sec)

Display records where first and last name begins with the same letter in MySQL −

mysql> select *from DemoTable789 where upper(left(FirstName,1))=upper(left(LastName,1));

This will produce the following output -

+-----------+----------+
| FirstName | LastName |
+-----------+----------+
| Tom       | Taylor   |
| Bob       | Brown    |
+-----------+----------+
2 rows in set (0.00 sec)
raja
Published on 09-Sep-2019 12:08:59
Advertisements