SQL queries on DataFrames in Apache Spark - Time & Space Complexity
When we run SQL queries on DataFrames, we want to know how the time to get results changes as the data grows.
We ask: How does the work increase when the number of rows gets bigger?
Analyze the time complexity of the following code snippet.
df.createOrReplaceTempView("people")
spark.sql("SELECT age, COUNT(*) FROM people GROUP BY age").show()
This code runs a SQL query on a DataFrame to count how many people are in each age group.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning all rows in the DataFrame to group by age.
- How many times: Each row is processed once during grouping and counting.
As the number of rows grows, the query needs to look at each row to group and count.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 row checks and group updates |
| 100 | About 100 row checks and group updates |
| 1000 | About 1000 row checks and group updates |
Pattern observation: The work grows roughly in direct proportion to the number of rows.
Time Complexity: O(n)
This means the time to run the query grows linearly as the number of rows increases.
[X] Wrong: "Grouping by a column makes the query run in constant time no matter the data size."
[OK] Correct: The query still needs to look at every row to group and count, so time grows with data size.
Understanding how SQL queries scale on DataFrames helps you explain performance in real projects and shows you know how data size affects work done.
"What if we added a filter before grouping? How would the time complexity change?"
Practice
createOrReplaceTempView method do in Apache Spark?Solution
Step 1: Understand the purpose of
This method registers a DataFrame as a temporary table in Spark's SQL context.createOrReplaceTempViewStep 2: Recognize its use in SQL queries
Once registered, you can run SQL queries on the DataFrame usingspark.sql().Final Answer:
It registers a DataFrame as a temporary SQL table for querying. -> Option AQuick Check:
Temporary view = SQL table for queries [OK]
- Thinking it saves data permanently
- Confusing it with running SQL queries
- Assuming it deletes tables
people?Solution
Step 1: Identify the correct method to run SQL queries
The method to run SQL queries on Spark isspark.sql().Step 2: Check the syntax for querying the temp view
The query string should be passed insidespark.sql()as shown in spark.sql("SELECT * FROM people").Final Answer:
spark.sql("SELECT * FROM people") -> Option CQuick Check:
Use spark.sql() to run SQL queries [OK]
- Using incorrect method names like spark.query
- Forgetting to use quotes around SQL query
- Confusing method names with other APIs
data = [(1, "Alice", 29), (2, "Bob", 31), (3, "Cathy", 25)]
columns = ["id", "name", "age"]
df = spark.createDataFrame(data, columns)
df.createOrReplaceTempView("people")
result = spark.sql("SELECT name FROM people WHERE age > 28 ORDER BY age DESC")
result.show()Solution
Step 1: Analyze the data and filter condition
Rows with age > 28 are Alice (29) and Bob (31).Step 2: Apply ORDER BY age DESC
Ordering by age descending gives Bob (31) first, then Alice (29).Final Answer:
[["Bob"], ["Alice"]] -> Option DQuick Check:
Filter age > 28 and order desc = Bob, Alice [OK]
- Mixing ascending and descending order
- Including rows with age <= 28
- Confusing column names in SELECT
df.createOrReplaceTempView("employees")
result = spark.sql("SELECT * FROM employee WHERE salary > 50000")
result.show()Solution
Step 1: Check temp view name and SQL query table name
The temp view is named "employees" but the query uses "employee" (missing 's').Step 2: Understand impact of name mismatch
This causes a runtime error because the table "employee" does not exist.Final Answer:
The temp view name is 'employees' but query uses 'employee'. -> Option BQuick Check:
Temp view and query table names must match exactly [OK]
- Assuming SQL syntax error instead of name mismatch
- Thinking show() can't be used on results
- Ignoring case sensitivity in table names
sales with columns product, region, and amount. You want to find the total sales amount per region but only for regions where total sales exceed 1000. Which SQL query on the temp view sales will achieve this?Solution
Step 1: Understand filtering on aggregated data
Filtering on aggregated results requires the HAVING clause, not WHERE.Step 2: Check correct use of HAVING with alias
Using HAVING total_sales > 1000 after GROUP BY is correct as in SELECT region, SUM(amount) AS total_sales FROM sales GROUP BY region HAVING total_sales > 1000.Final Answer:
SELECT region, SUM(amount) AS total_sales FROM sales GROUP BY region HAVING total_sales > 1000 -> Option AQuick Check:
Use HAVING to filter grouped aggregates [OK]
- Using WHERE instead of HAVING for aggregates
- Placing WHERE after GROUP BY
- Not aliasing SUM(amount) before HAVING
Ready to prove it?
Pass the test and this pattern moves unknown
