Explain NOT Operator in SQL
The NOT operator in SQL is used to negate a condition in a WHERE clause. It filters out rows where the condition is true, effectively returning rows where the condition is false.
Here’s a basic example to illustrate how the NOT operator works:
Example
Suppose you have a table named Employees with the following data:
| EmployeeID |
Name |
Department |
| 1 |
Alice |
HR |
| 2 |
Bob |
IT |
| 3 |
Carol |
IT |
| 4 |
Dave |
Marketing |
| 5 |
Eve |
HR |
Query 1: Using NOT
To retrieve all employees who are not in the IT department, you would use:
SELECT *
FROM Employees
WHERE Department NOT LIKE 'IT';
Output:
| EmployeeID |
Name |
Department |
| 1 |
Alice |
HR |
| 4 |
Dave |
Marketing |
| 5 |
Eve |
HR |
Explanation
In this query:
WHERE Department NOT LIKE 'IT' is the condition used to filter out employees whose department is not IT.
- The result includes employees in the
HR and Marketing departments.
You can use NOT with other operators as well, like NOT IN, NOT BETWEEN, NOT EXISTS, and NOT LIKE, depending on the type of condition you need to negate.