Sub topic 6
Comparing values: =, <>, <, <=, >, >=
Comparison operators are the base of every WHERE condition. This chapter covers what they return, how they behave across numbers, text, and dates, and the cases where they quietly return fewer rows than you expect.
This chapter assumes you can write a basic SELECT ... FROM ... WHERE query and know what a table, row, and column are. AND, OR, NOT, BETWEEN, IN, LIKE, and IS NULL have their own chapters. They appear here only where they affect comparisons.
The sample table
The examples use this small table. The script runs unchanged in PostgreSQL, MySQL, and SQLite.
CREATE TABLE employees (
employee_id INTEGER PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
department VARCHAR(50),
salary INTEGER,
hire_date DATE,
manager_id INTEGER
);
INSERT INTO employees VALUES
(1, 'Ana', 'Silva', 'Sales', 52000, '2020-03-15', NULL),
(2, 'Ben', 'Okafor', 'Sales', 48000, '2021-07-01', 1),
(3, 'Chen', 'Wei', 'Marketing', 61000, '2019-11-20', 1),
(4, 'Dara', 'McKay', 'Support', 39000, '2022-02-10', 3),
(5, 'Eli', 'Brown', NULL, 45000, '2023-05-05', 3);What a comparison returns
A comparison takes two values and tests how they relate. It is a kind of predicate, an expression that evaluates to a truth value. In SQL that value is one of three:
- TRUE: the relationship holds.
- FALSE: it does not hold.
- UNKNOWN: the result cannot be decided, which happens when either side is
NULL.
WHERE keeps a row only when its condition evaluates to TRUE. Rows that evaluate to FALSE or UNKNOWN are both discarded. Most surprises in this chapter come from that rule.
The six operators
| Operator | Meaning | Example |
|---|---|---|
| `=` | equal to | `salary = 48000` |
| `<>` | not equal to | `department <> 'Sales'` |
| `<` | less than | `salary < 45000` |
| `<=` | less than or equal to | `salary <= 45000` |
| `>` | greater than | `hire_date > '2021-01-01'` |
| `>=` | greater than or equal to | `hire_date >= '2021-01-01'` |
SQL uses a single = for equality. Writing == is a syntax error in most databases. Most databases also accept != for "not equal", but <> is the standard form and works everywhere.
A basic query:
SELECT first_name, salary
FROM employees
WHERE salary > 48000;It returns Ana (52000) and Chen (61000). Ben earns exactly 48000, so the strict > excludes him. Change the operator to >= and Ben appears too. Whether a boundary value belongs in the result is the most common off-by-one mistake in SQL, so check the boundary row whenever you pick between > and >=.
Comparing numbers, text, and dates
Both sides of a comparison should have compatible types. The rules differ by type.
Numbers
Numbers compare by value. Integer and decimal types mix freely, so salary > 48000.5 works. Avoid = on floating-point columns (FLOAT, DOUBLE, REAL). Binary floating point cannot store values like 0.1 exactly, so a computed value that looks equal to a literal may differ in the last bits. For floating-point data, compare against a small range instead. For money, use an exact type such as DECIMAL or NUMERIC.
Text
Text values are quoted with single quotes. Double quotes mean an identifier such as a column name in standard SQL and PostgreSQL, so department = "Sales" fails or is read as a column.
SELECT first_name, last_name
FROM employees
WHERE last_name >= 'M';This returns McKay, Okafor, Silva, and Wei. The ordering of text is decided by the column's collation, a rule set for sorting and comparing characters. Collations cause three differences:
- Case: In PostgreSQL and SQLite,
'sales' = 'Sales'is false by default. In MySQL, the default collations ignore case, so the same test is true. - Order of letters: Collations decide whether uppercase sorts before lowercase and how accented letters rank.
- Prefixes: A shorter string that is a prefix of a longer one is smaller.
'M' < 'McKay'is true, which is why McKay passes>= 'M'.
Text compares character by character, never as numbers. If a column holds numbers stored as text, then '9' > '10' is true, because '9' is greater than '1' at the first character. Convert with CAST or fix the column type.
Dates
Write date literals in ISO format, 'YYYY-MM-DD'. That format is unambiguous and sorts correctly even as text.
SELECT first_name, hire_date
FROM employees
WHERE hire_date >= '2021-01-01';This returns Ben, Dara, and Eli. If a column has a timestamp type, ts = '2024-05-01' means midnight at the start of that day, so it misses any row later that day. To select a whole day, use ts >= '2024-05-01' AND ts < '2024-05-02'. The half-open range, with an inclusive start and exclusive end, avoids both the boundary problem and any precision concerns.
Expressions on either side
A comparison operand can be a column, a literal, or an expression. Both sides may be columns.
SELECT first_name, salary
FROM employees
WHERE salary * 12 > 600000;This returns Ana (624000) and Chen (732000). You can compare two columns of the same row, for example manager_id < employee_id.
Two cautions apply. First, an alias defined in SELECT cannot be used here, because WHERE is evaluated before the select list. Repeat the expression, as above. The last chapter in this series explains the evaluation order. Second, wrapping a column in a function or arithmetic, such as salary * 12 > 600000, can stop the database from using an index on salary. When you can, move the arithmetic to the constant side: salary > 600000 / 12. For integer columns, check that the integer division in your database does not round, or write 50000 directly.
NOT EQUAL and NULL
NULL marks a missing value. Any comparison with NULL, including NULL = NULL and NULL <> 'Sales', evaluates to UNKNOWN. WHERE discards UNKNOWN rows. This makes <> less inclusive than it looks:
SELECT first_name, department
FROM employees
WHERE department <> 'Sales';You might expect Chen, Dara, and Eli, who are not in Sales. The result is only Chen and Dara. Eli's department is NULL, so NULL <> 'Sales' is UNKNOWN and Eli's row is dropped.
If you want rows with missing values too, say so explicitly:
SELECT first_name, department
FROM employees
WHERE department <> 'Sales'
OR department IS NULL;IS NULL is the only correct test for missing values. department = NULL never returns a row. The next chapters cover IS NULL and three-valued logic in detail.
Dialect notes
<>is standard and portable.!=works in PostgreSQL, MySQL, SQLite, and SQL Server, but Oracle accepts it only as an extension.- MySQL has a null-safe equality operator,
<=>, which treats two NULLs as equal. The standard equivalent isIS NOT DISTINCT FROM, available in PostgreSQL and SQLite. - PostgreSQL and SQLite let you compare a mixed row of values with
(a, b) < (x, y), which compares left to right. This is useful for pagination, but check that your database supports it before relying on it. - Comparing a number with a text value triggers implicit conversion in some databases (MySQL, SQLite) and an error in others (PostgreSQL). Write explicit types.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Syntax error near `==` | Programming-language habit | Use `=` |
| No rows from `= NULL` | Comparison with NULL is UNKNOWN | Use `IS NULL` |
| Rows with NULL missing from `<>` | UNKNOWN rows are discarded | Add `OR col IS NULL` |
| "Column does not exist" for `'Sales'` in double quotes | Double quotes name identifiers | Use single quotes |
| Boundary row missing | `>` used where `>=` was needed | Test the boundary value |
| `'9' > '10'` is true | Numbers stored as text | Cast or change the type |
| Day filter misses afternoon timestamps | Timestamp equals midnight only | Use a half-open range |
Exercise
Using the sample table, what does SELECT first_name FROM employees WHERE salary <> 48000; return, and what does WHERE salary < 48000 OR salary > 48000 return? Are they the same?
Show answer
Both return Ana, Chen, Dara, and Eli, because only Ben earns exactly 48000 and no salary is NULL. They are the same here. If salary could be NULL, both would still drop the NULL rows, since every comparison with NULL is UNKNOWN. The two forms stay equivalent for non-NULL data.
Exercise
Write a query that returns the first name and department of every employee who was hired before 2021-01-01 and is not in the Marketing department, keeping employees whose department is NULL. Which employees does it return?
Show answer
SELECT firstname, department FROM employees WHERE hiredate < '2021-01-01' AND (department <> 'Marketing' OR department IS NULL); It returns only Ana. Chen was hired before 2021 but is in Marketing. Ben, Dara, and Eli were hired in 2021 or later, so Eli's NULL department is never tested against the date condition.