Hey time travellers,
In this article, we will be discussing Logical Conditions. It is a very important aspect of SQL. It helps us to combine the results of two component conditions to produce a single result. In simple words we can say, it helps us to apply multiple conditions on different fields/operands.
There are 3 types of Logical Conditions in SQL.
When we use AND logical condition between two conditions, it returns TRUE if both component conditions are TRUE. It returns FALSE if either condition is FALSE.
SELECT * FROM employees WHERE job_id = 'PU_CLERK' AND department_id = 30 ORDER BY employee_id;
In the above SQL query, there are two component conditions and AND logical condition has been placed between them. The SQL query will show results if there are some employees with job_id as ‘PU_CLERK’ and department_id as 30. If any of these conditions evaluate to be FALSE, the query will show no results.
When we use OR logical condition between two component conditions, it returns TRUE if either component condition is TRUE. It returns FALSE if both conditions are FALSE.
SELECT * FROM employees WHERE job_id = 'PU_CLERK' OR department_id = 30 ORDER BY employee_id;
In the above SQL query, two conditions are bound with OR logical condition. So this query will show more records than the query in the example-1. It will show all the employees with department ID 30 or who have job ID as ‘PU_CLERK’.
An OR logical condition produces more row than an AND logical condition does.
In the above two queries, logical conditions are used between two component conditions but we can also use them among more than two component conditions.
It always shows inverse results. If the following condition is TRUE, it returns FALSE and if the condition is FALSE, it returns TRUE. It is always used with other conditions like BETWEEN, EXISTS, IN etc.
--Query-1 SELECT * FROM employees WHERE COMMISSION_PCT IS NOT NULL ORDER BY employee_id; --Query-2 SELECT * FROM employees WHERE salary NOT BETWEEN 2000 AND 5000 ORDER BY SALARY;
Query-1 and Query-2 show its applications with the NULL condition and BETWEEN condition respectively.
If you have any questions/suggestions, please comment below or write me an email.
If you like this blog, do share with your friends and colleagues on your social media. For more updates join my Facebook group and do like my Facebook page.