The NOT keyword in SQL is used to negate a condition or expression. It is typically used in conjunction with logical operators like WHERE, BETWEEN, IN, LIKE, and EXISTS to exclude specific data that matches a given condition. Essentially, it reverses the result of the condition it is applied to.
Basic Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
Examples:
- Using
NOTwithWHEREto exclude rows:
SELECT * FROM Employees
WHERE NOT (Age > 40);
This query will select all employees whose age is 40 or less.
- Using
NOTwithIN:
SELECT * FROM Products
WHERE ProductID NOT IN (1, 2, 3);
This will retrieve all products where the ProductID is not 1, 2, or 3.
- Using
NOTwithLIKE:
SELECT * FROM Customers
WHERE Name NOT LIKE 'A%';
This will return all customers whose name does not start with the letter 'A'.
- Using
NOTwithEXISTS:
SELECT * FROM Orders
WHERE NOT EXISTS (SELECT * FROM OrderDetails WHERE OrderDetails.OrderID = Orders.OrderID);
This will return all orders where there are no details in the OrderDetails table.
Notes:
- The
NOTkeyword is very useful for filtering data when you need to exclude certain values. - It can be combined with other conditions for more complex filtering.
Let me know if you'd like examples for more specific use cases!
No comments:
Post a Comment