Display selected records from a MySQL table with IN() operator

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   CustomerName varchar(100)
);
Query OK, 0 rows affected (0.51 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(CustomerName) values('Adam Smith');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(CustomerName) values('Chris Brown');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(CustomerName) values('David Miller');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(CustomerName) values('Carol Taylot');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(CustomerName) values('Carol Taylor');
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+--------------+
| Id | CustomerName |
+----+--------------+
| 1 | Adam Smith    |
| 2 | Chris Brown   |
| 3 | David Miller  |
| 5 | Carol Taylor  |
+----+--------------+
4 rows in set (0.00 sec)

Following is the query to display selected records using IN operator −

mysql> select *from DemoTable where Id IN(2,5);

This will produce the following output −

+----+--------------+
| Id | CustomerName |
+----+--------------+
|  2 | Chris Brown  |
|  5 | Carol Taylor |
+----+--------------+
2 rows in set (0.00 sec)
raja
Published on 03-Sep-2019 13:52:06
Advertisements