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.

SQLPySpark DataFrame API
What you writeA declarative statementA chain of method calls on a DataFrame
Order of writingSELECT … FROM … WHERE … GROUP BY … (fixed)In the order you think: df.filter(…).groupBy(…).agg(…)
Reusing a stepCTE or viewAssign it to a Python variable
When it runsWhen the statement runsLazily: only when an *action* (show, count, collect, write) is called
LogicSQL expressionsPython, so loops, functions and tests are available around the query
ExecutionDatabase engineSpark'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_idnamecitysignup_date
1AshaPune2024-01-05
2RaviDelhi2024-01-20
3MeeraNULL2024-02-02
4KabirPune2024-03-15
5ZoyaMumbai2024-03-28

orders

order_idcustomer_idorder_dateamountstatus
10112024-02-01250.00delivered
10212024-02-15400.00delivered
10322024-02-03150.00cancelled
10422024-03-09400.00delivered
10532024-03-10NULLpending
10642024-03-2290.00delivered
10712024-03-30120.00delivered
10892024-03-3175.00delivered
10712024-03-30120.00delivered

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_idcustomer_idamount
1011250.00
1021400.00
1042400.00
1071120.00
1071120.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_idamountsize
101250.00medium
102400.00large
103150.00medium
104400.00large
10690.00small
107120.00medium
107120.00medium
10875.00small

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_idordersrevenue
14890.00
21400.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_idnameamount
101Asha250.00
102Asha400.00
103Ravi150.00
104Ravi400.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_idnameorders
1Asha4
2Ravi2
3Meera1
4Kabir1
5Zoya0

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_idname
5Zoya

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_idamountrow_numberrankdense_rank
102400.00111
104400.00211
101250.00332
103150.00443
107120.00554
10690.00665
10875.00776

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_idorder_idorder_date
11072024-03-30
21042024-03-09
31052024-03-10
41062024-03-22
91082024-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_dateday_revenuerunning_revenue
2024-02-01250.00250.00
2024-02-15400.00650.00
2024-03-09400.001050.00
2024-03-2290.001140.00
2024-03-30120.001260.00
2024-03-3175.001335.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_idorder_idamountprev_amount
1101250.00NULL
1102400.00250.00
1107120.00400.00
2103150.00NULL
2104400.00150.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_idrevenue
1770.00
2400.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_rowswith_amounttotal
981605.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_idcityplain_equalsnull_safe_equals
1PuneTrueTrue
2DelhiTrueTrue
3NULLNULLTrue
4PuneTrueTrue
5MumbaiTrueTrue

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+
statusmedian_amount
cancelled150.00
delivered185.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+) and F.percentile(col, 0.5) (3.5+) are exact. F.percentile_approx is 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 DIV

This 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.

TaskSQL (DuckDB / PostgreSQL)MySQL 8PySpark
First day of monthdate_trunc('month', d)DATE_FORMAT(d, '%Y-%m-01')F.trunc("d", "month") (Spark SQL: trunc(d, 'MM'))
YearEXTRACT(YEAR FROM d)YEAR(d)F.year("d")
Days betweendate_diff('day', a, b)DATEDIFF(b, a)F.datediff("b", "a") (end date first)
Add a monthd + INTERVAL 1 MONTHDATE_ADD(d, INTERVAL 1 MONTH)F.add_months("d", 1)
Formatstrftime(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_idorder_monthdays_since_signupfollow_up_date
1012024-02-01272024-03-01
1042024-03-01492024-04-09
1062024-03-0172024-04-22

Mistakes:

  • Argument order: datediff puts the end date first in Spark and MySQL; DuckDB's date_diff takes 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.

  1. SQL vs DataFrame API: same plan. spark.sql("SELECT … GROUP BY …") and the equivalent filter().groupBy().agg() produced identical physical plans. Choose by readability.
  2. A window without partitionBy uses one partition. The plan shows Exchange 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).
  3. 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 saw SortMergeJoin become BroadcastHashJoin. F.broadcast(small_df) or the /*+ BROADCAST(t) */ hint requests it explicitly.
  4. Built-in functions beat Python UDFs. A Python UDF adds a BatchEvalPython step that ships rows to Python and back; the built-in F.upper stays inside the JVM. Look for a built-in function (or a pandas UDF) before writing a row-by-row Python UDF.
  5. 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.
  6. Know your actions. Transformations are lazy; count(), show(), collect() and first() run a job. collect() brings every row to the driver, so use it only on small results.
  7. Exact vs approximate. countDistinct and exact percentiles need more memory and shuffle than approx_count_distinct and percentile_approx. On large data, use the approximate versions when an estimate is acceptable.

Cheat sheet

The most common translations at a glance.

SQLPySpark
SELECT a, bdf.select("a", "b")
SELECT a AS xdf.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 … ENDF.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 JOINdf.join(other, "k") / df.join(other, "k", "left")
NOT EXISTS / EXISTSjoin(..., "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 <=> bF.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 10df.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

Further reading

Follow the free PySpark tutorial