TECHNOLOGIESTieInn Technologies

Spark SQL and window functions

Spark / PySpark · 12 questions

Short notes

Key idea

You can query DataFrames with plain SQL by registering them as views. Window functions work just like in SQL, through SQL text or the Window API.

Syntax

df.createOrReplaceTempView("orders")
spark.sql("SELECT city, SUM(amount) AS revenue FROM orders GROUP BY city")

from pyspark.sql import Window, functions as F
w = Window.partitionBy("city").orderBy(F.desc("amount"))
df.withColumn("rn", F.row_number().over(w)).filter("rn <= 3")

w2 = Window.partitionBy("customer_id").orderBy("order_date")
df.withColumn("prev", F.lag("amount").over(w2))

Example

Running revenue per city:

w = (Window.partitionBy("city").orderBy("order_date")
          .rowsBetween(Window.unboundedPreceding, Window.currentRow))
df.withColumn("running", F.sum("amount").over(w))

Traps

  • SQL and the DataFrame API compile to the same plan; choose whichever reads better.
  • A window with no partitionBy moves all data to one partition: slow and risky on big data.
  • Temp views last only for the session.
  • Specify the frame (rowsBetween) for running totals with tied dates.

Want the full lesson with step-by-step examples, a project and a certificate? Spark / PySpark course, ₹120 →

Questions

Open in Code Lab5 free questions
5 questions

    Spark SQL and window functions

  1. Question 1easy

    What do you call before running spark.sql("SELECT ... FROM orders") on a DataFrame named orders?

  2. Spark SQL and window functions

  3. Question 2medium

    Is spark.sql(...) slower than the equivalent DataFrame code?

  4. Spark SQL and window functions

  5. Question 3medium

    What does this print?

    changes = spark.createDataFrame([
        (1, "pending", "2024-05-01"), (1, "shipped", "2024-05-02"),
        (2, "pending", "2024-05-01"), (1, "delivered", "2024-05-04"),
    ], ["order_id", "status", "updated_at"])
    w = Window.partitionBy("order_id").orderBy(F.col("updated_at").desc())
    latest = changes.withColumn("rn", F.row_number().over(w)).filter("rn = 1")
    print(latest.count())
  6. Spark SQL and window functions

  7. Question 4medium

    Why is Window.orderBy("order_date") with no partitionBy risky on a billion rows?

  8. Spark SQL and window functions

  9. Question 5medium

    Amounts sorted high to low are 900, 800, 800, 700. What does dense_rank give the 700?

7 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.