Skip to main content
PySpark.inData Engineering
Tutorials
  • Python
  • SQL
  • PySpark
  • Machine Learning
  • NLP
  • Deep Learning
  • Linear Algebra
  • Data Engineering
  • All Tutorials
Challenge Arena Compiler Interview Questions Certifications Blogs Jobs Projects CV Builder
Menu
  • All Tutorials
  • Python
  • SQL
  • PySpark
  • Data Engineering
  • Learning Paths
  • Certificate Tracks
  • PySpark Compiler
  • Challenge Arena
  • Projects
  • Production Incidents
  • Boss Battles
  • Datasets
  • Interview Questions
  • Interview Mode
  • Company Prep
  • Certifications
  • DE Roadmap
  • Jobs
  • CV Builder
  • Blogs
  • About
  • Contact

We use cookies to run the site, remember your progress, and serve ads via Google AdSense. By continuing you agree to our Privacy Policy.

Explore

homeAll TutorialscodeLearn PythonanalyticsLearn PySparkterminalOnline Compileremoji_eventsChallenge ArenaarticleBlogsquizInterview QuestionsinfoAbout Uscontact_mailContact Us

Popular Topics

#python#pyspark#sql#spark#dataengineering#bigdata
Home›Interview Questions›PySpark Coding
💻 Interview Prep

PySpark Coding
Interview Questions

Hands-on PySpark problems: joins, window functions, aggregations, UDFs, and performance tuning scenarios.

JoinsWindow FnUDFsAggregationOptimization
10Questions
FreeAlways
search
Vishal Taneja's profile picture
Vishal Taneja·
Sep 13, 2026Interview Question
Q.1
You receive employee data in Spark. How would you calculate a 15% bonus column? Easy

🐍 script.py 37 lines
1from pyspark.sql import SparkSession
2from pyspark.sql.functions import col
3
4# Create SparkSession
5spark = SparkSession.builder \
6 .appName("EmployeeBonus") \
7 .master("local[*]") \
8 .getOrCreate()
9
10# Sample data
11data = [
12 (1, "Amit", 50000),
13 (2, "Rahul", 60000)
14]
15
16# Column names
17columns = ["id", "name", "salary"]
18
19# Create DataFrame
20df = spark.createDataFrame(data, columns)
21
22# Display original data
23print("Original Data:")
24df.show()
25
26# Calculate 15% bonus
27result = df.withColumn(
28 "bonus",
29 col("salary") * 0.15
30)
31
32# Display result
33print("Employee Bonus:")
34result.show()
35
36# Stop Spark
37spark.stop()
▶ Run to see output
✦ AI Explanation

Vishal Taneja's profile picture
Vishal Taneja·
Sep 13, 2026Interview Question
Q.2
Find Employee whoes salary greater than 55,0000? Easy

🐍 script.py 30 lines
1from pyspark.sql import SparkSession
2from pyspark.sql.functions import col
3# 1. Create SparkSession
4spark = SparkSession.builder \
5 .appName("EmployeeFiltering") \
6 .master("local[*]") \
7 .getOrCreate()
8# 2. Create sample employee data
9data = [
10 (1, "Amit", 50000),
11 (2, "Rahul", 60000),
12 (3, "John", 75000),
13 (4, "Priya", 55000),
14 (5, "Neha", 90000)
15]
16
17# 3. Define columns
18columns = ["employee_id", "name", "salary"]
19# 4. Create DataFrame
20df = spark.createDataFrame(data, columns)
21# 5. Display original DataFrame
22print("Original Data:")
23df.show()
24# 6. Filter employees whose salary is greater than 55,000
25result = df.filter(col("salary") > 55000)
26# 7. Display filtered result
27print("Employees with salary greater than 55,000:")
28result.show()
29# 8. Stop Spark
30spark.stop()
▶ Run to see output
✦ AI Explanation

Vishal Taneja's profile picture
Vishal Taneja·
Sep 4, 2026Interview Question
Q.3
A bank wants to identify customers whose salary has significantly declined over the last 3 months. Hard

Business Requirement

A bank wants to identify customers whose salary has significantly declined over the last 3 months.

Risk Criteria

  1. Customer should have monthly salary credits.
  2. Compare the latest month's salary with the average salary of the previous 3 months.
  3. If the salary has dropped by more than 40%, flag the customer.
  4. Ignore customers having fewer than 4 salary credits.

Input DataFrame

account_transactions

account_idtxn_datetxn_typeamount
10012024-01-05CREDIT100000
10012024-02-05CREDIT105000
10012024-03-05CREDIT98000
10012024-04-05CREDIT50000
10022024-01-05CREDIT70000
10022024-02-05CREDIT72000
10022024-03-05CREDIT71000
10022024-04-05CREDIT70000

Expected Output

account_idavg_previous_3_monthscurrent_salarydrop_percentagerisk_flag
1001101000.005000050.50%FLAG
100271000.00700001.41%NOT_FLAG


🐍 script.py 197 lines
1from pyspark.sql import SparkSession
2from pyspark.sql.functions import (
3 col,
4 avg,
5 count,
6 round,
7 when,
8 row_number
9)
10from pyspark.sql.window import Window
11# ============================================================
12# 1. Create Spark Session
13# ============================================================
14spark = SparkSession.builder \
15 .appName("SalaryDropAnalysis") \
16 .master("local[*]") \
17 .getOrCreate()
18# ============================================================
19# 2. Create Source Data
20# ============================================================
21data = [
22 (1001, "2024-01-05", "CREDIT", 100000),
23 (1001, "2024-02-05", "CREDIT", 105000),
24 (1001, "2024-03-05", "CREDIT", 98000),
25 (1001, "2024-04-05", "CREDIT", 50000),
26 (1002, "2024-01-05", "CREDIT", 70000),
27 (1002, "2024-02-05", "CREDIT", 72000),
28 (1002, "2024-03-05", "CREDIT", 71000),
29 (1002, "2024-04-05", "CREDIT", 70000),
30
31 # Only 3 credits - should be ignored
32 (1003, "2024-02-05", "CREDIT", 80000),
33 (1003, "2024-03-05", "CREDIT", 82000),
34 (1003, "2024-04-05", "CREDIT", 40000)
35]
36
37columns = [
38 "account_id",
39 "txn_date",
40 "txn_type",
41 "amount"
42]
43
44# ============================================================
45# 3. Create DataFrame
46# ============================================================
47df = spark.createDataFrame(data, columns)
48print("SOURCE DATA")
49df.show()
50# ============================================================
51# 4. Convert transaction date to date
52# ============================================================
53df = df.withColumn(
54 "txn_date",
55 col("txn_date").cast("date")
56)
57
58# ============================================================
59# 5. Keep only salary CREDIT transactions
60# ============================================================
61salary_df = df.filter(
62 col("txn_type") == "CREDIT"
63)
64print("SALARY CREDIT DATA")
65salary_df.show()
66
67# ============================================================
68# 6. Check customers having at least 4 salary credits
69# ============================================================
70valid_customers = salary_df \
71 .groupBy("account_id") \
72 .agg(
73 count("*").alias("credit_count")
74 ) \
75 .filter(
76 col("credit_count") >= 4
77 )
78
79print("CUSTOMERS WITH AT LEAST 4 CREDITS")
80valid_customers.show()
81# ============================================================
82# 7. Keep only valid customers
83# ============================================================
84salary_df = salary_df.join(
85 valid_customers.select("account_id"),
86 on="account_id",
87 how="inner"
88)
89
90# ============================================================
91# 8. Create Window
92#
93# Latest transaction gets rn = 1
94# Previous transactions get rn = 2, 3, 4
95# ============================================================
96window_spec = Window \
97 .partitionBy("account_id") \
98 .orderBy(col("txn_date").desc())
99# ============================================================
100# 9. Assign row number
101# ============================================================
102salary_df = salary_df.withColumn(
103 "rn",
104 row_number().over(window_spec)
105)
106print("DATA WITH ROW NUMBER")
107salary_df.show()
108# ============================================================
109# 10. Get latest salary
110# ============================================================
111current_salary_df = salary_df \
112 .filter(col("rn") == 1) \
113 .select(
114 "account_id",
115 col("amount").alias("current_salary")
116 )
117print("CURRENT SALARY")
118current_salary_df.show()
119# ============================================================
120# 11. Get previous 3 months average salary
121# ============================================================
122previous_salary_df = salary_df \
123 .filter(col("rn").between(2, 4)) \
124 .groupBy("account_id") \
125 .agg(
126 avg("amount").alias("avg_previous_3_months")
127 )
128print("AVERAGE OF PREVIOUS 3 MONTHS")
129previous_salary_df.show()
130# ============================================================
131# 12. Join current salary and previous salary
132# ============================================================
133
134result_df = current_salary_df.join(
135 previous_salary_df,
136 on="account_id",
137 how="inner"
138)
139
140# ============================================================
141# 13. Calculate salary drop percentage
142#
143# Drop % =
144# ((Previous Average - Current Salary)
145# / Previous Average) * 100
146# ============================================================
147
148result_df = result_df.withColumn(
149 "drop_percentage",
150 round(
151 (
152 (
153 col("avg_previous_3_months")
154 - col("current_salary")
155 )
156 / col("avg_previous_3_months")
157 ) * 100,
158 2
159 )
160)
161
162# ============================================================
163# 14. Apply Risk Rule
164#
165# Drop > 40% --> FLAG
166# Otherwise --> NOT_FLAG
167# ============================================================
168
169result_df = result_df.withColumn(
170 "risk_flag",
171 when(
172 col("drop_percentage") > 40,
173 "FLAG"
174 ).otherwise("NOT_FLAG")
175)
176
177# ============================================================
178# 15. Final Result
179# ============================================================
180
181final_df = result_df.select(
182 "account_id",
183 "avg_previous_3_months",
184 "current_salary",
185 "drop_percentage",
186 "risk_flag"
187).orderBy("account_id")
188
189print("FINAL RESULT")
190
191final_df.show(truncate=False)
192
193# ============================================================
194# 16. Stop Spark
195# ============================================================
196
197spark.stop()
▶ Run to see output
✦ AI Explanation

pyspark's profile picture
pyspark·
Sep 4, 2026Interview Question
Q.4
Given a DataFrame containing flight/train routes and fares, find the cheapest fare between a source and destination, including the possibility of travelling through an intermediate city? Medium

​Input DataFrame

Suppose we have this route data:

sourcedestinationfare
DelhiMumbai5000
DelhiPune3000
PuneMumbai1500
DelhiBangalore4000
BangaloreMumbai2500
DelhiChennai4500
ChennaiMumbai3000

We want to find the cheapest way to travel:

Delhi → Mumbai

Possible routes

RouteCalculationTotal Fare
Delhi → Mumbai50005000
Delhi → Pune → Mumbai3000 + 15004500
Delhi → Bangalore → Mumbai4000 + 25006500
Delhi → Chennai → Mumbai4500 + 30007500

Therefore:

Cheapest fare = ₹4,500

Route = Delhi → Pune → Mumbai

🐍 script.py 51 lines
1from pyspark.sql import SparkSession
2from pyspark.sql.functions import col
3# Create Spark Session
4spark = SparkSession.builder \
5 .appName("CheapestFare") \
6 .getOrCreate()
7# Route data
8data = [
9 ("Delhi", "Mumbai", 5000),
10 ("Delhi", "Pune", 3000),
11 ("Pune", "Mumbai", 1500),
12 ("Delhi", "Bangalore", 4000),
13 ("Bangalore", "Mumbai", 2500),
14 ("Delhi", "Chennai", 4500),
15 ("Chennai", "Mumbai", 3000)
16]
17columns = ["source", "destination", "fare"]
18routes_df = spark.createDataFrame(data, columns)
19# Self join to find routes through an intermediate city
20first_leg = routes_df.alias("a")
21second_leg = routes_df.alias("b")
22via_city = first_leg.join(
23 second_leg,
24 col("a.destination") == col("b.source"),
25 "inner"
26)
27# Filter source and destination
28via_city = via_city.filter(
29 (col("a.source") == "Delhi") &
30 (col("b.destination") == "Mumbai")
31)
32# Calculate total fare
33via_city = via_city.withColumn(
34 "total_fare",
35 col("a.fare") + col("b.fare")
36)
37# Select required columns
38result = via_city.select(
39 col("a.source").alias("source"),
40 col("a.destination").alias("intermediate_city"),
41 col("b.destination").alias("destination"),
42 col("a.fare").alias("first_leg_fare"),
43 col("b.fare").alias("second_leg_fare"),
44 col("total_fare")
45)
46# Find cheapest route
47cheapest = result.orderBy(
48 col("total_fare").asc()
49).limit(1)
50
51cheapest.show()
▶ Run to see output
✦ AI Explanation

Logic Explain:
“I have a routes DataFrame containing source, destination and fare. To find a route through an intermediate city, I self-join the DataFrame. The destination of the first leg should match the source of the second leg. Then I add the two fares to calculate the total fare and order by total fare ascending. Finally, I take the first record, which gives me the cheapest route.

Remember the logic

Self Join → Find Intermediate City → Add Fares → Sort Ascending → limit(1)

pyspark's profile picture
pyspark·
Sep 4, 2026Interview Question
Q.5
Given a sales DataFrame containing product_id, unit_price, and quantity, write PySpark code to calculate the total amount for each product and the overall total sales amount. Easy

1. Input DataFrame

Think of the DataFrame like this table:

product_idunit_pricequantity
101100.02
102200.03
10350.04
104150.02

For each row:

Total Amount = unit_price × quantity


🐍 script.py 32 lines
1from pyspark.sql import SparkSession
2from pyspark.sql.functions import col, sum
3# Create Spark Session
4spark = SparkSession.builder \
5 .appName("SalesCalculation") \
6 .getOrCreate()
7# Sample sales data
8data = [
9 (101, 100.0, 2),
10 (102, 200.0, 3),
11 (103, 50.0, 4),
12 (104, 150.0, 2)
13]
14columns = ["product_id", "unit_price", "quantity"]
15# Create DataFrame
16sales_df = spark.createDataFrame(data, columns)
17print("Input Data:")
18sales_df.show()
19# Calculate total amount for each row
20sales_with_amount = sales_df.withColumn(
21 "total_amount",
22 col("unit_price") * col("quantity")
23)
24print("Sales with Total Amount:")
25sales_with_amount.show()
26# Calculate overall total sales
27total_sales = sales_with_amount.agg(
28 sum("total_amount").alias("total_sales_amount")
29)
30print("Overall Total Sales:")
31total_sales.show()
32spark.stop()
▶ Run to see output
✦ AI Explanation


Nitesh Kumar Sharma's profile picture
Nitesh Kumar Sharma·
Sep 1, 2026Interview Question
Q.6
Detect Salary Drop Risk Customers Hard
Business Requirement
The bank wants to identify customers whose salary has significantly declined over the last 3 months.

Risk Criteria:
  1. Customer receives monthly salary credits.
  2. Compare latest month salary with average of previous 3 months.
  3. If salary drops by more than 40%, flag them.
  4. Ignore customers with fewer than 4 salary credits.

account_transactions txn_date    txn_type amount
1001    2024-01-05 CREDIT   100000  
1001     2024-02-05 CREDIT   105000  
1001     2024-03-05 CREDIT   98000
1001     2024-04-05 CREDIT   50000

1002     2024-01-05 CREDIT   70000
1002    2024-02-05 CREDIT   72000
1002    2024-03-05 CREDIT   71000
1002    2024-04-05 CREDIT   70000
 

Output details

Customer 1001 gets flagged.
Avg Salary:
(100000+105000+98000)/3 = 101000
Current Salary:
50000
Drop = 50.49%
Vishal Taneja's profile picture
Vishal Taneja·
Apr 20, 2026Interview Question
Q.7
Find the number of transactions that occurred for each product. Output the product name along with the transaction count and sort by product_id Hard

You are given two datasets:

1. Inventory Table

  product_id

  product_name

2. Transactions Table

transaction_id

time

product_id

Output the product name along with the transaction count and sort by product_id.

Handle duplicate transactions (keep latest)

Count the number of transactions per product

Exclude products with no transactions

Sort the result by product_id

🐍 script.py 58 lines
1inventory_data = [
2 (1, 'strawberry'),
3 (2, 'apple_fuji'),
4 (3, 'orange'),
5 (4, 'clementines'),
6 (5, 'blood_orange'),
7 (6, 'banana') # no transactions (to test filtering)
8]
9
10inv_cols = ["product_id", "product_name"]
11
12transaction_data = [
13 (153, '2016-01-06 08:57:52', 1),
14 (91, '2016-01-07 12:17:27', 1),
15 (31, '2016-01-05 13:19:25', 1),
16 (24, '2016-01-03 10:47:44', 3),
17 (4, '2016-01-06 17:57:42', 3),
18 (163, '2016-01-03 10:11:22', 3),
19 (92, '2016-01-08 12:03:20', 2),
20 (32, '2016-01-04 19:37:14', 4),
21 (253, '2016-01-06 14:15:20', 5),
22 (118, '2016-01-06 14:27:33', 5),
23 (118, '2016-01-07 14:27:33', 5), # duplicate (keep latest)
24 (300, '2016-01-02 09:00:00', 7) # product not in inventory (to test join)
25]
26
27trans_cols = ["transaction_id", "time", "product_id"]
28from pyspark.sql import SparkSession
29from pyspark.sql.functions import col, row_number, count
30from pyspark.sql.window import Window
31
32spark = SparkSession.builder.appName("InterviewSolution").getOrCreate()
33
34# DataFrames
35inv_df = spark.createDataFrame(inventory_data, ["product_id", "product_name"])
36trans_df = spark.createDataFrame(transaction_data, ["transaction_id", "time", "product_id"])
37
38# Step 1: Cast time to timestamp
39trans_df = trans_df.withColumn("time", col("time").cast("timestamp"))
40
41# Step 2: Deduplicate using window
42window_spec = Window.partitionBy("transaction_id").orderBy(col("time").desc())
43
44dedup_df = trans_df.withColumn("rn", row_number().over(window_spec)) \
45 .filter(col("rn") == 1) \
46 .drop("rn")
47
48# Step 3: Inner join
49joined_df = dedup_df.join(inv_df, on="product_id", how="inner")
50
51# Step 4: Aggregate
52result_df = joined_df.groupBy("product_id", "product_name") \
53 .agg(count("*").alias("transaction_count"))
54
55# Step 5: Sort
56final_df = result_df.orderBy("product_id")
57
58final_df.show()
▶ Run to see output
✦ AI Explanation

Vishal Taneja's profile picture
Vishal Taneja·
Apr 20, 2026Interview Question
Q.8
You are given two datasets: customers(customer_id, name, city) orders(customer_id, item, amount) Easy

Write a PySpark program to perform an JOIN and return only customers who have placed at least one order.


🐍 script.py 31 lines
1customers = [
2 ("C001", "Arjun", "Chennai"),
3 ("C002", "Priya", None),
4 ("C003", "Ravi", None)
5]
6
7orders = [
8 ("C001", "Idli", 50),
9 ("C002", "Coffee", 120),
10 ("C004", "Dosa", 60)
11]
12
13from pyspark.sql import SparkSession
14from pyspark.sql.functions import col
15
16# Create Spark session
17spark = SparkSession.builder.appName("CustomerOrders").getOrCreate()
18
19# Create DataFrames
20customers_df = spark.createDataFrame(customers, ["customer_id", "name", "city"])
21orders_df = spark.createDataFrame(orders, ["customer_id", "item", "amount"])
22
23# Perform INNER JOIN
24result_df = customers_df.join(orders_df, on="customer_id", how="inner")
25
26# Select only customer columns
27final_df = result_df.select("customer_id", "name", "city")
28
29# Show result
30
31final_df.show()
▶ Run to see output
✦ AI Explanation

Sandip Shaw (M24DE3069)(G23AI2095)'s profile picture
Sandip Shaw (M24DE3069)(G23AI2095)·
Apr 8, 2026Interview Question
Q.9
Give me the list of students who are coming for consecutive 3 days. Easy
student_idattendance_date
101-05-2025
201-05-2025
301-05-2025
102-05-2025
202-05-2025
302-05-2025
203-05-2025
303-05-2025
104-05-2025
204-05-2025

🗄 query.sql 25 lines
1CREATE TABLE attendance (
2 student_id INT,
3 attendance_date DATE
4
5);
6INSERT INTO attendance VALUES
7(1,'2025-05-01'),
8(2,'2025-05-01'),
9(3,'2025-05-01'),
10(1,'2025-05-02'),
11(2,'2025-05-02'),
12(3,'2025-05-02'),
13(2,'2025-05-03'),
14(3,'2025-05-03'),
15(1,'2025-05-04'),
16(2,'2025-05-04');
17
18SELECT DISTINCT a1.student_id
19FROM attendance a1
20JOIN attendance a2
21 ON a1.student_id = a2.student_id
22 AND a2.attendance_date = DATE_ADD(a1.attendance_date, INTERVAL 1 DAY)
23JOIN attendance a3
24 ON a1.student_id = a3.student_id
25 AND a3.attendance_date = DATE_ADD(a1.attendance_date, INTERVAL 2 DAY);
▶ Run to see output
✦ AI Explanation

Vishal Taneja's profile picture
Vishal Taneja·
Feb 21, 2026Interview Question
Q.10
Find Dupliacates records in a table? Easy

Table:Employee

idnamedepartment
1AmitIT
2NehaHR
3AmitIT
4RahulSales
5NehaHR

🗄 query.sql 18 lines
1CREATE TABLE employees (
2 id INT PRIMARY KEY,
3 name VARCHAR(100),
4 department VARCHAR(100)
5);
6
7INSERT INTO employees (name, department) VALUES
8('Amit', 'IT'),
9('Neha', 'HR'),
10('Amit', 'IT'),
11('Rahul', 'Sales'),
12('Neha', 'HR'),
13('Sonia', 'Finance');
14
15SELECT name, COUNT(*) AS duplicate_count
16FROM employees
17GROUP BY name
18HAVING COUNT(*) > 1;
▶ Run to see output
✦ AI Explanation

PySpark.inData Engineering

A learning and career platform for Data Engineering — structured tutorials, a browser-based PySpark compiler, coding challenges, interview preparation and certifications.

Learn

  • Python
  • SQL
  • PySpark
  • Machine Learning
  • NLP
  • Deep Learning
  • Linear Algebra
  • Data Engineering
  • All Tutorials

Practise

  • PySpark Compiler
  • Challenge Arena
  • Challenges by Topic
  • Dataset Library
  • Interview Questions

Career

  • Certifications
  • CV Builder
  • Jobs

Resources

  • Blogs
  • Projects
  • Certificate Tracks

Company

  • About
  • Contact
  • Terms
  • Privacy Policy

Stay ahead in Data Engineering

Weekly tutorials, PySpark tips, SQL challenges and interview questions.

© 2026 PySpark.in. All rights reserved.

TermsPrivacyCookies