Menu
CoddyTech

Query with Spark SQL

Part of the Fundamentals section of Coddy's PySpark journey. Lesson 13 of 18.

Spark can query a DataFrame with SQL. Register a temporary view using df.createOrReplaceTempView("visits"), then call spark.sql. The returned value is another DataFrame. A temporary view belongs to the current Spark session; it is not a saved file.

df.createOrReplaceTempView("visits")
result = spark.sql("SELECT city, amount FROM visits WHERE amount > 5")

SELECT chooses columns, WHERE filters rows, and ORDER BY requests order. SQL uses GROUP BY and aggregate functions such as SUM for summaries. Use AS to name a result column.

spark.sql("SELECT city, SUM(amount) AS total FROM visits GROUP BY city")

This produces one total for each city in the registered visits view.

challenge icon

Challenge

Easy

Register df as temporary view sales. Use Spark SQL to return only item, amount for rows with amount at least 10. Inputs have no nulls.

Write transform(df) and return a Spark DataFrame. The checker supplies df with schema item string, amount int. The session and F (PySpark functions) are already available. Do not print; the checker displays the returned rows. Return columns in this order: item, amount.

Try it yourself

def transform(df):
    return df
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Online Python compiler