Unit 4: Running SQL Queries Using Spark SQL - Practice Quiz

INT315 — Cluster Computing 60 Questions
0 Correct 0 Wrong 60 Left
0/60

1 What is the primary purpose of Spark SQL?

Importance and features of Spark SQL Easy
A. Managing computer network connections
B. Compiling Java source code
C. Designing graphical user interfaces
D. Processing structured and semi-structured data

2 Which Spark SQL component optimizes query execution plans?

Importance and features of Spark SQL Easy
A. Catalyst Optimizer
B. Block Manager
C. Task Scheduler
D. Cluster Manager

3 Which object is the main entry point for working with Spark SQL?

Concepts of Spark SQL Easy
A. SparkContext
B. SparkFiles
C. SparkListener
D. SparkSession

4 What is a DataFrame in Spark SQL?

Concepts of Spark SQL Easy
A. A network containing connected nodes
B. A local file with unnamed records
C. A distributed table with named columns
D. A program containing compiled classes

5 Which approach converts an RDD of case class objects into a DataFrame by automatically inferring its schema?

Methods to convert RDDs to DataFrames Easy
A. File-based schema compression
B. Reflection-based schema inference
C. Manual partition assignment
D. Network-based data transfer

6 Which schema type is commonly created when converting an RDD to a DataFrame programmatically?

Methods to convert RDDs to DataFrames Easy
A. StructType
B. StorageLevel
C. SparkConf
D. Partitioner

7 After importing Spark implicits, which method commonly converts an RDD of tuples into a DataFrame?

Methods to convert RDDs to DataFrames Easy
A. toDF()
B. collect()
C. toRDD()
D. persist()

8 Which method registers a DataFrame as a temporary SQL view?

Concepts of Spark SQL Easy
A. createGlobalDatabase()
B. saveTemporaryFile()
C. registerPermanentTable()
D. createOrReplaceTempView()

9 Which join returns only rows that have matching values in both datasets?

Joins Easy
A. Right outer join
B. Left outer join
C. Inner join
D. Full outer join

10 Which join returns all rows from the left dataset and matching rows from the right dataset?

Joins Easy
A. Left outer join
B. Right outer join
C. Inner join
D. Cross join

11 Which SQL keyword specifies the condition used to match rows in a join?

Joins Easy
A. HAVING
B. ON
C. LIMIT
D. INTO

12 What is the purpose of the SQL GROUP BY clause?

GroupBy Easy
A. To sort rows into ascending order
B. To group rows sharing common values
C. To remove columns from a table
D. To combine tables without conditions

13 Which query operation counts employees in each department?

GroupBy Easy
A. GROUP BY department with COUNT(*)
B. JOIN department with MAX(*)
C. ORDER BY department with SUM(*)
D. WHERE department with AVG(*)

14 What does the SQL ORDER BY clause do?

OrderBy Easy
A. Deletes the query result
B. Groups the query result
C. Joins two query results
D. Sorts the query result

15 Which keyword sorts values from highest to lowest?

OrderBy Easy
A. DISTINCT
B. ASC
C. BETWEEN
D. DESC

16 Which SQL aggregate function returns the number of rows?

Aggregate functions Easy
A. AVG()
B. MAX()
C. SUM()
D. COUNT()

17 Which aggregate function calculates the arithmetic mean of numeric values?

Aggregate functions Easy
A. SUM()
B. AVG()
C. COUNT()
D. MIN()

18 Which aggregate function calculates the total of numeric values in a column?

Aggregate functions Easy
A. COUNT()
B. MAX()
C. SUM()
D. AVG()

19 In a SQL LIKE pattern, what does the % wildcard represent?

SQL wildcards Easy
A. Exactly one character
B. Only one numeric digit
C. Only one blank space
D. Zero or more characters

20 In a SQL LIKE pattern, what does the _ wildcard represent?

SQL wildcards Easy
A. Only numeric characters
B. Only uppercase characters
C. Zero or more characters
D. Exactly one character

21 An application must analyze Parquet files and JSON records using both SQL queries and DataFrame operations. Which Spark SQL feature best supports this requirement?

Importance and features of Spark SQL Medium
A. A unified API for querying structured data from multiple sources
B. A scheduler that requires separate engines for SQL and DataFrames
C. A storage engine that converts every source into an RDD file
D. A streaming service that supports only schema-free text records

22 A query reads a Parquet table but selects only two columns and filters rows by date. Which Spark SQL optimization can reduce the amount of data read?

Importance and features of Spark SQL Medium
A. Row duplication and partition expansion
B. Cartesian joins and full table caching
C. Schema removal and eager evaluation
D. Column pruning and predicate pushdown

23 In Scala, an RDD[Employee] contains instances of a case class Employee. After importing spark.implicits._, which expression converts it to a DataFrame using schema inference?

Methods to convert RDDs to DataFrames Medium
A. employeeRDD.toDF()
B. employeeRDD.collect()
C. employeeRDD.mapPartitions()
D. employeeRDD.toLocalIterator

24 An RDD[Row] is created from a text file, and the column types must be explicitly controlled. Which approach should be used?

Methods to convert RDDs to DataFrames Medium
A. Create a StructType and call spark.createDataFrame(rowRDD, schema)
B. Convert the RDD to text and call spark.read.json() directly
C. Apply rowRDD.reduce() and infer columns from the final row
D. Call rowRDD.collect() and register the resulting local array

25 In Scala, pairRDD is an RDD[(Int, String)]. Which expression creates a DataFrame with columns named emp_id and emp_name, assuming Spark implicits are imported?

Methods to convert RDDs to DataFrames Medium
A. pairRDD.schema("emp_id", "emp_name")
B. pairRDD.toDF("emp_id", "emp_name")
C. pairRDD.asRow("emp_id", "emp_name")
D. pairRDD.columns("emp_id", "emp_name")

26 A DataFrame named salesDF must be queried with spark.sql("SELECT * FROM sales") in the current Spark session. What should be done first?

Concepts of Spark SQL Medium
A. Call salesDF.write.saveAsTextFile("sales")
B. Call salesDF.repartition("sales")
C. Call salesDF.persist(StorageLevel.NONE)
D. Call salesDF.createOrReplaceTempView("sales")

27 A program creates a DataFrame with several select and filter operations, but no Spark job appears in the UI. Which operation will normally trigger execution?

Concepts of Spark SQL Medium
A. Calling count() on the final DataFrame
B. Renaming a column with withColumnRenamed()
C. Adding another filter() transformation
D. Creating an alias with alias()

28 A report should include only orders whose customer_id exists in the customer table. Which join type should be used between orders and customers?

Joins Medium
A. Left anti join
B. Left outer join
C. Inner join
D. Full outer join

29 A DataFrame employees must return only employees whose department_id has a match in departments, without adding any department columns. Which join is most suitable?

Joins Medium
A. Full outer join
B. Left semi join
C. Right outer join
D. Left outer join

30 A report must list every department, including departments that currently have no employees. If departments is the left DataFrame, which join should be used?

Joins Medium
A. Left outer join
B. Left semi join
C. Inner join
D. Left anti join

31 Two DataFrames both contain a column named id. After joining them using an expression such as a.id == b.id, selecting id produces an ambiguous-column error. What is the best solution?

Joins Medium
A. Sort both DataFrames by id before selecting the column
B. Convert both id columns to strings before the join
C. Assign aliases and select a qualified column such as a.id
D. Cache both DataFrames and repeat the same unqualified selection

32 Which SQL query returns regions whose total sales amount exceeds 100000?

GroupBy Medium
A. SELECT region, SUM(amount) FROM sales ORDER BY SUM(amount) > 100000
B. SELECT region, SUM(amount) FROM sales GROUP BY region HAVING SUM(amount) > 100000
C. SELECT region, SUM(amount) FROM sales WHERE SUM(amount) > 100000 GROUP BY region
D. SELECT region, SUM(amount) FROM sales HAVING amount > 100000 GROUP BY region

33 What is the result of applying salesDF.groupBy("region", "product").sum("amount")?

GroupBy Medium
A. One result row for every original sales record
B. One result row for each distinct region regardless of product
C. One result row for each product regardless of region
D. One result row for each distinct region-product combination

34 Which statement correctly distinguishes ORDER BY from SORT BY in Spark SQL?

OrderBy Medium
A. ORDER BY provides global ordering, while SORT BY orders rows within partitions
B. ORDER BY supports numbers, while SORT BY supports only text columns
C. ORDER BY removes duplicates, while SORT BY preserves duplicate rows
D. ORDER BY orders within partitions, while SORT BY provides global ordering

35 A result must show employees by descending salary, with employees having equal salaries arranged by ascending name. Which clause is correct?

OrderBy Medium
A. ORDER BY salary ASC, name DESC
B. ORDER BY name ASC, salary DESC
C. ORDER BY name DESC, salary ASC
D. ORDER BY salary DESC, name ASC

36 A table has 100 rows, and the bonus column contains 15 NULL values. What will COUNT(*) and COUNT(bonus) return?

Aggregate functions Medium
A. 100 and 100, respectively
B. 100 and 85, respectively
C. 85 and 100, respectively
D. 85 and 85, respectively

37 The values in a column are 10, 20, NULL, and 30. What does Spark SQL return for AVG(value)?

Aggregate functions Medium
A. 12
B. 15
C. 20
D. NULL

38 A grouped query must collect the distinct product names purchased in each region into an array. Which Spark SQL aggregate function is appropriate?

Aggregate functions Medium
A. first(product)
B. collect_list(product)
C. concat(product)
D. collect_set(product)

39 Which LIKE condition matches values that contain the substring data anywhere in the text?

SQL wildcards Medium
A. LIKE '_data_'
B. LIKE '%data%'
C. LIKE '%data'
D. LIKE 'data%'

40 What type of value is matched by the SQL pattern LIKE 'A_%'?

SQL wildcards Medium
A. A value starting with A and containing no additional characters
B. A value containing a literal underscore immediately after A
C. A value ending with A and containing at least one earlier character
D. A value starting with A and containing at least one more character

41 A pipeline filters adult users and converts names to uppercase. Which implementation gives Catalyst the greatest opportunity for predicate optimization, column pruning, and whole-stage code generation?

Importance and features of Spark SQL Hard
A. Convert the DataFrame to an RDD and apply a Scala function to every row
B. Use DataFrame expressions such as filter, select, and the built-in upper function
C. Register a Scala UDF containing both operations and invoke it from SQL
D. Apply a Python UDF for filtering and a second Python UDF for capitalization

42 A DataFrame is registered as a temporary view, queried through SQL, and then filtered again through the DataFrame API. No caching operation is used. Which statement best describes execution?

Importance and features of Spark SQL Hard
A. The SQL segment is optimized independently and executed before later operators
B. Crossing from SQL to the DataFrame API forces an intermediate disk checkpoint
C. SQL and DataFrame operators contribute to a lazily optimized logical plan
D. Registering the view immediately materializes the DataFrame in executor memory

43 Given RDD[(String, String)] containing (name, ageText) and case class Person(name: String, age: Int), which conversion produces columns named name and age with age represented as an integer?

Methods to convert RDDs to DataFrames Hard
A. Import spark.implicits._, map each tuple to Person(n, a.toInt), and call toDF()
B. Call spark.createDataFrame(rdd) and attach the Person schema after execution
C. Call rdd.toDF("name", "age") and rely on column naming to convert the type
D. Map each tuple to (n, a) and cast the entire resulting DataFrame to Person

44 An RDD[Row] is converted using spark.createDataFrame(rows, schema). The schema declares (id: Long, amount: Double), but each row contains (amountValue, idValue) in that order. What is the key correctness issue?

Methods to convert RDDs to DataFrames Hard
A. Spark sorts schema fields alphabetically before associating them with row values
B. The schema affects only column labels, so the reversed row order has no effect
C. Spark matches unnamed Row values to schema fields by their runtime data types
D. Row values are positional, so their order and compatible types must match the schema

45 An RDD[String] contains JSON records, but a numeric field is absent from many initial records. Which approach both enforces the intended numeric type and avoids a schema-inference pass?

Methods to convert RDDs to DataFrames Hard
A. Use spark.createDataFrame(jsonRDD, expectedSchema) to parse each JSON document
B. Use spark.read.schema(expectedSchema).json(jsonRDD) with an explicit StructType
C. Use jsonRDD.toDF("json") because JSON fields are automatically expanded
D. Use spark.read.json(jsonRDD) and assume later records will revise inferred types

46 Session S1 creates both a local temporary view v and a global temporary view g. A new Spark session S2 is created within the same Spark application. Which access pattern is valid?

Concepts of Spark SQL Hard
A. S2 can query only v, using the name global_temp.v
B. S2 can query only g, using the name global_temp.g
C. S2 can query both views directly as v and g
D. S2 cannot query either view because all temporary views are session-local

47 A nullable column score must be filtered so that rows with score = 5 are removed while rows with other values or NULL are retained. Which predicate has the required semantics?

Concepts of Spark SQL Hard
A. score <> 5 AND score IS NOT NULL
B. NOT (score = 5) AND score IS NULL
C. NOT (score = 5 OR score IS NULL)
D. score <> 5 OR score IS NULL

48 The query employees e LEFT JOIN departments d ON e.dept_id = d.id WHERE d.active = TRUE unexpectedly removes employees with no department. Which rewrite retains every employee while attaching only active department data?

Joins Hard
A. Replace the left join with a full outer join and keep the same filter
B. Replace the left join with a cross join followed by both predicates
C. Add e.dept_id IS NOT NULL to the existing WHERE condition
D. Move d.active = TRUE into the ON condition of the left join

49 Two join-key columns may contain NULL. The requirement is that two rows match when their keys are equal or when both keys are NULL, but not when only one key is NULL. Which Spark SQL condition satisfies this requirement?

Joins Hard
A. l.key <=> r.key
B. l.key IS NULL OR r.key IS NULL
C. l.key <> r.key
D. l.key = r.key

50 The left relation contains (1,a), (1,b), (NULL,c), and (2,d). The right relation contains keys 1, 1, and NULL. What does a left-semi join using ordinary equality on the key return?

Joins Hard
A. Four rows with key 1, because every matching right row duplicates output
B. All four left rows because a semi join preserves the complete left relation
C. The two left rows with key 1, each appearing exactly once
D. The two key-1 rows and the key-NULL row, each appearing once

51 Two DataFrames both contain a column named id. How does joining them by a key-name list differ from joining them with the explicit condition left.id = right.id?

Joins Hard
A. The key-name join produces one merged id, while the explicit condition retains both key columns
B. Both joins always produce one id because Catalyst removes every duplicate column name
C. Both joins retain two id columns because join conditions never influence output schemas
D. The key-name join retains both id columns, while the explicit condition merges them automatically

52 A query uses GROUP BY CUBE(region, product), and both source columns may already contain NULL. Which statement correctly describes the result?

GroupBy Hard
A. It creates two grouping sets, and source nulls are removed before aggregation
B. It creates four grouping sets, but subtotal nulls cannot be distinguished from source nulls
C. It creates one grouping set for every distinct pair of non-null source values
D. It creates four grouping sets, and GROUPING or GROUPING_ID can identify subtotal nulls

53 Rows are (A,10), (A,NULL), (A,10), and (B,NULL). For each group, Spark computes COUNT(*), COUNT(value), COUNT(DISTINCT value), and SUM(value). Which results are correct?

GroupBy Hard
A. A: (3,2,2,20) and B: (1,0,1,NULL)
B. A: (3,2,1,20) and B: (1,0,0,NULL)
C. A: (2,2,1,20) and B: (0,0,0,NULL)
D. A: (3,3,2,20) and B: (1,1,1,0)

54 A grouped query must collect all integer values, preserve duplicates, and produce a deterministic ascending array for each key. Which expression best satisfies the requirement?

GroupBy Hard
A. sort_array(collect_list(value))
B. sort_array(collect_set(value))
C. first(value) followed by an array conversion
D. collect_list(value) after globally ordering the input

55 For values NULL, 2, and 1, what are Spark SQL's default results for ORDER BY value ASC and ORDER BY value DESC, respectively?

OrderBy Hard
A. ASC: 1,2,NULL; DESC: NULL,2,1
B. ASC: NULL,1,2; DESC: NULL,2,1
C. ASC: 1,2,NULL; DESC: 2,1,NULL
D. ASC: NULL,1,2; DESC: 2,1,NULL

56 A DataFrame has many partitions. Which statement correctly compares orderBy(key) with sortWithinPartitions(key)?

OrderBy Hard
A. orderBy orders only inside partitions, while sortWithinPartitions establishes global ordering
B. Both order only inside partitions, and neither can produce globally ordered collected output
C. orderBy establishes global ordering, while sortWithinPartitions orders only inside each partition
D. Both establish global ordering, but sortWithinPartitions always performs an additional shuffle

57 A global aggregation is executed over an empty DataFrame: SELECT COUNT(*), COUNT(v), SUM(v), AVG(v) FROM t. What result does Spark SQL produce?

Aggregate functions Hard
A. One row containing (NULL, NULL, NULL, NULL)
B. One row containing (0, 0, NULL, NULL)
C. No rows because the input relation is empty
D. One row containing (0, NULL, 0, 0)

58 Orders (1,100) and (2,100) have two and three matching item rows, respectively. Which query computes total qualifying order revenue as 200 without being affected by the one-to-many join or equal order totals?

Aggregate functions Hard
A. SELECT SUM(o.total) / COUNT(DISTINCT i.item_id) FROM orders o JOIN items i ON o.order_id = i.order_id
B. SELECT SUM(DISTINCT o.total) FROM orders o INNER JOIN items i ON o.order_id = i.order_id
C. SELECT SUM(o.total) FROM orders o LEFT SEMI JOIN items i ON o.order_id = i.order_id
D. SELECT SUM(o.total) FROM orders o INNER JOIN items i ON o.order_id = i.order_id

59 Given strings A, AB, A_, A12, and BA1, which set matches the Spark SQL predicate value LIKE 'A_%'?

SQL wildcards Hard
A. AB, A12, and BA1
B. A_ and A12 only
C. A, AB, A_, and A12
D. AB, A_, and A12

60 Which predicate matches every code that begins with the literal characters A_, treating the underscore as data rather than as a wildcard?

SQL wildcards Hard
A. code LIKE 'A!_%' ESCAPE '!'
B. code LIKE 'A!!_%' ESCAPE '!'
C. code LIKE 'A_%' ESCAPE '!'
D. code LIKE 'A_!%' ESCAPE '!'