The PySpark round

Part of the free LogicWiz Data Engineering course, Module 18: Interview rounds. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is the PySpark round. You solved the SQL question in ten minutes, and the interviewer smiles: "Good. Now write it in PySpark, as a function that takes a DataFrame and returns one." The logic is the same. The words are different, and so are the traps: a NULL that a != filter quietly drops, a join that doubles revenue, a nested items array to flatten.

You'll learn to

  • Translate the classic SQL patterns into DataFrame code with `F` and `Window`
  • Handle nested data with `explode`, and read and write files safely
  • Spot the Spark traps: NULL filters, fan-out joins and rerun writes

Learn

How the round runs

A Spark interview has two halves. First you write DataFrame code for a problem you could also solve in SQL. Then you explain how Spark runs it (the rapid-fire round covers that half).

Interviewers want code a Spark engineer would write: built-in functions from pyspark.sql.functions (imported as F), Window specs, no Python UDFs, and no collect() of big data to the driver.

Many ask for a function that takes DataFrames and returns a DataFrame, so it can be tested on a tiny input. Every problem below is graded that way: hidden tests build small DataFrames and check the collected values.

In this browser the PySpark syntax runs on DuckDB. Stick to the common API, and check results with collect(), not show().

SQL to DataFrame

SQLPySpark
ROWNUMBER() OVER (PARTITION BY k ORDER BY ts DESC)F.rownumber().over(Window.partitionBy('k').orderBy(F.col('ts').desc()))
LAG(x) OVER (ORDER BY day)F.lag('x').over(Window.orderBy('day'))
SUM(x) OVER (... ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)F.sum('x').over(w.rowsBetween(Window.unboundedPreceding, Window.currentRow))
CASE WHEN ... THEN ... ELSE ... ENDF.when(cond, a).otherwise(b)
WHERE NOT EXISTS (...)a.join(b, 'k', 'leftanti')
WHERE EXISTS (...)a.join(b, 'k', 'leftsemi')
COUNT() FILTER (WHERE status = ...) per columngroupBy('d').pivot('status', [...]).agg(F.count('orderid'))
UNNEST(items), a field inside a JSON objectF.explode('items'), F.col('device.os')
seconds between two timestampsF.unixtimestamp('ts') - F.unixtimestamp('prevts')

Read each row left to right: the SQL you know, then its twin. If you can write it in SQL, you can write it here: the window, the join type and the aggregate all have a direct twin.

Build one answer: the latest payment per order

Take a question you have already solved in SQL: an order can have several payments, and you want the latest one.

In SQL it is ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY paid_ts DESC), then keep row 1. In PySpark it is the same four moves, each with its own name:

  1. Partition: put each order's payments together.
  2. Order: newest first, with a tie-breaker.
  3. Number: F.row_number() over that window.
  4. Filter: keep rn == 1.

Follow two real orders through the four moves. Order 1012 failed once and then went through. Order 1033 was charged twice.

Four payments, four moves, two rows kept

The payments of orders 1012 and 1033 are grouped per order, sorted newest first, numbered with row_number, and filtered to the first row of each group.

  1. Partition. Window.partitionBy('order_id') puts each order's payments in their own group.

  2. Order. Inside each group, sort newest first: paid_ts descending, then payment_id descending as the tie-breaker.

  3. Number. F.row_number().over(w) numbers the rows of each group, starting again at 1 for every order.

  4. Filter. Keep rn == 1: one payment per order, and you can say which one and why. The failed attempt and the double charge are gone.

Each box is one order's group. dropDuplicates(['order_id']) would also leave one row per order, but you could not say which one. The window makes the choice explicit.

The same four moves as code

from pyspark.sql import SparkSession, Window
from pyspark.sql import functions as F

spark = SparkSession.builder.getOrCreate()

payments = spark.read.json('data/payments.jsonl')
w = Window.partitionBy('order_id').orderBy(F.col('paid_ts').desc(), F.col('payment_id').desc())
ranked = payments.withColumn('rn', F.row_number().over(w))

for r in ranked.filter(F.col('order_id').isin(1012, 1033)).orderBy('order_id', 'rn').collect():
    print(r['order_id'], r['payment_id'], r['status'], r['rn'])

latest = ranked.filter(F.col('rn') == 1).drop('rn')
print('orders:', latest.count())

Line by line: w is the partition and the order, row_number numbers the rows, the filter keeps rn == 1. Printing collected values, not show(), keeps the output identical here and on real Spark.

What real Spark runs for the window

A simplified physical plan for the latest-payment query: a JSON file scan, a hash exchange on order_id into 200 partitions, a sort by order_id, paid_ts and payment_id, the Window operator computing row_number, and a filter keeping rank 1.

Read it from the bottom up. It is simplified from explain() on a cluster. The window's partitionBy becomes a shuffle (the Exchange node), so the follow-up "what if one order has a million payments?" is a skew question: that key's rows all land in one task.

A partitioned write on real Spark

Runs on Databricks:

(orders_clean.write
    .mode("overwrite")
    .partitionBy("order_date")
    .parquet("/Volumes/main/swiftkart/clean/orders"))

spark.read.parquet("/Volumes/main/swiftkart/clean/orders") \
    .filter("order_date = '2025-06-05'").count()
6

The round often ends with "now save it". On a cluster, partitionBy writes one folder per date, and the filter reads only one of them. The browser engine writes a single Parquet file, so the problems below use write.mode('overwrite').parquet(path) without it. The default mode, errorifexists, fails the second time a job runs: say "overwrite" or "merge" out loud.

Write the window spec on its own line and name it (w = Window.partitionBy(...)). It reads like your SQL and is easy to discuss. Then say what Spark does with it: "this window shuffles by order_id; if one key is huge, that task is skewed." Linking the code to how it runs is what separates a Spark engineer from someone who memorised the API.

The trap: what interviewers plant in Spark code. F.col('user_id') != 5 drops every row where user_id is NULL, exactly like SQL. Joining order lines to payments before aggregating doubles the revenue of an order that was charged twice. A Python UDF works but is slow, because every row leaves the JVM: a built-in F function almost always exists. And collect() on a billion rows crashes the driver.

Remember: partition, order, number, filter. Write the window on its own line and give it a name.

Next is the modelling round: no code at all, only tables on a whiteboard.

In one line

PySpark is your SQL written as method calls: a named Window for ranking and running totals, anti and semi joins, explode for nested data, and overwrite so a rerun is safe.

Interview corner

How do you get the top N rows per group in PySpark?

Define w = Window.partitionBy('group').orderBy(F.col('value').desc(), F.col('id')), add F.row_number().over(w) as a column and filter it <= N. I use row_number for exactly N rows and dense_rank when ties should share a place. The window shuffles the data by the group key, so a very large group can skew one task.

How do you deduplicate in Spark, and when is dropDuplicates not enough?

dropDuplicates() removes exact copies, and dropDuplicates(['key']) keeps one row per key, but which row it keeps is not defined. When I must keep the latest version, I use a window per key ordered by the timestamp descending (with a tie-breaker) and keep row_number() == 1.

Why avoid Python UDFs?

A Python UDF sends every row from the JVM to a Python worker and back, which is slow, and the optimiser cannot see inside it to push filters or prune columns. Built-in F functions run inside the engine and are optimised. If logic truly needs Python, a vectorised pandas UDF is the better option.

What does explode do with empty or NULL arrays?

explode produces one row per array element and drops rows whose array is empty or NULL. explode_outer keeps them with a NULL element. After exploding, struct fields are selected with dot paths such as F.col('item.product_id').