Translate it: SQL to DataFrame code

Part of the free LogicWiz Data Engineering course, Module 11: PySpark DataFrames. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 4:30 on Friday. This week you moved Tess's reports from Postgres to Spark, rewriting each SQL query as DataFrame code. Most match to the cent. One does not: "customers who never ordered" said 0 in Postgres and says 2 in Spark. Every clause of your translation looks right.

You'll learn to

  • Translate a SELECT into DataFrame code, clause by clause
  • Rewrite the sessions query from Module 2 in PySpark
  • Spot where Postgres and Spark give different answers
  • Avoid the Python operator mistakes that break filters

Learn

A method, not a memory test

Nora does not start with the broken report. She asks how you translate at all. A PySpark interview opens the same way: "Here is the query. Same answer, DataFrame API, no spark.sql."

SQL is written SELECT ... FROM ... WHERE ..., but it runs in another order (Module 2): FROM and JOIN first, SELECT near the end. DataFrame code is written in exactly that running order, top to bottom. So the method is:

  1. Say the grain of the result out loud ("one row per customer").
  2. Walk the clauses in running order and write one method for each.
  3. Check it on the data: run both versions and compare the collected rows.

The order SQL runs in, and the method for each step

Nine steps from top to bottom: from and join, where, group by, having, window functions, select, distinct, order by and limit, each with its DataFrame method.

Read it top to bottom: each box is a SQL clause, and the line under it is the method you write.

SQL clause, PySpark twin

SQLDataFrame API
FROM a JOIN b ON a.k = b.ka.join(b, "k"), with how="left" for LEFT JOIN
WHERE ... (before grouping).filter(...) before groupBy
GROUP BY x with aggregates.groupBy("x").agg(F.sum(...).alias(...), ...)
HAVING COUNT() = 3.filter(F.col("n") = 3) after agg
CASE WHEN ... THEN ... ELSE ... ENDF.when(...).when(...).otherwise(...)
COUNT(DISTINCT x), COALESCE(a, b)F.countDistinct("x"), F.coalesce("a", "b")
ROWNUMBER() OVER (...), LAG(x) OVER (...).withColumn(..., F.rownumber().over(w))
WHERE EXISTS / NOT EXISTS (...)a.join(b, "k", "leftsemi") / "leftanti"
SELECT x AS y.select(F.col("x").alias("y"))
ORDER BY r DESC, k LIMIT 3.orderBy(F.desc("r"), "k").limit(3)

Top customers, clause by clause

Take a report that did match: the top 3 customers by revenue, among those with at least 2 delivered or shipped orders. The grain is one row per customer.

Now walk the SQL in running order. The joins come first, although SELECT is the first word on the page. WHERE becomes a filter before groupBy. HAVING becomes a filter after agg, on the alias you gave the aggregate. ORDER BY and LIMIT close the chain.

Step through it below, then run both versions and compare.

One clause at a time

The SQL query for top customers on the left, as written, and the DataFrame chain on the right growing one method at a time in the order the SQL runs: joins, where, group by with aggregates, having, order by and limit.

  1. FROM and JOIN run first. SELECT is the first word on the page, but the tables come first: start from orders and join the other two on their keys.

  2. WHERE. The status filter runs before any grouping, so it goes before groupBy. IN becomes isin.

  3. GROUP BY, with the aggregates from SELECT. groupBy takes the grain. The two aggregates move into agg, each with the alias the SELECT gave it.

  4. HAVING. It runs after the grouping, so it is a second filter, after agg, on the alias orders.

  5. ORDER BY, then LIMIT. Sort first, with customer_id as the tie-breaker, and only then keep 3 rows. Limiting first would keep 3 arbitrary rows and sort only those.

The green line jumps around the SQL; the chain on the right only grows downwards.

Top customers, both ways

from pyspark.sql import SparkSession, functions as F

spark = SparkSession.builder.getOrCreate()
orders = spark.read.csv("data/orders.csv", header=True, inferSchema=True)
items = spark.read.csv("data/order_items.csv", header=True, inferSchema=True)
customers = spark.read.csv("data/customers.csv", header=True, inferSchema=True)
for name, df in [("orders", orders), ("order_items", items), ("customers", customers)]:
    df.createOrReplaceTempView(name)

sql = spark.sql("""
    SELECT o.customer_id, c.country,
           COUNT(DISTINCT o.order_id) AS orders,
           ROUND(SUM(i.qty * i.unit_price), 2) AS revenue
    FROM orders o
    JOIN order_items i ON i.order_id = o.order_id
    JOIN customers c ON c.customer_id = o.customer_id
    WHERE o.status IN ('delivered', 'shipped')
    GROUP BY o.customer_id, c.country
    HAVING COUNT(DISTINCT o.order_id) >= 2
    ORDER BY revenue DESC, o.customer_id
    LIMIT 3
""")

api = (
    orders                                                         # FROM orders
    .join(items, "order_id")                                       # JOIN order_items
    .join(customers.select("customer_id", "country"), "customer_id")  # JOIN customers
    .filter(F.col("status").isin("delivered", "shipped"))          # WHERE
    .groupBy("customer_id", "country")                             # GROUP BY
    .agg(F.countDistinct("order_id").alias("orders"),
         F.round(F.sum(F.col("qty") * F.col("unit_price")), 2).alias("revenue"))
    .filter(F.col("orders") >= 2)                                  # HAVING
    .orderBy(F.desc("revenue"), "customer_id")                     # ORDER BY
    .limit(3)                                                      # LIMIT
)
print([tuple(r) for r in sql.collect()])
print([tuple(r) for r in api.collect()])
print("same answer:", [tuple(r) for r in sql.collect()] == [tuple(r) for r in api.collect()])

The comments line up each method with the clause it replaces. The last line is step 3 of the method: it compares the collected rows of the two versions.

Remember: say the grain, then each clause as you type its method. Stuck on a function name in an interview? Say the SQL and offer F.expr("..."): the structure matters more than remembering countDistinct.

Both versions, one plan

Both versions print the same three rows. As Lesson 11.6 showed, the SQL text and the method chain become one plan, which is why neither is faster.

The tree below is that plan after Catalyst has improved it. Two things moved. Your WHERE now sits right on top of orders, below both joins: the optimiser pushed it down so fewer rows reach the joins. And Sort with Limit run as one step, in which every task keeps only its own top 3 and the driver merges them. The table is never fully sorted.

One optimised plan for both versions

A logical plan tree: a limit over a sort over a filter on orders over an aggregate by customer and country, over two inner joins, with the status filter pushed down onto the orders relation.

Read it from the bottom up, from the three tables to the limit. The rule that moved the WHERE is PushPredicateThroughJoin; in the physical plan Sort plus Limit become TakeOrderedAndProject.

The hard one: sessions

The hardest report on the list was Module 2's sessions: a new session starts when more than 30 minutes pass since the user's previous event. The SQL used three steps, and each has a twin:

  1. LAG(ts) OVER (PARTITION BY user_id ORDER BY ts) gives the previous event's time: F.lag('ts').over(w).
  2. CASE WHEN prev_ts IS NULL OR gap > 30 minutes THEN 1 ELSE 0 END flags the first event of each session: F.when(...).otherwise(0). The gap in minutes is (F.unix_timestamp('ts') - F.unix_timestamp('prev_ts')) / 60.
  3. A running SUM of the flags numbers the sessions: F.sum('new_session').over(w.rowsBetween(Window.unboundedPreceding, Window.currentRow)).

This is the gaps-and-islands trick: a running sum of "something new starts here" flags turns a stream into numbered groups.

User 6, step by step

tsprevtsgapminnewsessionsessionno
2025-06-01 13:43:01nullnull11
2025-06-01 13:44:0113:43:01101
2025-06-01 15:12:0113:44:018812
2025-06-01 15:13:0115:12:01102
2025-06-02 14:46:522025-06-01 15:33:011393.8513
2025-06-02 16:06:5215:03:526314

Some rows are left out. Every flag of 1 starts a new island, and the running sum carries the session number down to the rows after it. User 6 had four sessions over two days.

The operators that bite

The flag in step 2 joins two conditions with OR. That is where translations break: not on the window, but on Python operators.

  • &, |, ~, never and, or, not. Python's and cannot combine two columns.
  • Brackets around every comparison. In Python & and | bind more tightly than ==, so F.col('a') == 1 & F.col('b') == 2 is parsed as F.col('a') == (1 & F.col('b')) == 2. Write (F.col('a') == 1) & (F.col('b') == 2).
  • == to compare; a single = is assignment.
  • isin('a', 'b') for IN, isNull() for IS NULL.

When a condition reads more clearly as SQL, a string works too: filter("status = 'placed' AND customer_id > 5").

and between two columns. On Databricks, filter((F.col("status") == "placed") and (F.col("customer_id") > 5)) stops with ValueError: Cannot convert column into bool. The browser engine is worse: it silently keeps only the second condition and returns the wrong rows. Use & and wrap each comparison in brackets.

Sessions in PySpark

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

spark = SparkSession.builder.getOrCreate()
events = spark.read.json("data/events.jsonl").filter(F.col("user_id").isNotNull())

w = Window.partitionBy("user_id").orderBy("ts", "event_id")
flagged = (
    events
    .withColumn("prev_ts", F.lag("ts").over(w))
    .withColumn("gap_min", (F.unix_timestamp("ts") - F.unix_timestamp("prev_ts")) / 60)
    .withColumn("new_session", F.when(F.col("prev_ts").isNull() | (F.col("gap_min") > 30), 1).otherwise(0))
    .withColumn("session_no", F.sum("new_session").over(w.rowsBetween(Window.unboundedPreceding, Window.currentRow)))
)
per_user = flagged.groupBy("user_id").agg(F.max("session_no").alias("sessions"))
print("users:", per_user.count(), " sessions:", per_user.agg(F.sum("sessions").alias("s")).first()["s"])
print("busiest:", [(r["user_id"], r["sessions"]) for r in per_user.orderBy(F.desc("sessions"), "user_id").limit(3).collect()])

The four withColumn lines are the four new columns of the table above; the flag line joins two bracketed conditions with |. On Databricks, spark.read.json leaves ts as text (Lesson 11.4), and F.unix_timestamp cannot read text like 2025-06-01T13:43:01Z: add .withColumn("ts", F.to_timestamp("ts")) after the read, or read with a schema.

Why 0 became 2

Now the Friday report. The Postgres query said: customers whose id is NOT IN the list of customer ids on orders. You translated it as a left_anti join, the twin of NOT EXISTS. Clause-perfect.

Nora asks one question: "Is there a null in that list?" There is. A late order in the feed has lost its customer id.

In SQL a null means "unknown". NOT IN asks whether your id differs from every value in the list. A left_anti join asks something else: is there a match? The two questions agree until an unknown value joins the list.

Customer 12 meets a list with a null

Customer 12, who never ordered, is checked against a list of 28 customer ids and one null: NOT IN gets an unknown answer and drops the customer, while a left anti join finds no match and keeps the customer.

  1. The list. 28 customers have orders, so the list holds their 28 ids, plus one NULL from the late row. Customer 12 never ordered.

  2. NOT IN: is 12 different from every value? 12 <> 1 is true, and so on down the list. 12 <> NULL is unknown. One unknown makes the whole answer unknown, and WHERE keeps only true. Customer 12 is dropped, and so is everyone else.

  3. left_anti: does 12 have a match? 12 matches none of the 28 ids, and NULL matches nothing. No match is found, so customer 12 is kept. So is customer 30: 2 rows.

Follow customer 12 through the same list twice: once asked about every value, once asked for any match.

Remember: NOT EXISTS is left_anti. NOT IN is not, once the list can hold a null: Spark plans a NOT IN subquery as a null-aware anti join, and left_anti is a plain one that ignores the null.

Three more rules that differ

Nulls in a list are not the only place where Postgres (Module 2) and Spark disagree. A translation can be clause-perfect and still return different rows:

  • Null order. Postgres sorts nulls last in ascending order; Spark sorts them first. A top-N or a "first value" moves when nulls exist: write F.asc_nulls_last(...) to match.
  • Division. In Postgres 7 / 2 on integers is 3. Spark's / always divides as floating point: 3.5. Use F.floor or SQL's div for whole numbers.
  • != drops nulls. filter(F.col('status') != 'x') skips null statuses; ~F.col('status').eqNullSafe('x') keeps them, like IS DISTINCT FROM.

The next cards ask each engine.

The same question in two engines

QuestionPostgresSpark
ORDER BY x with values 2, null, 11, 2, nullnull, 1, 2
SELECT 7 / 233.5
WHERE id NOT IN (subquery holding a NULL)no rowsno rows (null-aware anti join)
the same written as leftantinot availablerows with no match: the null is ignored
CAST('N/A' AS INT)error: invalid input syntax for type integerSpark 4.0: CASTINVALIDINPUT; 3.5: null

Run both versions on data that contains nulls before you trust a translation; the clean sample data of an interview rarely does.

Ask Postgres

SELECT 7 / 2 AS int_division,
       (SELECT string_agg(COALESCE(x::text, 'null'), ', ' ORDER BY x)
        FROM (VALUES (2), (NULL), (1)) AS t(x)) AS ascending_order,
       (SELECT COUNT(*)
        FROM customers
        WHERE customer_id NOT IN (SELECT customer_id FROM orders UNION ALL SELECT NULL)) AS not_in_rows;

Read the three columns: integer division gives 3, nulls sort last, and one null in the subquery makes NOT IN return no customers at all.

Ask Spark

from pyspark.sql import SparkSession, functions as F

spark = SparkSession.builder.getOrCreate()
t = spark.createDataFrame([(2,), (None,), (1,)], "x INT")
print("7 / 2 =", t.select((F.lit(7) / F.lit(2)).alias("q")).first()["q"])
print("orderBy x:", [r["x"] for r in t.orderBy("x").collect()])

customers = spark.read.csv("data/customers.csv", header=True, inferSchema=True)
orders = spark.read.csv("data/orders.csv", header=True, inferSchema=True)
ids = [r["customer_id"] for r in orders.select("customer_id").distinct().collect()] + [None]
with_null = spark.createDataFrame([(i,) for i in ids], "customer_id INT")
print("left_anti:", customers.join(with_null, "customer_id", "left_anti").count())
print("NOT IN   :", customers.filter(~F.col("customer_id").isin(ids)).count())

Spark says 3.5 and puts nulls first. The two ways of saying "never ordered" disagree once a null is in the list: left_anti finds the 2 customers, NOT IN finds none.

Numbers to remember

NameWhat it isWhy it matters
Session timeoutmore than 30 minutesThat is a gap of more than 1,800 seconds from F.unixtimestamp.
PushPredicateThroughJoinan optimiser ruleMoves a WHERE below the joins.
TakeOrderedAndProjecta physical stepSort plus Limit: each task keeps its own top N.
Null-aware anti joinhow Spark plans NOT IN (subquery)Returns no rows when the subquery holds a null.
ValueError: Cannot convert column into boolreal PySparkand, or or not was used between columns.

What changed at SwiftKart

The Postgres report had said 0 because of one null. You and Tess decided what it should mean, customers with no order, and kept the left_anti join with a note on the change. It says 2 now, on purpose.

Each translated report became a function, such as top_customers(orders, items, customers, n), with a unit test on a three-row DataFrame that includes a null. That is how SQL a stakeholder wrote in a notebook becomes a tested step of a pipeline (Module 7 and Module 10).

You can now write the pipeline in PySpark. Module 12, "How Spark runs", opens the engine underneath it, starting with Lesson 12.1: "Driver, executors and partitions".

In one line

Translate SQL in the order it runs, one method per clause, combine conditions with & and | inside brackets, and compare both versions on data that has nulls.

Interview corner

How would you write a HAVING clause in PySpark?

There is no separate method: it is a filter placed after groupBy().agg(), on the aliased aggregate column, for example .agg(F.count("*").alias("n")).filter(F.col("n") >= 3). A filter before the groupBy is the WHERE clause. The position in the chain is what decides.

Sessionize clickstream events in PySpark with a 30-minute timeout.

Window per user ordered by timestamp; F.lag("ts") gives the previous event; flag a new session when the previous is null or the gap from F.unix_timestamp differences is over 1800 seconds; a running F.sum of the flags over rowsBetween(unboundedPreceding, currentRow) gives the session number. Then group by user and session for session-level metrics.

Why does `filter(cond1 and cond2)` fail on columns?

Python's and needs a single true or false, but a Column is an expression evaluated later on every row, so PySpark raises "Cannot convert column into bool". Use &, | and ~, and wrap each comparison in brackets because those operators bind more tightly than == in Python.

Your PySpark translation of a Postgres report returns more rows than the original. What do you check?

First the null rules, because syntax rarely causes it. A NOT IN (subquery) translated as left_anti returns rows when the subquery holds a null, where the original returned none; Spark itself plans NOT IN as a null-aware anti join, so keep the SQL meaning or filter the nulls on purpose. Then sort order (Postgres puts nulls last ascending, Spark first, which changes top-N and first-value results), integer division (/ is floating point in Spark), and joins that fan out. I compare both versions on data that includes nulls and duplicates, row by row, before trusting either.