coderz.py

Keep Coding Keep Cheering!

SQL: AND & OR operators

SQL Views

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 NameSalaryDepartment ID
Anne1000090
David900080
John800070
George700070

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 NameSalaryDepartment ID
David900080
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 NameSalaryDepartment ID
Anne1000090
David900080
John800070
George700070

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 NameSalaryDepartment ID
Anne1000090
David900080
John800070
George700070

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

Leave a Comment

Your email address will not be published. Required fields are marked *

Advertisement