SQL Logical Operators
Sometimes there is required to match multiple conditions/relational expressions in where clause. To handle such type of situation such like of many high level languages SQL also provide logical operators. These operators are AND, OR and NOT.
In all below examples the employee table is used, which is defined in SQL select statement explanation.
SQL AND operator
AND operator results TRUE if both provided relational expressions are TRUE. If any of these is FALSE then result will also FALSE.
Syntax
SELECT *| list_of_columns FROM table_name WHERE condition_1 AND condition_2 ...... AND condition_n;
Example
If we want to fetch record of employee whose blood group is A+ and name is Jack then the SQL query will be as below.
SELECT * FROM employee WHERE `name` = "Jack" AND `blood_group` = "A+";
Output
SQL OR Operator
OR operator behave reciprocal to the AND operator. It means it will return FALSE if both provided conditions are FALSE, otherwise return TRUE if any one results im TRUE.
Syntax
SELECT *| list_of_columns FROM table_name WHERE condition_1 OR condition_2 ...... AND condition_n;
Example
Similar to above said example of AND operator, we can chanege it with OR operator. Then the result of query will include both results having either blood group A+ or O- or may any other.
SELECT * FROM employee WHERE `name` = "Jack" OR `blood_group` = "A+";
Output
id | name | dob | city | phone | blood_group |
1 | Jack | 1989-04-12 | New York | +155345342 | A+ |
5 | Jack | 2002-03-24 | Portland | +133390232 | O- |
SQL NOT operator
NOT results TRUE if the result is FALSE and similarly returns FALSE if result of expression is TRUE. It always invert the result of condition in where clause.
Syntax
SELECT *| list_of_columns FROM table_name WHERE NOT condition;
Example
If we want to display all records of employee excluding the name as Jack then NOT operator can be used.
SELECT * FROM employee WHERE NOT `name` = "Jack";
Output
id | name | dob | city | phone | blood_group |
2 | Milton | 1988-02-01 | Los Angeles | +154380323 | AB- |
3 | Devan | 1999-07-04 | Chicago | +124342321 | O+ |
4 | James | 1972-08-21 | Houston | +112340655 | B+ |
SQL Multiple Logical Operators
Sometimes there is need to use combination of all these logical operators in a single query. For this purpose we can group our relational expressions/conditions using small parentheses. Then SQL will evaluate results according to precedence of operators.
Example
SELECT * FROM employee WHERE NOT `name` = "Jack" AND `blood_group` = "O+";
id | name | dob | city | phone | blood_group |
3 | Devan | 1999-07-04 | Chicago | +124342321 | O+ |