Fetch a specific record using a single MySQL query with AND & OR operator


Let us first create a table −

mysql> create table DemoTable2015
   -> (
   -> StudentId int,
   -> StudentName varchar(20),
   -> StudentCountryName varchar(20)
   -> );
Query OK, 0 rows affected (1.20 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable2015 values(1,'Chris','US');
Query OK, 1 row affected (0.23 sec)

mysql> insert into DemoTable2015 values(2,'Bob','UK');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable2015 values(3,'David','AUS');
Query OK, 1 row affected (0.11 sec)

mysql> insert into DemoTable2015 values(4,'Robert','US');
Query OK, 1 row affected (0.16 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable2015;

This will produce the following output −

+-----------+-------------+--------------------+
| StudentId | StudentName | StudentCountryName |
+-----------+-------------+--------------------+
| 1         | Chris       | US                 |
| 2         | Bob         | UK                 |
| 3         | David       | AUS                |
| 4         | Robert      | US                 |
+-----------+-------------+--------------------+
4 rows in set (0.00 sec)

Here is the query to fetch a specific record with a single query −

mysql> select *from DemoTable2015
   -> where StudentName='David' OR StudentCountryName='UK' and StudentId=3;

This will produce the following output −

+-----------+-------------+--------------------+
| StudentId | StudentName | StudentCountryName |
+-----------+-------------+--------------------+
| 3         | David       | AUS                |
+-----------+-------------+--------------------+
1 row in set (0.00 sec)

Updated on: 06-Apr-2020

100 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements