SQL vs PySpark: the same queries, side by side
If you already write SQL, you already know most of PySpark. The DataFrame API expresses the same relational operations (filter, group, join, window) as method calls instead of clauses, and Spark compiles both into the same execution plan. This guide shows each common query written both ways on one small dataset, with the real output, and the mistakes that trip people up when they move from SQL to PySpark.
How PySpark is different from SQL
SQL and PySpark describe the same operations. What changes is how you write them and when they run.
| SQL | PySpark DataFrame API | |
|---|---|---|
| What you write | A declarative statement | A chain of method calls on a DataFrame |
| Order of writing | SELECT … FROM … WHERE … GROUP BY … (fixed) | In the order you think: df.filter(…).groupBy(…).agg(…) |
| Reusing a step | CTE or view | Assign it to a Python variable |
| When it runs | When the statement runs | Lazily: only when an *action* (show, count, collect, write) is called |
| Logic | SQL expressions | Python, so loops, functions and tests are available around the query |
| Execution | Database engine | Spark's Catalyst optimizer; Spark SQL and the DataFrame API produce the same plan |
So "Spark SQL vs PySpark" is mostly a question of style, not speed: spark.sql("SELECT …") and the equivalent DataFrame code compile to the same physical plan (we checked this with explain(); see Performance). Use SQL when the logic reads best as a query, and the DataFrame API when you want to compose, parameterise or unit-test steps in Python. You can mix both in one job.
The dataset
Two small tables used by every example. They include a NULL city, a NULL amount, an order from a customer who does not exist (108), and an exact duplicate row (107), because those are what break real queries.
customers
| customer_id | name | city | signup_date |
|---|---|---|---|
| 1 | Asha | Pune | 2024-01-05 |
| 2 | Ravi | Delhi | 2024-01-20 |
| 3 | Meera | NULL | 2024-02-02 |
| 4 | Kabir | Pune | 2024-03-15 |
| 5 | Zoya | Mumbai | 2024-03-28 |
orders
| order_id | customer_id | order_date | amount | status |
|---|---|---|---|---|
| 101 | 1 | 2024-02-01 | 250.00 | delivered |
| 102 | 1 | 2024-02-15 | 400.00 | delivered |
| 103 | 2 | 2024-02-03 | 150.00 | cancelled |
| 104 | 2 | 2024-03-09 | 400.00 | delivered |
| 105 | 3 | 2024-03-10 | NULL | pending |
| 106 | 4 | 2024-03-22 | 90.00 | delivered |
| 107 | 1 | 2024-03-30 | 120.00 | delivered |
| 108 | 9 | 2024-03-31 | 75.00 | delivered |
| 107 | 1 | 2024-03-30 | 120.00 | delivered |
To follow along in SQL, create the tables in any database (this runs on MySQL 8, PostgreSQL and DuckDB):
SQL
CREATE TABLE customers (customer_id INT, name VARCHAR(50), city VARCHAR(50), signup_date DATE);
INSERT INTO customers VALUES
(1, 'Asha', 'Pune', '2024-01-05'), (2, 'Ravi', 'Delhi', '2024-01-20'), (3, 'Meera', NULL, '2024-02-02'),
(4, 'Kabir', 'Pune', '2024-03-15'), (5, 'Zoya', 'Mumbai', '2024-03-28');
CREATE TABLE orders (order_id INT, customer_id INT, order_date DATE, amount DECIMAL(10,2), status VARCHAR(20));
INSERT INTO orders VALUES
(101, 1, '2024-02-01', 250.00, 'delivered'), (102, 1, '2024-02-15', 400.00, 'delivered'),
(103, 2, '2024-02-03', 150.00, 'cancelled'), (104, 2, '2024-03-09', 400.00, 'delivered'),
(105, 3, '2024-03-10', NULL, 'pending'), (106, 4, '2024-03-22', 90.00, 'delivered'),
(107, 1, '2024-03-30', 120.00, 'delivered'), (108, 9, '2024-03-31', 75.00, 'delivered'),
(107, 1, '2024-03-30', 120.00, 'delivered');The same data in PySpark. The two temp views let you run any SQL example through spark.sql(...) as well:
PySpark
import datetime as dt
from decimal import Decimal
from pyspark.sql import SparkSession, Window
from pyspark.sql import functions as F
spark = SparkSession.builder.getOrCreate()
CUSTOMERS = [(1, "Asha", "Pune", dt.date(2024, 1, 5)), (2, "Ravi", "Delhi", dt.date(2024, 1, 20)),
(3, "Meera", None, dt.date(2024, 2, 2)), (4, "Kabir", "Pune", dt.date(2024, 3, 15)),
(5, "Zoya", "Mumbai", dt.date(2024, 3, 28))]
ORDERS = [(101, 1, dt.date(2024, 2, 1), Decimal("250.00"), "delivered"),
(102, 1, dt.date(2024, 2, 15), Decimal("400.00"), "delivered"),
(103, 2, dt.date(2024, 2, 3), Decimal("150.00"), "cancelled"),
(104, 2, dt.date(2024, 3, 9), Decimal("400.00"), "delivered"),
(105, 3, dt.date(2024, 3, 10), None, "pending"),
(106, 4, dt.date(2024, 3, 22), Decimal("90.00"), "delivered"),
(107, 1, dt.date(2024, 3, 30), Decimal("120.00"), "delivered"),
(108, 9, dt.date(2024, 3, 31), Decimal("75.00"), "delivered"),
(107, 1, dt.date(2024, 3, 30), Decimal("120.00"), "delivered")]
customers = spark.createDataFrame(CUSTOMERS, "customer_id INT, name STRING, city STRING, signup_date DATE")
orders = spark.createDataFrame(ORDERS, "order_id INT, customer_id INT, order_date DATE, amount DECIMAL(10,2), status STRING")
customers.createOrReplaceTempView("customers")
orders.createOrReplaceTempView("orders")SELECT and WHERE
Choosing columns and filtering rows is the same idea in both: SELECT becomes select() and WHERE becomes filter().
SQL
SELECT order_id, customer_id, amount
FROM orders
WHERE status = 'delivered' AND amount > 100
ORDER BY order_id;PySpark
(orders
.filter((F.col("status") == "delivered") & (F.col("amount") > 100))
.select("order_id", "customer_id", "amount")
.orderBy("order_id"))| order_id | customer_id | amount |
|---|---|---|
| 101 | 1 | 250.00 |
| 102 | 1 | 400.00 |
| 104 | 2 | 400.00 |
| 107 | 1 | 120.00 |
| 107 | 1 | 120.00 |
Mistakes when switching: use &, | and ~ instead of and, or, not, and wrap each condition in brackets: (a > 1) & (b < 2). Python's and raises an error on columns. filter and where are the same method. Order 107 appears twice because the source row is duplicated; see Duplicates.
CASE WHEN vs when().otherwise()
Conditional logic in PySpark is a chain of F.when() calls ending in .otherwise(), the DataFrame spelling of CASE WHEN … ELSE … END.
SQL
SELECT order_id, amount,
CASE WHEN amount >= 300 THEN 'large'
WHEN amount >= 100 THEN 'medium'
ELSE 'small' END AS size
FROM orders
WHERE amount IS NOT NULL
ORDER BY order_id;PySpark
(orders.filter(F.col("amount").isNotNull())
.select("order_id", "amount",
F.when(F.col("amount") >= 300, "large")
.when(F.col("amount") >= 100, "medium")
.otherwise("small").alias("size"))
.orderBy("order_id"))| order_id | amount | size |
|---|---|---|
| 101 | 250.00 | medium |
| 102 | 400.00 | large |
| 103 | 150.00 | medium |
| 104 | 400.00 | large |
| 106 | 90.00 | small |
| 107 | 120.00 | medium |
| 107 | 120.00 | medium |
| 108 | 75.00 | small |
Conditions are checked top to bottom, exactly like CASE. Without .otherwise(), unmatched rows get NULL, just as a CASE without ELSE does. Conditional aggregation (SUM(CASE WHEN …)) is how SQL pivots; PySpark also has groupBy().pivot().
GROUP BY and HAVING
Grouping is groupBy() followed by agg(), with one aggregate function per output column.
SQL
SELECT customer_id, COUNT(*) AS orders, SUM(amount) AS revenue
FROM orders
WHERE status = 'delivered'
GROUP BY customer_id
HAVING SUM(amount) > 300
ORDER BY revenue DESC;PySpark
(orders.filter(F.col("status") == "delivered")
.groupBy("customer_id")
.agg(F.count("*").alias("orders"), F.sum("amount").alias("revenue"))
.filter(F.col("revenue") > 300) # HAVING is just a filter after agg()
.orderBy(F.desc("revenue")))| customer_id | orders | revenue |
|---|---|---|
| 1 | 4 | 890.00 |
| 2 | 1 | 400.00 |
There is no separate having(): a filter placed after agg() is the HAVING, and a filter before groupBy() is the WHERE. Note customer 1 shows 4 orders and 890: the duplicated order 107 is counted twice. Deduplicate before aggregating (the CTE example does, and gets 770).
Joins
INNER JOIN. With the same column name on both sides, pass the name and PySpark keeps a single customer_id column:
SQL
SELECT o.order_id, c.name, o.amount
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
WHERE o.order_id < 105
ORDER BY o.order_id;PySpark
(orders.join(customers, "customer_id")
.filter(F.col("order_id") < 105)
.select("order_id", "name", "amount").orderBy("order_id"))| order_id | name | amount |
|---|---|---|
| 101 | Asha | 250.00 |
| 102 | Asha | 400.00 |
| 103 | Ravi | 150.00 |
| 104 | Ravi | 400.00 |
LEFT JOIN with zero counts:
SQL
SELECT c.customer_id, c.name, COUNT(o.order_id) AS orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name
ORDER BY c.customer_id;PySpark
(customers.join(orders, "customer_id", "left")
.groupBy("customer_id", "name")
.agg(F.count("order_id").alias("orders"))
.orderBy("customer_id"))| customer_id | name | orders |
|---|---|---|
| 1 | Asha | 4 |
| 2 | Ravi | 2 |
| 3 | Meera | 1 |
| 4 | Kabir | 1 |
| 5 | Zoya | 0 |
COUNT(o.order_id) / F.count("order_id") skips NULLs, so Zoya gets 0. COUNT(*) would give her 1.
Anti join (rows with no match). SQL uses NOT EXISTS or LEFT JOIN … IS NULL; PySpark has a join type for it:
SQL
SELECT c.customer_id, c.name
FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id);PySpark
customers.join(orders, "customer_id", "left_anti").select("customer_id", "name")| customer_id | name |
|---|---|
| 5 | Zoya |
The same pattern the other way round finds orphan orders: orders.join(customers, "customer_id", "left_anti") returns order 108 (customer 9 does not exist). left_semi is the opposite: rows that *do* have a match, without adding the right table's columns.
Mistake: NOT IN (SELECT customer_id FROM orders) returns nothing at all if that column contains a NULL. NOT EXISTS and left_anti do not have this problem.
Ranking: ROW_NUMBER, RANK, DENSE_RANK
Window functions work the same way in both: define the partition and the order once, then apply a ranking function over it.
SQL
SELECT order_id, amount,
ROW_NUMBER() OVER (ORDER BY amount DESC, order_id) AS row_number,
RANK() OVER (ORDER BY amount DESC) AS rank,
DENSE_RANK() OVER (ORDER BY amount DESC) AS dense_rank
FROM (SELECT DISTINCT * FROM orders) d
WHERE amount IS NOT NULL
ORDER BY row_number;PySpark
d = orders.distinct().filter(F.col("amount").isNotNull())
by_amount = Window.orderBy(F.desc("amount"))
d.select("order_id", "amount",
F.row_number().over(Window.orderBy(F.desc("amount"), "order_id")).alias("row_number"),
F.rank().over(by_amount).alias("rank"),
F.dense_rank().over(by_amount).alias("dense_rank"))| order_id | amount | row_number | rank | dense_rank |
|---|---|---|---|---|
| 102 | 400.00 | 1 | 1 | 1 |
| 104 | 400.00 | 2 | 1 | 1 |
| 101 | 250.00 | 3 | 3 | 2 |
| 103 | 150.00 | 4 | 4 | 3 |
| 107 | 120.00 | 5 | 5 | 4 |
| 106 | 90.00 | 6 | 6 | 5 |
| 108 | 75.00 | 7 | 7 | 6 |
The two 400s tie. ROW_NUMBER still numbers them 1 and 2 (so give it a tie-breaker, or the order is arbitrary), RANK gives both 1 and skips to 3, DENSE_RANK gives both 1 and continues at 2.
Top N per group is a ranking inside a partition, then a filter. Latest order per customer:
SQL
SELECT customer_id, order_id, order_date
FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY customer_id
ORDER BY order_date DESC, order_id DESC) AS rn
FROM orders) x
WHERE rn = 1;PySpark
w = Window.partitionBy("customer_id").orderBy(F.desc("order_date"), F.desc("order_id"))
orders.withColumn("rn", F.row_number().over(w)).filter("rn = 1").select("customer_id", "order_id", "order_date")| customer_id | order_id | order_date |
|---|---|---|
| 1 | 107 | 2024-03-30 |
| 2 | 104 | 2024-03-09 |
| 3 | 105 | 2024-03-10 |
| 4 | 106 | 2024-03-22 |
| 9 | 108 | 2024-03-31 |
Running totals and LAG
Cumulative sums and previous-row lookups are window functions with an explicit order and, for running totals, an explicit frame.
Running total (delivered revenue by day, after removing the duplicate row):
SQL
SELECT order_date, SUM(amount) AS day_revenue,
SUM(SUM(amount)) OVER (ORDER BY order_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_revenue
FROM (SELECT DISTINCT * FROM orders WHERE status = 'delivered') d
GROUP BY order_date
ORDER BY order_date;PySpark
daily = (orders.filter(F.col("status") == "delivered").distinct()
.groupBy("order_date").agg(F.sum("amount").alias("day_revenue")))
running = Window.orderBy("order_date").rowsBetween(Window.unboundedPreceding, Window.currentRow)
daily.withColumn("running_revenue", F.sum("day_revenue").over(running)).orderBy("order_date")| order_date | day_revenue | running_revenue |
|---|---|---|
| 2024-02-01 | 250.00 | 250.00 |
| 2024-02-15 | 400.00 | 650.00 |
| 2024-03-09 | 400.00 | 1050.00 |
| 2024-03-22 | 90.00 | 1140.00 |
| 2024-03-30 | 120.00 | 1260.00 |
| 2024-03-31 | 75.00 | 1335.00 |
Previous value with LAG:
SQL
SELECT customer_id, order_id, amount,
LAG(amount) OVER (PARTITION BY customer_id ORDER BY order_date, order_id) AS prev_amount
FROM (SELECT DISTINCT * FROM orders) d
WHERE customer_id IN (1, 2);PySpark
w = Window.partitionBy("customer_id").orderBy("order_date", "order_id")
(orders.distinct().filter(F.col("customer_id").isin(1, 2))
.withColumn("prev_amount", F.lag("amount").over(w))
.select("customer_id", "order_id", "amount", "prev_amount"))| customer_id | order_id | amount | prev_amount |
|---|---|---|---|
| 1 | 101 | 250.00 | NULL |
| 1 | 102 | 400.00 | 250.00 |
| 1 | 107 | 120.00 | 400.00 |
| 2 | 103 | 150.00 | NULL |
| 2 | 104 | 400.00 | 150.00 |
Mistakes: with only ORDER BY and no frame, the default window frame is RANGE … CURRENT ROW, so rows with the same date are summed together. Write the ROWS frame when you mean row by row. A ROWS BETWEEN 6 PRECEDING frame counts rows, not days; if dates can be missing, use a range over dates or fill the gaps first.
CTEs
A CTE names an intermediate result. In PySpark you get the same thing by assigning a DataFrame to a variable:
SQL
WITH revenue AS (
SELECT customer_id, SUM(amount) AS revenue
FROM (SELECT DISTINCT * FROM orders) d
WHERE status = 'delivered'
GROUP BY customer_id
)
SELECT customer_id, revenue
FROM revenue
WHERE revenue > (SELECT AVG(revenue) FROM revenue);PySpark
revenue = (orders.distinct().filter(F.col("status") == "delivered")
.groupBy("customer_id").agg(F.sum("amount").alias("revenue")))
avg_revenue = revenue.agg(F.avg("revenue")).first()[0] # an action: runs a small job
revenue.filter(F.col("revenue") > avg_revenue)| customer_id | revenue |
|---|---|
| 1 | 770.00 |
| 2 | 400.00 |
Neither a CTE nor a DataFrame variable stores data. Both are recomputed where they are used. If an expensive intermediate result is reused several times in PySpark, cache() it deliberately. first() is an action, so the average is computed immediately and passed in as a plain number.
NULL handling
COUNT and SUM skip NULLs:
SQL
SELECT COUNT(*) AS all_rows, COUNT(amount) AS with_amount, SUM(amount) AS total FROM orders;PySpark
orders.agg(F.count("*").alias("all_rows"), F.count("amount").alias("with_amount"), F.sum("amount").alias("total"))| all_rows | with_amount | total |
|---|---|---|
| 9 | 8 | 1605.00 |
Replacing NULLs for display: COALESCE(city, 'unknown') in SQL is F.coalesce("city", F.lit("unknown")) in PySpark, and df.fillna({"city": "unknown"}) does the same for whole columns.
NULL never equals NULL. city = city is NULL, not true, when city is NULL. That's why joins and filters on nullable keys silently drop rows. Use the null-safe comparison when NULL should match NULL:
SQL
SELECT customer_id, city,
city = city AS plain_equals,
city IS NOT DISTINCT FROM city AS null_safe_equals -- Spark SQL also accepts: city <=> city
FROM customers;PySpark
customers.select("customer_id", "city",
(F.col("city") == F.col("city")).alias("plain_equals"),
F.col("city").eqNullSafe(F.col("city")).alias("null_safe_equals"))| customer_id | city | plain_equals | null_safe_equals |
|---|---|---|---|
| 1 | Pune | True | True |
| 2 | Delhi | True | True |
| 3 | NULL | NULL | True |
| 4 | Pune | True | True |
| 5 | Mumbai | True | True |
Duplicates
Exact duplicate rows: SELECT DISTINCT * is df.distinct() (or dropDuplicates() with no arguments). Our 9 order rows become 8.
One row per key, deterministically: dropDuplicates(["order_id"]) keeps *an* arbitrary row per key. When it matters which one survives (latest, smallest id), rank inside the key and keep row 1:
SQL
SELECT order_id, customer_id, amount
FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY order_date DESC) AS rn
FROM orders) x
WHERE rn = 1;PySpark
w = Window.partitionBy("order_id").orderBy(F.desc("order_date"))
orders.withColumn("rn", F.row_number().over(w)).filter("rn = 1").select("order_id", "customer_id", "amount")Mistake: deduplicating on too few columns merges records that are genuinely different. Decide which columns define "the same" record first.
Median
Most engines now have a median aggregate; MySQL is the exception, so it gets its own version below.
SQL
-- DuckDB / PostgreSQL / Spark SQL 3.4+: a median aggregate exists
SELECT status, MEDIAN(amount) AS median_amount
FROM (SELECT DISTINCT * FROM orders) d
WHERE amount IS NOT NULL
GROUP BY status;PySpark
(orders.distinct().filter(F.col("amount").isNotNull())
.groupBy("status").agg(F.median("amount").alias("median_amount"))) # Spark 3.4+| status | median_amount |
|---|---|
| cancelled | 150.00 |
| delivered | 185.00 |
The delivered amounts are 75, 90, 120, 250, 400, 400, so the median is the average of the middle two: (120 + 250) / 2 = 185.
- PySpark options:
F.median(3.4+) andF.percentile(col, 0.5)(3.5+) are exact.F.percentile_approxis approximate and much cheaper on large data, so it's the usual choice when an estimate is fine. - MySQL 8 has no median function. Number the rows and average the middle one or two:
MySQL 8
SELECT AVG(amount) AS median_amount
FROM (SELECT amount,
ROW_NUMBER() OVER (ORDER BY amount) AS rn,
COUNT(*) OVER () AS n
FROM orders
WHERE amount IS NOT NULL AND status = 'delivered') x
WHERE rn IN ((n + 1) DIV 2, (n + 2) DIV 2); -- DuckDB: use // instead of DIVThis returns 185.00 on the deduplicated data, matching MEDIAN.
Dates
Date functions are where SQL dialects differ most, so here is the same operation in each.
| Task | SQL (DuckDB / PostgreSQL) | MySQL 8 | PySpark |
|---|---|---|---|
| First day of month | date_trunc('month', d) | DATE_FORMAT(d, '%Y-%m-01') | F.trunc("d", "month") (Spark SQL: trunc(d, 'MM')) |
| Year | EXTRACT(YEAR FROM d) | YEAR(d) | F.year("d") |
| Days between | date_diff('day', a, b) | DATEDIFF(b, a) | F.datediff("b", "a") (end date first) |
| Add a month | d + INTERVAL 1 MONTH | DATE_ADD(d, INTERVAL 1 MONTH) | F.add_months("d", 1) |
| Format | strftime(d, '%Y-%m') | DATE_FORMAT(d, '%Y-%m') | F.date_format("d", "yyyy-MM") |
Example on our data:
PySpark
(orders.join(customers, "customer_id").filter(F.col("order_id").isin(101, 104, 106))
.select("order_id",
F.trunc("order_date", "month").alias("order_month"),
F.datediff("order_date", "signup_date").alias("days_since_signup"),
F.add_months("order_date", 1).alias("follow_up_date")))| order_id | order_month | days_since_signup | follow_up_date |
|---|---|---|---|
| 101 | 2024-02-01 | 27 | 2024-03-01 |
| 104 | 2024-03-01 | 49 | 2024-04-09 |
| 106 | 2024-03-01 | 7 | 2024-04-22 |
Mistakes:
- Argument order:
datediffputs the end date first in Spark and MySQL; DuckDB'sdate_difftakes a unit and then start, end. - Format patterns: Spark uses Java patterns (
yyyy-MM), not%Y-%m. - Month vs calendar month: grouping by
MONTH(d)alone merges January of different years. Truncate to the month instead.
Performance: what actually matters
Each point below was checked on Spark 3.5.1 by reading the query plan with explain(), rather than assumed. Run explain() on your own queries to see the same things.
- SQL vs DataFrame API: same plan.
spark.sql("SELECT … GROUP BY …")and the equivalentfilter().groupBy().agg()produced identical physical plans. Choose by readability. - A window without
partitionByuses one partition. The plan showsExchange SinglePartition: every row goes to a single task. That's fine for a small table and a bottleneck for a large one. Partition the window whenever the logic allows it (per customer, per day). - Small tables are broadcast. Spark joins a small table by sending it to every executor instead of shuffling both sides. It decides from table statistics (
spark.sql.autoBroadcastJoinThreshold, default 10 MB). When there are no statistics, Adaptive Query Execution switches the join at runtime: we sawSortMergeJoinbecomeBroadcastHashJoin.F.broadcast(small_df)or the/*+ BROADCAST(t) */hint requests it explicitly. - Built-in functions beat Python UDFs. A Python UDF adds a
BatchEvalPythonstep that ships rows to Python and back; the built-inF.upperstays inside the JVM. Look for a built-in function (or a pandas UDF) before writing a row-by-row Python UDF. - Filter and select early when reading files. With Parquet or Delta, Spark pushes filters and column selection down to the scan, so less data is read.
SELECT *followed by a late filter loses some of that benefit. - Know your actions. Transformations are lazy;
count(),show(),collect()andfirst()run a job.collect()brings every row to the driver, so use it only on small results. - Exact vs approximate.
countDistinctand exact percentiles need more memory and shuffle thanapprox_count_distinctandpercentile_approx. On large data, use the approximate versions when an estimate is acceptable.
Cheat sheet
The most common translations at a glance.
| SQL | PySpark |
|---|---|
SELECT a, b | df.select("a", "b") |
SELECT a AS x | df.select(F.col("a").alias("x")) |
WHERE a > 1 AND b = 'x' | df.filter((F.col("a") > 1) & (F.col("b") == "x")) |
CASE WHEN … THEN … ELSE … END | F.when(…, …).otherwise(…) |
GROUP BY a + COUNT(*), SUM(b) | df.groupBy("a").agg(F.count("*"), F.sum("b")) |
HAVING SUM(b) > 10 | .filter(F.col("sum_b") > 10) after agg |
JOIN … USING (k) / LEFT JOIN | df.join(other, "k") / df.join(other, "k", "left") |
NOT EXISTS / EXISTS | join(..., "left_anti") / join(..., "left_semi") |
ROW_NUMBER() OVER (PARTITION BY a ORDER BY b) | F.row_number().over(Window.partitionBy("a").orderBy("b")) |
SUM(x) OVER (ORDER BY d ROWS UNBOUNDED PRECEDING) | F.sum("x").over(Window.orderBy("d").rowsBetween(Window.unboundedPreceding, 0)) |
LAG(x) / LEAD(x) | F.lag("x") / F.lead("x") |
WITH t AS (…) | t = df… (a variable) |
COALESCE(a, 0) | F.coalesce("a", F.lit(0)) or df.fillna({"a": 0}) |
a IS NOT DISTINCT FROM b / a <=> b | F.col("a").eqNullSafe(F.col("b")) |
SELECT DISTINCT * | df.distinct() |
MEDIAN(x) | F.median("x") / F.percentile_approx("x", 0.5) |
ORDER BY a DESC LIMIT 10 | df.orderBy(F.desc("a")).limit(10) |
Practise the same problems
Every problem linked on this page runs in the browser in SQL or PySpark, and your answer is checked against test data. Checking an answer needs no account; the online PySpark compiler needs a Google sign-in to run code.
Frequently asked questions
Is PySpark faster than Spark SQL?
No. Both compile to the same plan, so equivalent code runs the same way. Differences come from what the code does (UDFs, missing filters, unpartitioned windows), not from the API.
Can I just run my SQL in PySpark?
Yes. Register DataFrames as views with createOrReplaceTempView and call spark.sql(...). Most standard SQL works. Dialect-specific functions (MySQL DATE_FORMAT patterns, DIV, some date arithmetic) need the Spark spelling.
Should I learn SQL or PySpark first?
SQL. Every concept on this page starts in SQL, and PySpark reuses it. Learn the DataFrame API once you need pipelines in Python, testing, or data too large for one database.
Open the free PySpark compiler · Data Engineering challenges · Data Engineering jobs