Skip to content
Bronze 5 min read · Selection 3 practice problems ↓

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

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.

PySparkSpark SQL
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

namedeptsalary
AshaEngineering72000
BenSales48000
DevHR51000
Faridnullnull: A missing or unknown value. Any comparison with null gives null, so filters treat it as false. Learn more →39000

Output

namedeptsalary
AshaEngineering72000
DevHR51000

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

PySparkSpark SQL

Input: employees

idnamedeptsalarymanager_id
1AshaEngineering72000null
2BenSales480001
3ChitraEngineering950001
4DevHR510001
5EshaSales500002
6Faridnull390002
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

MeaningPySparkSQL
and(a) & (b)a AND b
or(a) | (b)a OR b
not~(a)NOT a
in a listF.col("dept").isin("HR", "Sales")dept IN ('HR', 'Sales')
range, inclusiveF.col("salary").between(40000, 60000)salary BETWEEN 40000 AND 60000
is nullF.col("dept").isNull()dept IS NULL
Watch out: Python's 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.

PySparkSpark SQL · Two filters that do not add up to the whole table
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.

Why this matters: pushdown only works on plain column comparisons. Wrapping the column in a function, like 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") == 2 is evaluated as F.col("a") == (1 | F.col("b")) == 2. Wrap every comparison.
  • Comparing with None — F.col("dept") == None is always null, so the filter returns nothing. Use isNull().

Key takeaways

  • filter and where are 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?"

They have a null status. Comparisons with null return null, and filter keeps only true, so those rows are in neither result. Show the fix (| 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?"
Python's 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."
They are aliases on the DataFrame API and produce the same plan. Both accept a Column or a SQL expression string.

Check yourself

3 questions

A 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

See all 29 problems →

Keep going

Up next · Read and select · lesson 4 of 5 · 6 min read
withColumn
Add or replace one column, and why calling it in a long loop slows Spark down.

Related lessons

Previous: select

Primary sources: DataFrame.filter · WHERE clause