Passing an array to a query using WHERE clause in MySQL?


We can pass an array with the help of where IN clause. Let us first create a new table for our example.

mysql> create table PassingAnArrayDemo
   -> (
   -> id int,
   -> Firstname varchar(100)
   -> );
Query OK, 0 rows affected (1.60 sec)

Let us now insert records.

mysql> insert into PassingAnArrayDemo values(1,'John'),(2,'Carol'),(3,'Smith'),(4,'Bob'),(5,'Johnson'),(6,'David'),(7,'Sam'),(8,'Jessica');
Query OK, 8 rows affected (0.32 sec)
Records: 8  Duplicates: 0  Warnings: 0

To display all records.

mysql> select *from PassingAnArrayDemo;

The following is the output.

+------+-----------+
| id   | Firstname |
+------+-----------+
|    1 | John      |
|    2 | Carol     |
|    3 | Smith     |
|    4 | Bob       |
|    5 | Johnson   |
|    6 | David     |
|    7 | Sam       |
|    8 | Jessica   |
+------+-----------+
8 rows in set (0.00 sec)

The following is the syntax to send an array parameter with the help of where IN clause.

mysql> SELECT *
   -> FROM PassingAnArrayDemo where id IN(1,3,6);

The following is the output.

+------+-----------+
| id   | Firstname |
+------+-----------+
|    1 | John      |
|    3 | Smith     |
|    6 | David     |
+------+-----------+
3 rows in set (0.04 sec)

Updated on: 30-Jul-2019

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements