MySQL query to find a match and fetch records


To find a match from records, use MySQL IN(). Let us first create a table −

mysql> create table DemoTable
(
   Id int,
   FirstName varchar(20),
   Gender ENUM('Male','Female')
);
Query OK, 0 rows affected (1.73 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(1,'Chris','Male');
Query OK, 1 row affected (0.47 sec)
mysql> insert into DemoTable values(10,'Emma','Female');
Query OK, 1 row affected (1.88 sec)
mysql> insert into DemoTable values(9,'Emma','Male');
Query OK, 1 row affected (0.70 sec)
mysql> insert into DemoTable values(11,'Isabella','Female');
Query OK, 1 row affected (0.46 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+------+-----------+--------+
| Id   | FirstName | Gender |
+------+-----------+--------+
|    1 | Chris     | Male   |
|   10 | Emma      | Female |
|    9 | Emma      | Male   |
|   11 | Isabella  | Female |
+------+-----------+--------+
4 rows in set (0.00 sec)

Following is the query to find match and fetch records with Id 1 and 11 −

mysql> select *from DemoTable where Id IN(1,11);

This will produce the following output −

+------+-----------+--------+
| Id   | FirstName | Gender |
+------+-----------+--------+
|    1 | Chris     | Male   |
|   11 | Isabella  | Female |
+------+-----------+--------+
2 rows in set (0.00 sec)
raja
Published on 09-Oct-2019 15:42:17
Advertisements