filter / where
Most questions start by narrowing the data down: only Pune, only last week, only orders above 500. filter keeps the rows you want and drops the rest. This lesson shows single and combined conditions, the parentheses trap in PySpark, and how missing values make rows quietly disappear.
Step 1 · PySpark functions · Bronze · Read and select, lesson 3 of 5
On this page
Show code in
Every code block on the page follows this.
Read first: select (skip if you know it)
In plain words first
Picture sorting a stack of delivery slips into "keep" and "bin". You check each slip against a rule, such as "city is Pune and amount over 500", and only the slips that clearly pass are kept.
filter (also called where) is that rule. One catch, explained below: a slip with the amount left blank does not clearly pass, so it goes in the bin too.
What it does
filter and where are the same method. They take a boolean column expression, or a SQL string, and return only the rows where it evaluates to true.
employees.filter(F.col("dept") == "Sales") employees.where("dept = 'Sales'") # same thing, SQL string
SELECT * FROM employees WHERE dept = 'Sales'
Step by step
Keep engineers, or anyone earning more than 50,000:
Input
| name | dept | salary |
|---|---|---|
| Asha | Engineering | 72000 |
| Ben | Sales | 48000 |
| Dev | HR | 51000 |
| Farid | nullnull: A missing or unknown value. Any comparison with null gives null, so filters treat it as false. Learn more → | 39000 |
Output
| name | dept | salary |
|---|---|---|
| Asha | Engineering | 72000 |
| Dev | HR | 51000 |
Farid has a null department. dept = 'Engineering' is null for him, not false, and he earns too little, so he is dropped.
Run the example
Input: employees
| id | name | dept | salary | manager_id |
|---|---|---|---|---|
| 1 | Asha | Engineering | 72000 | null |
| 2 | Ben | Sales | 48000 | 1 |
| 3 | Chitra | Engineering | 95000 | 1 |
| 4 | Dev | HR | 51000 | 1 |
| 5 | Esha | Sales | 50000 | 2 |
| 6 | Farid | null | 39000 | 2 |
from pyspark.sql import functions as F result = employees.filter( (F.col("dept") == "Engineering") | (F.col("salary") > 50000) )
SELECT * FROM employees WHERE dept = 'Engineering' OR salary > 50000
Combining conditions
| Meaning | PySpark | SQL |
|---|---|---|
| and | (a) & (b) | a AND b |
| or | (a) | (b) | a OR b |
| not | ~(a) | NOT a |
| in a list | F.col("dept").isin("HR", "Sales") | dept IN ('HR', 'Sales') |
| range, inclusive | F.col("salary").between(40000, 60000) | salary BETWEEN 40000 AND 60000 |
| is null | F.col("dept").isNull() | dept IS NULL |
and, or and not do not work on columns; you get "Cannot convert column into bool". And because & binds tighter than > in Python, F.col("a") > 1 & F.col("b") < 2 is parsed wrongly. Always wrap each comparison in parentheses.Nulls: the silent row killer
SQL uses three-valued logic: a comparison with null is neither true nor false, it is null. filter keeps only true, so rows with a null in the tested column vanish from both a filter and its opposite.
employees.filter(F.col("dept") == "Sales").count() # 2 employees.filter(F.col("dept") != "Sales").count() # 3, not 4: Farid is in neither
SELECT COUNT(*) FROM employees WHERE dept = 'Sales'; -- 2 SELECT COUNT(*) FROM employees WHERE dept <> 'Sales'; -- 3
To include nulls on purpose, say so: (F.col("dept") != "Sales") | F.col("dept").isNull(), or use the null-safe comparison ~F.col("dept").eqNullSafe("Sales").
Under the hood: predicate pushdown Optional deep dive
CatalystCatalyst: Spark's query optimizer. It rewrites your DataFrame code into a faster equivalent plan before running it. Learn more → moves filters as early as possible, even below joins and into the file scan. ParquetParquet: A columnar file format: values of each column are stored together, so queries read only the columns they need. Learn more → stores min and max values per row grouprow group: A block of rows inside a Parquet file. Its min and max statistics let readers skip blocks that cannot match a filter. Learn more →, so a filter like salary > 90000 lets the reader skip whole row groups whose maximum is lower. In explain() you will see them as PushedFilters.
Part of explain() output
FileScan parquet [name#1,dept#2,salary#3] PushedFilters: [IsNotNull(salary), GreaterThan(salary,90000)]
A filter on a partitionpartition: A chunk of a DataFrame's rows. Spark processes each partition as one task, so partitions decide how much work runs in parallel. Learn more → column is even better: Spark does not open the files of other partitions at all. That is partition pruning.
F.year(F.col("ts")) == 2025, usually prevents it. Compare against a range on the raw column instead: F.col("ts") >= "2025-01-01".Common mistakes
- Using and / or instead of & / | — Python tries to turn a Column into a single bool and raises a ValueError. Use the bitwise operators.
- Leaving out parentheses —
F.col("a") == 1 | F.col("b") == 2is evaluated asF.col("a") == (1 | F.col("b")) == 2. Wrap every comparison. - Comparing with None —
F.col("dept") == Noneis always null, so the filter returns nothing. UseisNull().
Key takeaways
filterandwhereare the same; both keep rows where the condition is true.- Use
&,|,~with parentheses around each comparison. - Null comparisons are null, so those rows drop out of both a filter and its opposite.
- Simple column comparisons are pushed into the scan and can skip whole files and row groups.
Interview prep
THE QUESTION
"Total rows: 1,000. Rows with status = 'active': 600. Rows with status != 'active': 350. Where are the other 50?"
| F.col("status").isNull() or eqNullSafe) and you have answered the real question: do you understand three-valued logic.Avoid: "the rows are lost" or "it is a bug". Say three-valued logic: comparisons with null are null, and filter keeps only true.
Follow-ups · answer out loud, then open
Follow-up"Why does df.filter(col('a') > 1 and col('b') < 5) raise an error?"
and tries to turn each Column into a bool, which PySpark forbids. Use &, | and ~ with parentheses around each comparison, because & binds tighter than > in Python: (F.col("a") > 1) & (F.col("b") < 5).Scenario"Filter users whose country is in a list of 50,000 allowed codes."
isin with 50,000 literals builds a huge expression and plan. Put the codes in a DataFrame and use a left_semi join, which Spark will broadcast if the list is small. That also keeps the list out of the driver-side plan.Trap"filter and where are different: where is the SQL one."
Check yourself
3 questionsA table has 10 rows; 3 have a null country. filter(F.col("country") != "IN") can return at most how many rows?
Show the answer
7. The 3 null rows evaluate to null, not true, so they are never kept. At most the 7 non-null rows can pass.
Which filter is written correctly?
Show the answer
(F.col("a") > 1) & (F.col("b") < 5). Columns need &, and each comparison needs its own parentheses because & binds tighter than comparison operators in Python.
Which filter is most likely to stop Parquet row-group skipping?
Show the answer
F.year("ts") == 2025. Wrapping the column in a function hides it from the min/max statistics. A range on the raw column can be pushed down.
Practise this
Problems that use filter / where, graded on hidden tests
- Paid Orders in MarchFiltering & Selection Easy
- Filter High EarnersFiltering & Selection Easy
- Departments with Large TeamsAggregations Easy
Keep going
Up next · Read and select · lesson 4 of 5 · 6 min readwithColumn
Add or replace one column, and why calling it in a long loop slows Spark down.
Related lessons
eqNullSafe (<=>)PySpark functions · 4 min read
when / otherwiseData lake & lakehouse · 6 min read
Partitioning done right
Previous: select
Primary sources: DataFrame.filter · WHERE clause