Introduction
Logical operators help you combine or change conditions in database queries to get exactly the data you want.
Logical operators help you combine or change conditions in database queries to get exactly the data you want.
SELECT column_names FROM table_name WHERE condition1 AND condition2; SELECT column_names FROM table_name WHERE condition1 OR condition2; SELECT column_names FROM table_name WHERE NOT condition;
AND means both conditions must be true.
OR means at least one condition must be true.
NOT reverses the condition.
SELECT * FROM employees WHERE department = 'Sales' AND status = 'Active';
SELECT * FROM products WHERE stock > 0 OR on_sale = TRUE;
SELECT * FROM users WHERE NOT is_admin;
This creates a simple customers table, adds some data, then finds customers who live in New York and have made a purchase.
CREATE TABLE customers ( id INT, name VARCHAR(50), city VARCHAR(50), has_purchased BOOLEAN ); INSERT INTO customers VALUES (1, 'Alice', 'New York', TRUE), (2, 'Bob', 'Los Angeles', FALSE), (3, 'Carol', 'New York', FALSE), (4, 'Dave', 'Chicago', TRUE); SELECT name FROM customers WHERE city = 'New York' AND has_purchased = TRUE;
Use parentheses to group conditions when mixing AND and OR to avoid confusion.
NOT applies only to the condition immediately after it unless parentheses are used.
AND requires all conditions to be true.
OR requires at least one condition to be true.
NOT reverses the truth of a condition.
all conditions to be true for the whole expression to be true?age is greater than 18 and status is 'active'?employees with columns department and salary, what rows will this query return?SELECT * FROM employees WHERE department = 'Sales' OR salary > 50000 AND NOT department = 'HR';
SELECT * FROM orders WHERE NOT order_date > '2023-01-01' AND status = 'shipped' OR;
Pass the test and this pattern moves unknown