🎬No video for this question yet. The written answer is below.
Write Filter for or condition
📝 Answer
Interviewer:
Can you write a filter condition using OR in PySpark? Also explain how it works in a real-time scenario.
Candidate:
So basically, when I hear this question, I don’t just think about syntax… I think about how filtering impacts performance and data reduction.
Let me explain step by step.
In PySpark, we use the filter or where method to apply conditions. For OR conditions, we use the pipe symbol (|), not the Python “or” keyword.
This is very important because using “or” will not work correctly with column objects.
Let me show the code first.
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
data = [
(1, "Hyderabad", 5000),
(2, "Bangalore", 7000),
(3, "Chennai", 4000),
(4, "Hyderabad", 3000)
]
columns = ["id", "city", "salary"]
df = spark.createDataFrame(data, columns)
# OR condition filter
filtered_df = df.filter((df.city == "Hyderabad") | (df.salary > 6000))
filtered_df.show()
So basically, what is happening here is…
We are filtering records where either the city is Hyderabad OR salary is greater than 6000.
Now let me connect this to a real-time scenario.
In one of my projects, I had to filter data based on multiple conditions like region or revenue threshold.
For example, I needed to process records where region is “US” OR revenue is above a certain limit.
Using OR conditions helped me combine multiple business rules in a single filter.
One important thing I learned is always use parentheses properly, because logical conditions can behave unexpectedly if not grouped correctly.
Also, filtering early in the pipeline helps reduce data size and improves performance.
So basically, OR condition in PySpark is implemented using “|” operator, and it is commonly used for combining multiple filtering conditions.
Interviewer (Follow-up):
Good. What will happen if you use Python 'or' instead of '|' in PySpark?