๐Ÿ” Filtering with WHERE

WHERE keeps only the rows that match a condition. It is the SQL equivalent of PySpark's filter(), and getting it right (especially with AND/OR and NULL) is what separates correct reports from subtly wrong ones.


1. Sample Data

All examples use the employees view from the Introduction to Spark SQL:

CREATE OR REPLACE TEMP VIEW employees AS
SELECT * FROM VALUES
  (1, 'Asha',  'Engineering', 95000, DATE'2019-03-15', NULL, 'Bengaluru'),
  (2, 'Ben',   'Engineering', 82000, DATE'2020-07-01', 1,    'Pune'),
  (3, 'Chen',  'Sales',       60000, DATE'2021-01-10', 1,    'Mumbai'),
  (4, 'Divya', 'Sales',       65000, DATE'2018-11-23', 3,    'Mumbai'),
  (5, 'Elena', 'Marketing',   58000, DATE'2022-05-30', 1,    NULL),
  (6, 'Farid', 'Engineering', 82000, DATE'2023-02-14', 2,    'Bengaluru'),
  (7, 'Grace', NULL,          45000, DATE'2024-01-08', NULL, 'Delhi')
AS employees(emp_id, name, dept, salary, hire_date, manager_id, city)

2. Comparison Operators

The simplest filter compares a column with a value:

SELECT name, salary
FROM employees
WHERE salary > 80000
ORDER BY salary DESC, name
+-----+------+
|name |salary|
+-----+------+
|Asha |95000 |
|Ben  |82000 |
|Farid|82000 |
+-----+------+

Spark SQL supports the usual operators:

OperatorMeaningExample
=Equal todept = 'Sales'
<> or !=Not equal todept <> 'Sales'
> and >=Greater than (or equal)salary >= 60000
< and <=Less than (or equal)salary < 60000

Text comparisons are case-sensitive: dept = 'sales' matches nothing, because the data says Sales.


3. Combining Conditions with AND, OR and NOT

  • AND: both conditions must be true.
  • OR: at least one condition must be true.
  • NOT: flips a condition.
SELECT name, dept, city
FROM employees
WHERE dept = 'Engineering'
  AND city = 'Bengaluru'
ORDER BY name
+-----+-----------+---------+
|name |dept       |city     |
+-----+-----------+---------+
|Asha |Engineering|Bengaluru|
|Farid|Engineering|Bengaluru|
+-----+-----------+---------+
SELECT name, dept, salary
FROM employees
WHERE NOT (dept = 'Engineering' OR salary < 50000)
ORDER BY name
+-----+---------+------+
|name |dept     |salary|
+-----+---------+------+
|Chen |Sales    |60000 |
|Divya|Sales    |65000 |
|Elena|Marketing|58000 |
+-----+---------+------+

The second query removes everyone in Engineering and everyone earning under 50,000. Grace earns 45,000, so she is removed by the salary part.


4. The AND/OR Precedence Trap

AND is evaluated before OR, just like multiplication before addition. Forgetting this is one of the most common SQL bugs.

Suppose you want "employees in Engineering or Sales who earn more than 85,000". This looks right but is not:

SELECT name, dept, salary
FROM employees
WHERE dept = 'Engineering' OR dept = 'Sales' AND salary > 85000
ORDER BY name
+-----+-----------+------+
|name |dept       |salary|
+-----+-----------+------+
|Asha |Engineering|95000 |
|Ben  |Engineering|82000 |
|Farid|Engineering|82000 |
+-----+-----------+------+

Spark read it as dept = 'Engineering' OR (dept = 'Sales' AND salary > 85000), so every Engineering employee came back, whatever their salary. Add parentheses to say what you mean:

SELECT name, dept, salary
FROM employees
WHERE (dept = 'Engineering' OR dept = 'Sales') AND salary > 85000
ORDER BY name
+----+-----------+------+
|name|dept       |salary|
+----+-----------+------+
|Asha|Engineering|95000 |
+----+-----------+------+

Common mistake: Mixing AND and OR without parentheses. Even when the default precedence happens to be what you want, parentheses make the intent obvious to the next reader.


5. Matching a List with IN

IN is a shorter way to write several OR conditions on the same column:

SELECT name, city
FROM employees
WHERE city IN ('Mumbai', 'Pune')
ORDER BY name
+-----+------+
|name |city  |
+-----+------+
|Ben  |Pune  |
|Chen |Mumbai|
|Divya|Mumbai|
+-----+------+

NOT IN keeps the rows that match none of the values. Watch what happens to the NULL department:

SELECT name, dept
FROM employees
WHERE dept NOT IN ('Engineering', 'Sales')
ORDER BY name
+-----+---------+
|name |dept     |
+-----+---------+
|Elena|Marketing|
+-----+---------+

Only Elena is returned. Grace's department is NULL, and Spark cannot say whether an unknown value is "not in" the list, so the row is dropped. The Handling NULLs tutorial explains this in detail, including the even nastier case of a NULL inside the list.


6. Ranges with BETWEEN

BETWEEN low AND high keeps values in a range. Both ends are included:

SELECT name, salary
FROM employees
WHERE salary BETWEEN 58000 AND 65000
ORDER BY salary
+-----+------+
|name |salary|
+-----+------+
|Elena|58000 |
|Chen |60000 |
|Divya|65000 |
+-----+------+

Elena (58,000) and Divya (65,000) sit exactly on the boundaries, and both are returned. BETWEEN 58000 AND 65000 is the same as salary >= 58000 AND salary <= 65000.

Common mistake: Writing the range backwards. BETWEEN 65000 AND 58000 returns no rows, because no value is both >= 65000 and <= 58000.


7. Pattern Matching with LIKE, ILIKE and RLIKE

LIKE matches text against a pattern with two wildcards:

WildcardMatchesExampleMatches
%Any number of characters (including none)'B%'Ben, Bengaluru
_Exactly one character'_e%'Ben, Delhi
SELECT name, city
FROM employees
WHERE city LIKE 'B%'
ORDER BY name
+-----+---------+
|name |city     |
+-----+---------+
|Asha |Bengaluru|
|Farid|Bengaluru|
+-----+---------+
SELECT name
FROM employees
WHERE name LIKE '_e%'
ORDER BY name
+----+
|name|
+----+
|Ben |
+----+

LIKE is case-sensitive. ILIKE ignores case:

SELECT name
FROM employees
WHERE name LIKE 'a%' OR name ILIKE 'e%'
ORDER BY name
+-----+
|name |
+-----+
|Elena|
+-----+

LIKE 'a%' found nothing (all names start with a capital letter), while ILIKE 'e%' matched Elena.

To search for a literal % or _, mark it with an escape character using ESCAPE:

SELECT code
FROM VALUES ('SALE_10'), ('SALE10'), ('SALEX10') AS t(code)
WHERE code LIKE 'SALE!_%' ESCAPE '!'
+-------+
|code   |
+-------+
|SALE_10|
+-------+

!_ means "a real underscore", so only SALE_10 matches. Without the escape, _ would match any single character, and SALE10 and SALEX10 would match too.

For anything more complex, RLIKE (also spelled REGEXP) uses a regular expression. This finds names that end in a vowel:

SELECT name
FROM employees
WHERE name RLIKE '[aeiou]$'
ORDER BY name
+-----+
|name |
+-----+
|Asha |
|Divya|
|Elena|
|Grace|
+-----+

Unlike LIKE, RLIKE matches anywhere in the string unless you anchor the pattern with ^ (start) or $ (end).


8. Filtering NULLs: IS NULL, Not = NULL

To find missing values, use IS NULL. Comparing with = NULL looks natural but never matches anything:

SELECT name, city
FROM employees
WHERE city = NULL
+----+----+
|name|city|
+----+----+
+----+----+
SELECT name, city
FROM employees
WHERE city IS NULL
+-----+----+
|name |city|
+-----+----+
|Elena|NULL|
+-----+----+

IS NOT NULL does the opposite. NULL also hides rows from "not equal" filters:

SELECT name, city
FROM employees
WHERE city <> 'Mumbai'
ORDER BY name
+-----+---------+
|name |city     |
+-----+---------+
|Asha |Bengaluru|
|Ben  |Pune     |
|Farid|Bengaluru|
|Grace|Delhi    |
+-----+---------+

Elena is missing. Her city is unknown, so city <> 'Mumbai' is neither true nor false, and WHERE only keeps rows where the condition is true. To include her, say so: WHERE city <> 'Mumbai' OR city IS NULL.

Interview tip: "Why does WHERE col = NULL return nothing?" Any comparison with NULL gives NULL (unknown), not true, and WHERE drops rows whose condition is not true.


9. Filtering Dates

Compare date columns with date literals:

SELECT name, hire_date
FROM employees
WHERE hire_date >= DATE'2022-01-01'
ORDER BY hire_date
+-----+----------+
|name |hire_date |
+-----+----------+
|Elena|2022-05-30|
|Farid|2023-02-14|
|Grace|2024-01-08|
+-----+----------+

BETWEEN works for dates too, and both ends are included. Date functions such as year() and month() let you filter on part of a date:

SELECT name, hire_date
FROM employees
WHERE year(hire_date) BETWEEN 2019 AND 2021
ORDER BY hire_date
+----+----------+
|name|hire_date |
+----+----------+
|Asha|2019-03-15|
|Ben |2020-07-01|
|Chen|2021-01-10|
+----+----------+

You can also write the date as plain text, as in hire_date >= '2022-01-01', and Spark converts it for you. The DATE'...' form is safer, though. See what happens with a typo (month 13) in each form:

SELECT name FROM employees
WHERE hire_date >= DATE'2022-13-01'
[INVALID_TYPED_LITERAL] The value of the typed literal "DATE" is invalid: '2022-13-01'.(line 2, pos 19)
SELECT name FROM employees
WHERE hire_date >= '2022-13-01'
+----+
|name|
+----+
+----+

The typed literal fails loudly. The plain string cannot be converted to a date, so it becomes NULL, every comparison is unknown, and the query quietly returns nothing. The Date & Time Functions tutorial covers dates in depth.


10. Expressions in WHERE

The condition can use any expression, not just plain columns:

SELECT name, salary
FROM employees
WHERE salary * 1.10 > 100000
   OR length(name) = 3
ORDER BY name
+----+------+
|name|salary|
+----+------+
|Asha|95000 |
|Ben |82000 |
+----+------+

Asha passes the salary test (95,000 x 1.10 = 104,500), and Ben passes the name-length test.


11. WHERE Cannot Use SELECT Aliases

Remember the evaluation order from the introduction: WHERE runs before SELECT. So an alias defined in SELECT does not exist yet when WHERE runs:

SELECT name, salary * 1.10 AS new_salary
FROM employees
WHERE new_salary > 90000
[UNRESOLVED_COLUMN.WITH_SUGGESTION] A column or function parameter with name `new_salary` cannot be resolved. Did you mean one of the following? [`salary`, `emp_id`, `name`, `city`, `dept`].; line 3 pos 6;

Two common fixes:

  1. Repeat the expression: WHERE salary * 1.10 > 90000.
  2. Compute it first in a subquery or CTE, then filter on the alias:
SELECT name, new_salary
FROM (
  SELECT name, salary * 1.10 AS new_salary
  FROM employees
) AS raised
WHERE new_salary > 90000
ORDER BY name
+-----+----------+
|name |new_salary|
+-----+----------+
|Asha |104500.00 |
|Ben  |90200.00  |
|Farid|90200.00  |
+-----+----------+

The Subqueries & CTEs tutorial covers this pattern.


12. Try It in the Online Compiler

Copy this into the PySpark Online Compiler:

from pyspark.sql import SparkSession

spark = SparkSession.builder.appName("Spark SQL Where").getOrCreate()

spark.sql("""
CREATE OR REPLACE TEMP VIEW employees AS
SELECT * FROM VALUES
  (1, 'Asha',  'Engineering', 95000, DATE'2019-03-15', NULL, 'Bengaluru'),
  (2, 'Ben',   'Engineering', 82000, DATE'2020-07-01', 1,    'Pune'),
  (3, 'Chen',  'Sales',       60000, DATE'2021-01-10', 1,    'Mumbai'),
  (4, 'Divya', 'Sales',       65000, DATE'2018-11-23', 3,    'Mumbai'),
  (5, 'Elena', 'Marketing',   58000, DATE'2022-05-30', 1,    NULL),
  (6, 'Farid', 'Engineering', 82000, DATE'2023-02-14', 2,    'Bengaluru'),
  (7, 'Grace', NULL,          45000, DATE'2024-01-08', NULL, 'Delhi')
AS employees(emp_id, name, dept, salary, hire_date, manager_id, city)
""")

# Parentheses change the answer
spark.sql("""
SELECT name, dept, salary FROM employees
WHERE (dept = 'Engineering' OR dept = 'Sales') AND salary > 85000
""").show(truncate=False)

# NULL needs IS NULL
spark.sql("SELECT name, city FROM employees WHERE city <> 'Mumbai' OR city IS NULL ORDER BY name").show(truncate=False)

# Dates and ranges
spark.sql("""
SELECT name, hire_date FROM employees
WHERE hire_date BETWEEN DATE'2019-01-01' AND DATE'2021-12-31'
ORDER BY hire_date
""").show(truncate=False)

Summary

  • WHERE keeps rows whose condition is true; rows where it is false or NULL are dropped.
  • Text comparisons are case-sensitive. Use ILIKE or lower() when case should not matter.
  • AND binds tighter than OR. Use parentheses whenever you mix them.
  • IN matches a list; BETWEEN matches a range and includes both ends.
  • LIKE uses % and _; RLIKE uses regular expressions; ESCAPE matches literal wildcards.
  • Use IS NULL / IS NOT NULL, never = NULL. Remember that <> and NOT IN silently drop NULL rows.
  • WHERE runs before SELECT, so it cannot see column aliases.

Next, you will learn how to summarize data with GROUP BY and aggregate functions.