Can we use WHERE, AND & OR in a single MySQL query?


Yes, we can use all of them in a single query. Let us first create a table −

mysql> create table DemoTable
   (
   StudentId int,
   StudentFirstName varchar(20),
   StudentLastName varchar(20),
   StudentAge int
   );
Query OK, 0 rows affected (0.53 sec)

Insert records in the table using insert command −

mysql> insert into DemoTable values(100,'John','Smith',23);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(101,'Carol','Taylor',24);
Query OK, 1 row affected (0.62 sec)
mysql> insert into DemoTable values(103,'John','Doe',22);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable values(104,'Adam','Smith',23);
Query OK, 1 row affected (0.18 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+------------------+-----------------+------------+
| StudentId | StudentFirstName | StudentLastName | StudentAge |
+-----------+------------------+-----------------+------------+
| 100       | John             | Smith           | 23         |
| 101       | Carol            | Taylor          | 24         |
| 103       | John             | Doe             | 22         |
| 104       | Adam             | Smith           | 23         |
+-----------+------------------+-----------------+------------+
4 rows in set (0.00 sec)

Following is the query to use MySQL WHERE, AND & OR in a single MySQL query to fetch records−

mysql> select *from DemoTable
where StudentFirstName='John' AND StudentLastName='Doe' OR StudentAge=26;

This will produce the following output −

+-----------+------------------+-----------------+------------+
| StudentId | StudentFirstName | StudentLastName | StudentAge |
+-----------+------------------+-----------------+------------+
| 103       | John             | Doe             | 22         |
+-----------+------------------+-----------------+------------+
1 row in set (0.00 sec)

Updated on: 30-Jul-2019

192 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements