SQL AND & OR
AND OR - SQL Operators :
- AND & OR operators are used to select records based based on more than one condition.
- SQL AND operator displays a record if both the first condition AND the second condition are true.
- SQL OR operator displays a record if either the first condition OR the second condition is true.
| Operator | Condition 1 | Condition 2 | Record Selected |
|---|---|---|---|
| AND | true | true | Record is Selected |
| AND | false | true | Record is not Selected |
| AND | true | false | Record is not Selected |
| AND | false | false | Record is not Selected |
| OR | true | true | Record is Selected |
| OR | false | true | Record is Selected |
| OR | true | false | Record is Selected |
| OR | false | false | Record is not Selected |
Demo Example
Consider following “CUSTOMER” table -
| ID | NAME | AGE | ADDRESS | SALARY |
|---|---|---|---|---|
| 1 | Raj | 20 | Pune | 1000.00 |
| 2 | Saurabh | 20 | Pune | 6000.00 |
| 3 | Omkar | 24 | Mumbai | 4000.00 |
| 4 | Anand | 23 | Pune | 3000.00 |
| 5 | Anmol | 29 | Pune | 1000.00 |
| 6 | Poonam | 25 | Delhi | 9000.00 |
AND Operator :
Suppose we need to select all the customers that are living in Pune and having customer id greater than or equal to 2 then we can write below query -
SQL> Select * from CUSTOMER where ID >=2 AND CITY = 'PUNE'
Above query will provide you following records
| ID | NAME | AGE | ADDRESS | SALARY |
|---|---|---|---|---|
| 2 | Saurabh | 20 | Pune | 6000.00 |
| 4 | Anand | 23 | Pune | 3000.00 |
| 5 | Anmol | 29 | Pune | 1000.00 |
OR Operator :
We need to select all the customers that are living in Pune or having their age greater than 23 then Consider the below query -
SQL> Select * from CUSTOMER where CITY = 'PUNE' OR AGE > 23
Query will provide you following result -
| ID | NAME | AGE | ADDRESS | SALARY |
|---|---|---|---|---|
| 1 | Raj | 20 | Pune | 1000.00 |
| 2 | Saurabh | 20 | Pune | 6000.00 |
| 3 | Omkar | 24 | Mumbai | 4000.00 |
| 4 | Anand | 23 | Pune | 3000.00 |
| 5 | Anmol | 29 | Pune | 1000.00 |
| 6 | Poonam | 25 | Delhi | 9000.00 |
