SQL not
Created By: chatGPT
SQL provides a way to retrieve and manipulate data using various commands. One of the essential logical operators in SQL is NOT, which allows you to exclude certain conditions from your queries. It is primarily used to negate a condition in a query.
SELECT *
FROM customers
WHERE NOT city = 'Paris';
In the above query, we are selecting all columns from the customers table where the city is NOT 'Paris'. This means we will receive all customers from other cities.
SELECT *
FROM products
WHERE NOT price < 50;
This query retrieves products where the price is NOT less than 50. It effectively fetches products that have a price of 50 or more.
SELECT *
FROM orders
WHERE NOT status IN ('Cancelled', 'Returned');
Here, we are selecting orders that are NOT Cancelled or Returned. The IN clause allows for the use of a list of values, and by combining it with NOT, we filter out multiple statuses at once.
SELECT *
FROM employees
WHERE NOT (department = 'HR' OR department = 'Sales');
In this example, we are selecting employees who are NOT in the HR or Sales departments. The use of parentheses ensures that the OR condition is evaluated first, thereby negating the entire condition.
SELECT name
FROM customers
WHERE NOT EXISTS (SELECT *
FROM orders
WHERE customers.id = orders.customer_id);
Finally, this query retrieves the names of customers who do not have any related records in the orders table. The NOT EXISTS condition checks for the absence of entries in a subquery.
-- Example usage of NOT with other conditions
SELECT *
FROM employees
WHERE NOT (salary > 100000 AND department = 'Management');
In this example, we are selecting employees whose salary is NOT greater than 100,000 in the Management department. The logical conditions can be combined to create more complex queries.
This retrieves all products that are NOT marked as discontinued. Logical operators like NOT enhance the flexibility and power of SQL queries, allowing for more precise data retrieval.SELECT *
FROM products
WHERE NOT discontinued = true;