SQL Basics

SQL WHERE

Filter database records precisely using WHERE clauses with comparison and logical operators.

The SQL WHERE Clause

The WHERE clause is used to filter records. It extracts only those records that fulfill a specified condition.

Comparison Operators

OperatorDescription
=Equal
>Greater than
<Less than
>=Greater than or equal
<=Less than or equal
<> or !=Not equal

Logical Operators

  • AND — All conditions must be true
  • OR — At least one condition must be true
  • NOT — Negates a condition

Special Operators

  • BETWEEN — Within a range
  • IN — Matches list of values
  • LIKE — Pattern matching
  • IS NULL / IS NOT NULL — Check for null

Example

sql
-- Basic WHERE
SELECT * FROM orders WHERE status = 'pending';

-- Multiple conditions with AND
SELECT * FROM products
WHERE category = 'Electronics'
  AND price < 500
  AND in_stock = true;

-- OR condition
SELECT * FROM users
WHERE role = 'admin' OR role = 'moderator';

-- BETWEEN (inclusive)
SELECT * FROM products
WHERE price BETWEEN 10 AND 50;

-- IN operator
SELECT * FROM orders
WHERE status IN ('pending', 'processing', 'shipped');

-- LIKE pattern matching
SELECT * FROM users WHERE email LIKE '%@gmail.com';
SELECT * FROM products WHERE name LIKE 'Python%';
SELECT * FROM posts WHERE title LIKE '%AI%';

-- NULL checks
SELECT * FROM users WHERE last_login IS NULL;
SELECT * FROM orders WHERE shipped_at IS NOT NULL;

-- NOT
SELECT * FROM products WHERE category NOT IN ('archived', 'draft');

Want to run this code interactively?

Try in Compiler