How can I achieve similar result like using a loop in MySQL WHERE clause to display only alternate ID records?


Get similar results using MySQL IN(). Let us first create a table −

mysql> create table DemoTable
(
   ClientId int,
   ClientName varchar(100),
   ClientAge int
);
Query OK, 0 rows affected (0.70 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(100,'Chris',34);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values(101,'Robert',31);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(103,'David',33);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values(104,'Mike',45);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(105,'Sam',39);
Query OK, 1 row affected (0.09 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----------+------------+-----------+
| ClientId | ClientName | ClientAge |
+----------+------------+-----------+
|      100 | Chris      |        34 |
|      101 | Robert     |        31 |
|      103 | David      |        33 |
|      104 | Mike       |        45 |
|      105 | Sam        |        39 |
+----------+------------+-----------+
5 rows in set (0.00 sec)

Following is the query to get similar results like a loop using MySQL IN() −

mysql> select ClientId,ClientName,ClientAge from DemoTable
where ClientId IN(101,103,105);

This will produce the following output −

+----------+------------+-----------+
| ClientId | ClientName | ClientAge |
+----------+------------+-----------+
|      101 | Robert     |        31 |
|      103 | David      |        33 |
|      105 | Sam        |        39 |
+----------+------------+-----------+
3 rows in set (0.00 sec)

Updated on: 26-Sep-2019

87 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements