The AND and OR operators are used in SQL to filter data and produce precise results based on conditions. Multiple conditions can also be combined using the SQL AND & OR operators. In a SELECT, INSERT, UPDATE, or DELETE statement, these two operators can be combined to test for multiple conditions.
Note:
- It is critical to use parentheses when combining these conditions so that the database knows what order to evaluate each condition in.
- The AND and OR operators are used with the WHERE clause.
- These two operators are called conjunctive operators.
AND operator:
The AND is a logical operator that combines two Boolean expressions. It returns TRUE only when both expressions evaluate TRUE. This operator returns only records where all conditions evaluate to True.
Syntax:
SELECT * FROM table_name WHERE condition1 AND condition2 and ...conditionN;
Example:
Consider an Employee table:
Employee Name | Salary | Department ID |
Anne | 10000 | 90 |
David | 9000 | 80 |
John | 8000 | 70 |
George | 7000 | 70 |
In the given query we have used the AND operator to meet Salary and DepartmentID conditions. The output would only be generated if and only if both the conditions are true, otherwise, even if one of the conditions isn’t met, no output would be generated.
SELECT * FROM Employee WHERE Salary < 10000 AND Department ID > 70
Output:
Employee Name | Salary | Department ID |
David | 9000 | 80 |
OR operator:
In SQL, the OR operator is used to combine two or more conditions in a WHERE clause to display records where either one of the conditions is true.
Note: Any record that is in the resultset must satisfy at least one of the conditions specified.
Syntax:
SELECT * FROM table_name WHERE condition1 OR condition2 OR...conditionN;
Example:
Let us consider the same Employee table:
Employee Name | Salary | Department ID |
Anne | 10000 | 90 |
David | 9000 | 80 |
John | 8000 | 70 |
George | 7000 | 70 |
In the given query we have used the OR operator to meet either Salary or DepartmentID conditions. The output would be generated if any of the conditions are true, otherwise, even if all the conditions aren’t met, no output would be generated.
SELECT * FROM Employee WHERE Salary < 10000 OR Department ID > 70
Output:
Employee Name | Salary | Department ID |
Anne | 10000 | 90 |
David | 9000 | 80 |
John | 8000 | 70 |
George | 7000 | 70 |
Note: also read about SQL: DISTINCT keyword
Follow Me
Please follow me to read my latest post on programming and technology if you like my post.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Leave a Comment