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. Processing structured and semi-structured data
C. Designing graphical user interfaces
D. Compiling Java source code

2 Which Spark SQL component optimizes query execution plans?

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

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

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

4 What is a DataFrame in Spark SQL?

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

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. Network-based data transfer
B. Manual partition assignment
C. Reflection-based schema inference
D. File-based schema compression

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

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

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. toRDD()
C. collect()
D. persist()

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

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

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

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

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

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

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

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

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

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

13 Which query operation counts employees in each department?

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

14 What does the SQL ORDER BY clause do?

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

15 Which keyword sorts values from highest to lowest?

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

16 Which SQL aggregate function returns the number of rows?

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

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

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

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

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

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

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

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

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

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 scheduler that requires separate engines for SQL and DataFrames
B. A storage engine that converts every source into an RDD file
C. A unified API for querying structured data from multiple sources
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. Column pruning and predicate pushdown
B. Row duplication and partition expansion
C. Schema removal and eager evaluation
D. Cartesian joins and full table caching

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.collect()
B. employeeRDD.toDF()
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. Call rowRDD.collect() and register the resulting local array
B. Create a StructType and call spark.createDataFrame(rowRDD, schema)
C. Apply rowRDD.reduce() and infer columns from the final row
D. Convert the RDD to text and call spark.read.json() directly

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.columns("emp_id", "emp_name")
B. pairRDD.asRow("emp_id", "emp_name")
C. pairRDD.toDF("emp_id", "emp_name")
D. pairRDD.schema("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.createOrReplaceTempView("sales")
C. Call salesDF.persist(StorageLevel.NONE)
D. Call salesDF.repartition("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. Inner join
B. Left anti join
C. Full outer join
D. Left 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. Left outer join
B. Left semi join
C. Full outer join
D. Right 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 semi join
B. Inner join
C. Left outer 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. Convert both id columns to strings before the join
B. Cache both DataFrames and repeat the same unqualified selection
C. Assign aliases and select a qualified column such as a.id
D. Sort both DataFrames by id before selecting the column

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

GroupBy Medium
A. SELECT region, SUM(amount) FROM sales GROUP BY region HAVING SUM(amount) > 100000
B. SELECT region, SUM(amount) FROM sales WHERE SUM(amount) > 100000 GROUP BY region
C. SELECT region, SUM(amount) FROM sales ORDER BY SUM(amount) > 100000
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 each distinct region-product combination
B. One result row for every original sales record
C. One result row for each distinct region regardless of product
D. One result row for each product regardless of region

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 removes duplicates, while SORT BY preserves duplicate rows
C. ORDER BY supports numbers, while SORT BY supports only text columns
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 salary DESC, name ASC
C. ORDER BY name DESC, salary ASC
D. ORDER BY name ASC, salary DESC

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. 85 and 85, respectively
B. 100 and 85, respectively
C. 100 and 100, respectively
D. 85 and 100, 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. 15
B. NULL
C. 20
D. 12

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. concat(product)
B. collect_set(product)
C. first(product)
D. collect_list(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 containing a literal underscore immediately after A
B. A value ending with A and containing at least one earlier character
C. A value starting with A and containing no additional characters
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. Use DataFrame expressions such as filter, select, and the built-in upper function
B. Convert the DataFrame to an RDD and apply a Scala function to every row
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. Crossing from SQL to the DataFrame API forces an intermediate disk checkpoint
B. SQL and DataFrame operators contribute to a lazily optimized logical plan
C. Registering the view immediately materializes the DataFrame in executor memory
D. The SQL segment is optimized independently and executed before later operators

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. Map each tuple to (n, a) and cast the entire resulting DataFrame to Person
B. Call rdd.toDF("name", "age") and rely on column naming to convert the type
C. Call spark.createDataFrame(rdd) and attach the Person schema after execution
D. Import spark.implicits._, map each tuple to Person(n, a.toInt), and call toDF()

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. Spark matches unnamed Row values to schema fields by their runtime data types
C. Row values are positional, so their order and compatible types must match the schema
D. The schema affects only column labels, so the reversed row order has no effect

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.read.json(jsonRDD) and assume later records will revise inferred types
B. Use jsonRDD.toDF("json") because JSON fields are automatically expanded
C. Use spark.createDataFrame(jsonRDD, expectedSchema) to parse each JSON document
D. Use spark.read.schema(expectedSchema).json(jsonRDD) with an explicit StructType

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 both views directly as v and g
C. S2 can query only g, using the name global_temp.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 OR score IS NULL)
C. NOT (score = 5) AND 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. Move d.active = TRUE into the ON condition of the left join
B. Add e.dept_id IS NOT NULL to the existing WHERE condition
C. Replace the left join with a cross join followed by both predicates
D. Replace the left join with a full outer join and keep the same filter

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 IS NULL OR r.key IS NULL
B. l.key <> r.key
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. The two key-1 rows and the key-NULL row, each appearing once
B. Four rows with key 1, because every matching right row duplicates output
C. The two left rows with key 1, each appearing exactly once
D. All four left rows because a semi join preserves the complete left relation

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

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 one grouping set for every distinct pair of non-null source values
C. It creates four grouping sets, and GROUPING or GROUPING_ID can identify subtotal nulls
D. It creates four grouping sets, but subtotal nulls cannot be distinguished from source 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. collect_list(value) after globally ordering the input
B. first(value) followed by an array conversion
C. sort_array(collect_list(value))
D. sort_array(collect_set(value))

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: NULL,1,2; DESC: 2,1,NULL
B. ASC: 1,2,NULL; DESC: 2,1,NULL
C. ASC: NULL,1,2; DESC: NULL,2,1
D. ASC: 1,2,NULL; DESC: NULL,2,1

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

OrderBy Hard
A. Both order only inside partitions, and neither can produce globally ordered collected output
B. orderBy establishes global ordering, while sortWithinPartitions orders only inside each partition
C. orderBy orders only inside partitions, while sortWithinPartitions establishes global ordering
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. One row containing (0, NULL, 0, 0)
D. No rows because the input relation is empty

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) FROM orders o INNER 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) / COUNT(DISTINCT i.item_id) FROM orders o JOIN items i ON o.order_id = i.order_id
D. SELECT SUM(o.total) FROM orders o LEFT SEMI 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, A_, and A12
B. AB, A12, and BA1
C. A, AB, A_, and A12
D. A_ and A12 only

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 '!'