The AND & OR & NOT operators(logical operators) are used to filter records based on more than one condition.
The AND operator displays a record if both the first condition and the second condition is true.
The OR operator displays a record if either the first condition or the second condition is true.
The NOT operator displays the records that are false to the specified value.
In the previous tutorials, we have learn that the WHERE keyword can be used to conditionally select data from a table.This are simple conditions.
With And & OR & NOT we will learn how to make compound conditions. Compound conditions are simple conditions combined connected using And & OR & NOT.
We can use as many simple conditions as we like into out query.
Sintax for a compound condition is :
Let's create the table we will use
Script:
Check the table to see the data and the structure.
Very good
The AND condition
If you want to select rows that must satisfy all the given conditions, you can use the logical operator, AND.
Example
-we want to see the persons that have the id =1 and name= Eve.
- in this example the AND condition must be true for both cases (for both = conditions), if one of the condition is false then no result will be shownExample of wrong or false = condition.
Example 2
-an example with more than 2 AND conditions
-we can add as many conditions as we want .
The OR condition
If you want to select rows that satisfy at least one of the given conditions, you can use the logical operator, OR.
-when we use OR condition is enough that one of our condition to be true so that all of them to be true.
-let's take the example 2 (where the AND condition returned no lines), but this time we will replace the AND condition with OR and see what happens:
- we can see that returned a row; why is that ? because of the OR condition.
AND & OR conditions are very important and they of great use in everyday work with SQL language ,for now we will stop here but in the future we will give more attention to our AND & OR conditions .
The NOT condition
If you want to find rows that do not satisfy a condition, you can use the logical operator, NOT. NOT results in the reverse of a condition. That is, if a condition is satisfied, then the row is not returned.
Using our test table we will want to find the name of the persons who are not working in the AD department:
-see that the result of the querys are the same, it will show all the users that are not in the AD department.