Sub topic 2
Comparing values: =, <>, <, <=, >, >=
This chapter assumes you can write a basic SELECT ... FROM query and that a WHERE clause keeps only the rows where its condition is true. The examples use an employees table with the columns first_name, last_name, department, salary, hire_date, and manager_id.
Comparison operators
Comparison operators test how one value relates to another. Each returns true, false, or unknown.
| Operator | Meaning |
|---|---|
| `=` | Equal to |
| `<>` | Not equal to (many databases also accept `!=`) |
| `<` | Less than |
| `<=` | Less than or equal to |
| `>` | Greater than |
| `>=` | Greater than or equal to |
SELECT first_name, salary
FROM employees
WHERE salary >= 50000;Text values go in single quotes, as in department = 'Sales'. Dates in ISO format ('2021-06-01') compare correctly as text in most databases.
Combining conditions with AND, OR, and NOT
AND requires both conditions to be true. OR requires at least one. NOT reverses a condition. AND binds more tightly than OR, so parentheses control the meaning:
SELECT first_name, department, salary
FROM employees
WHERE (department = 'Sales' OR department = 'Marketing')
AND salary > 50000;Ranges and lists with BETWEEN and IN
BETWEEN tests an inclusive range, so both endpoints match. IN tests membership in a list.
SELECT first_name, last_name
FROM employees
WHERE department IN ('Sales', 'Marketing', 'Support')
AND hire_date BETWEEN '2020-01-01' AND '2022-12-31';Matching text patterns with LIKE
In a LIKE pattern, % matches any run of characters, and _ matches exactly one character.
SELECT first_name, last_name
FROM employees
WHERE last_name LIKE 'Mc%';Handling NULL with IS NULL and IS NOT NULL
NULL means "no known value." Any comparison with NULL, including manager_id = NULL, yields unknown, so it matches no rows. Use IS NULL and IS NOT NULL instead:
SELECT first_name, last_name
FROM employees
WHERE manager_id IS NULL;Rows where manager_id is NULL also fail a condition such as manager_id <> 5. Add IS NOT NULL when you need those rows included.
Exercise
Write a query that returns firstname and salary for employees in 'Sales' whose salary is below 40000 or who have no manager (managerid IS NULL).
Show answer
SELECT firstname, salary FROM employees WHERE department = 'Sales' AND (salary < 40000 OR managerid IS NULL);