Sub topic 7
Filtering Rows with WHERE
This chapter assumes you can write a basic SELECT ... FROM statement, you have a session open in SQL*Plus, SQL Developer or SQL Worksheet, and you know the basic data types (numbers, strings, dates). The examples use the HR sample schema, mainly the employees table.
What WHERE does
A SELECT without a filter returns every row in the table. The WHERE clause keeps only the rows for which a condition is true. The condition is evaluated once for each row. A condition has three possible outcomes: TRUE, FALSE or UNKNOWN. Oracle returns a row only when the result is TRUE. FALSE and UNKNOWN rows are both discarded. UNKNOWN appears when NULL is involved, which the next chapter covers in detail. This chapter only points out where it affects filtering.
SELECT employee_id, first_name, last_name, salary
FROM employees
WHERE department_id = 50
ORDER BY salary DESC, last_name;WHERE goes after FROM and before ORDER BY. Only rows where department_id = 50 reach the sort and the output.
Comparison operators
A condition usually compares a column with a value or with another column.
| Operator | Meaning | Example |
|---|---|---|
| `=` | equal | `department_id = 50` |
| `<>`, `!=`, `^=` | not equal | `department_id <> 50` |
| `<`, `<=` | less than, less than or equal | `salary < 3000` |
| `>`, `>=` | greater than, greater than or equal | `salary >= 10000` |
Oracle accepts three spellings of "not equal". <> is the ANSI standard form and the best choice for portable code.
SELECT last_name, salary
FROM employees
WHERE salary >= 10000
ORDER BY salary;Literals must match the column type
Each kind of literal has its own rules.
- Numbers are written bare:
salary > 5000. - Strings use single quotes:
job_id = 'IT_PROG'. Double quotes are for identifiers, not strings. - Character comparisons are case sensitive by default.
last_name = 'king'does not match'King'. - Dates need a date literal or an explicit conversion.
SELECT last_name, hire_date
FROM employees
WHERE hire_date >= DATE '2005-01-01'
AND hire_date < DATE '2006-01-01'
ORDER BY hire_date;DATE '2005-01-01' is an ANSI date literal and does not depend on session settings. You can also use TO_DATE('01-JAN-2005', 'DD-MON-YYYY'). Avoid writing hire_date > '01-JAN-05'. Oracle then converts the string to a date implicitly using the session's NLS_DATE_FORMAT, so the same query can fail or return different rows in another session.
A DATE column also holds a time of day. The query above uses a half-open range (>= the start, < the next start) so that rows with a time later than midnight on 31 December are still included. Writing hire_date <= DATE '2005-12-31' would miss any row stamped after 00:00:00 that day.
Combining conditions with AND, OR and NOT
AND requires both conditions to be true. OR requires at least one. NOT reverses a condition.
SELECT last_name, department_id, salary
FROM employees
WHERE department_id = 50
AND salary > 5000;Oracle evaluates NOT first, then AND, then OR. Mixing AND and OR without parentheses is a common source of wrong results.
-- Intended: employees in department 50 or 80 who earn over 10000
-- Actual: all of department 50, plus those in 80 who earn over 10000
SELECT last_name, department_id, salary
FROM employees
WHERE department_id = 50 OR department_id = 80 AND salary > 10000;
-- Correct version
SELECT last_name, department_id, salary
FROM employees
WHERE (department_id = 50 OR department_id = 80)
AND salary > 10000;Add parentheses whenever a WHERE clause mixes AND and OR, even when the default precedence would give the result you want. The next reader will not have to work it out.
BETWEEN, IN and LIKE
These three operators are shorthand for common patterns.
BETWEEN
x BETWEEN a AND b means x >= a AND x <= b. Both ends are included, and the lower value must come first. BETWEEN 10 AND 5 matches nothing.
SELECT last_name, salary
FROM employees
WHERE salary BETWEEN 5000 AND 7000;IN
IN tests membership in a list. It replaces a chain of OR comparisons.
SELECT last_name, job_id
FROM employees
WHERE job_id IN ('IT_PROG', 'SA_REP', 'ST_CLERK');A list in Oracle can hold at most 1000 expressions. NOT IN has a trap with NULL, covered in the NULL section below.
LIKE
LIKE matches a string against a pattern. Two characters are special: % matches any sequence of characters, including none, and _ matches exactly one character.
SELECT first_name, last_name
FROM employees
WHERE last_name LIKE 'Ma%';
SELECT first_name, last_name
FROM employees
WHERE last_name LIKE '_a%';The first query finds last names that start with Ma. The second finds names whose second letter is a. To match a literal % or _, declare an escape character:
SELECT job_id
FROM employees
WHERE job_id LIKE 'SA\_%' ESCAPE '\';Here \_ means a literal underscore, so the query matches job IDs that start with SA_. Without the escape, _ would match any character.
For case-insensitive matching, apply a function to both sides: WHERE UPPER(last_name) LIKE 'MA%'. Be aware that wrapping a column in a function usually prevents Oracle from using an ordinary index on that column. A function-based index on UPPER(last_name) solves this when the query is frequent.
NULL in conditions
NULL means "no value" or "unknown". Any comparison with NULL using =, <>, < or > yields UNKNOWN, never TRUE. So commission_pct = NULL returns no rows, and so does commission_pct <> NULL. Use IS NULL and IS NOT NULL.
SELECT first_name, last_name, NVL(commission_pct, 0) AS commission
FROM employees
WHERE commission_pct IS NULL OR commission_pct > 0.2;NVL(commission_pct, 0) changes only the displayed value. The WHERE clause still sees the real NULL, which is why it needs IS NULL.
Three consequences are worth memorizing.
salary <> 5000does not return rows wheresalaryis NULL, because the comparison is UNKNOWN.NOT (condition)does not rescue UNKNOWN.NOT UNKNOWNis still UNKNOWN.x NOT IN (1, 2, NULL)never returns TRUE. For any value that is not 1 or 2, one of the tests isx <> NULL, which is UNKNOWN. The whole condition is therefore never TRUE.
The truth tables for AND and OR with UNKNOWN are:
| A | B | A AND B | A OR B |
|---|---|---|---|
| TRUE | UNKNOWN | UNKNOWN | TRUE |
| FALSE | UNKNOWN | FALSE | UNKNOWN |
| UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN |
If you want rows with a NULL commission included in a "not equal" filter, say so explicitly:
SELECT last_name, commission_pct
FROM employees
WHERE commission_pct <> 0.2 OR commission_pct IS NULL;Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| No rows returned for `= NULL` | NULL compared with `=` | Use `IS NULL` |
| `ORA-00933: SQL command not properly ended` | Clauses in the wrong order, such as `WHERE` after `ORDER BY` | Order them `FROM`, `WHERE`, `ORDER BY` |
| `ORA-00904: "ALIAS": invalid identifier` | A select-list alias used in `WHERE` | Repeat the expression, or use a subquery |
| `ORA-01722: invalid number` | Comparing a numeric column with a non-numeric string | Compare with the right type, or convert explicitly |
| `ORA-01843: not a valid month` or `ORA-01861` | Implicit date conversion that disagrees with `NLS_DATE_FORMAT` | Use `DATE '...'` or `TO_DATE` |
| Name search misses rows | Case-sensitive comparison | Compare `UPPER(col)` with an upper-case literal |
Aliases cannot be used in WHERE
Oracle evaluates WHERE before it computes the select list, so an alias defined in the select list does not exist yet.
-- Fails with ORA-00904
SELECT salary * 12 AS annual_salary
FROM employees
WHERE annual_salary > 100000;
-- Works
SELECT salary * 12 AS annual_salary
FROM employees
WHERE salary * 12 > 100000;ORDER BY runs later and can use the alias. A later chapter on the logical order of query clauses explains why.
WHERE and DUAL
WHERE also works against dual, which holds one row. A true condition returns that row and a false one returns nothing. This gives a quick way to test a condition:
SELECT 'yes' AS result FROM dual WHERE 5 BETWEEN 1 AND 10;
SELECT 'yes' AS result FROM dual WHERE NULL = NULL;The first query returns one row. The second returns no rows, because NULL = NULL is UNKNOWN.
Summary
WHEREkeeps rows whose condition is TRUE and drops FALSE and UNKNOWN rows.- Use
<>for not equal, and always useIS NULLorIS NOT NULLto test for NULL. - Strings are case sensitive. Use
DATE '...'literals and half-open ranges for dates. ANDbinds tighter thanOR, so use parentheses.BETWEENincludes both ends,INtakes a list, andLIKEuses%and_.- A select-list alias cannot be used in
WHERE.
Exercise
A table has 107 employees. 35 have a NULL commissionpct, 5 have commissionpct = 0.2, and the remaining 67 have a different non-NULL value. How many rows does SELECT * FROM employees WHERE commission_pct <> 0.2 return, and how would you change the query to also return the NULL rows?
Show answer
It returns 67 rows. The 5 rows equal to 0.2 give FALSE, and the 35 NULL rows give UNKNOWN, so both groups are discarded. To include the NULL rows, use WHERE commission_pct <> 0.2 OR commission_pct IS NULL, which returns 102 rows.
Exercise
Rewrite this query so that it returns employees who are in department 50 or 80 and who earn more than 10000, and explain why the original gives a different result: WHERE department_id = 50 OR department_id = 80 AND salary > 10000.
Show answer
Use WHERE department_id IN (50, 80) AND salary > 10000, or WHERE (department_id = 50 OR department_id = 80) AND salary > 10000. In the original, AND binds tighter than OR, so it means department_id = 50 OR (department_id = 80 AND salary > 10000). That returns every employee in department 50 regardless of salary.
Exercise
Why does SELECT salary * 12 AS annual FROM employees WHERE annual > 100000 raise ORA-00904, and how do you fix it?
Show answer
Oracle evaluates WHERE before it computes the select list, so the alias annual does not exist yet. Repeat the expression in the filter: WHERE salary * 12 > 100000. A subquery that defines the alias first also works.