Courseiva

Databricks Certified Associate Developer for Apache Spark (Databricks-Spark-Assoc) — Questions 1–75

295 questions total · 4pages · All types, answers revealed

Page 1 of 4

Page 2
1
MCQeasy

In Spark's cluster architecture, what happens to the tasks if the Driver node crashes during the execution of a job?

A.Tasks continue to run until the current stage is completed.
B.The cluster manager automatically restarts the driver and resumes tasks.
C.The entire application fails and tasks are terminated.
D.Executors take over the driver's role to finish remaining tasks.
AnswerC

The driver acts as the master process. Its failure results in the loss of the SparkContext, which leads to the immediate termination of the application and all associated tasks. There is no mechanism for executors to continue or recover the work without the driver.

Why this answer

When the Spark Driver fails, the entire SparkContext is terminated. Since the driver is responsible for scheduling tasks and maintaining the application state, all executors lose their connection to the driver, and any pending or running tasks are aborted. The application essentially crashes, and the resources held by the executors will eventually be reclaimed by the cluster manager based on the application's exit status.

Exam trap

Candidates often assume that if the Driver crashes, executors can continue running independent tasks, misunderstanding the critical supervisory role of the SparkContext.

2
MCQhard

A developer is writing a Spark SQL query that must handle null values in a column named discount. The requirement is to replace null discounts with 0.0, but also to replace any negative discount values with 0.0, leaving positive values unchanged. Which expression should be used?

A.COALESCE(GREATEST(discount, 0.0), 0.0)
B.IF(discount < 0, 0.0, discount)
C.GREATEST(discount, 0.0)
D.COALESCE(discount, 0.0)
AnswerA

GREATEST(discount, 0.0) turns negative values into 0.0 but returns null if discount is null. Wrapping it with COALESCE(..., 0.0) replaces that null with 0.0. This combination satisfies both conditions: nulls become 0.0, negatives become 0.0, and positive values are preserved. It is the correct nested expression.

Why this answer

The requirement is to treat both nulls and negatives as zero. GREATEST(discount, 0.0) ensures negatives become 0.0 but yields null for null input. COALESCE then replaces that null with 0.0.

The nested expression COALESCE(GREATEST(discount, 0.0), 0.0) correctly handles both cases and leaves positive values untouched. Using COALESCE alone misses negatives, GREATEST alone misses nulls, and the IF expression misses nulls.

Exam trap

The trap here is forgetting that GREATEST returns null when any argument is null, so a separate COALESCE is needed to handle null inputs.

3
MCQeasy

Which component in Structured Streaming is responsible for providing fault tolerance and ensuring data is processed exactly once?

A.The State Store
B.Checkpointing
C.The Write Ahead Log
D.The Driver
AnswerB

Checkpointing records the metadata and offsets of the micro-batches in a persistent store. This allows the streaming query to recover from failures and resume processing exactly where it left off, which is the cornerstone of providing the exactly-once fault-tolerance guarantees expected in enterprise data pipelines.

Why this answer

Checkpointing is the mechanism that stores the query's metadata and progress in durable storage (like DBFS or S3). By recording the offset of the processed data, Spark can recover from failures and restart from the exact point where it left off. This is fundamental to ensuring that streaming applications are reliable and maintain exactly-once processing guarantees across restarts or cluster crashes.

Exam trap

Candidates often confuse checkpointing with logging. They think checkpointing is just for debugging output, whereas it is actually the critical mechanism for state recovery and exactly-once processing guarantees.

4
MCQhard

You have a Pandas-on-Spark DataFrame 'psdf'. You perform an operation that results in a 'compute.ops_on_diff_frames' error. What is the root cause of this behavior?

A.The cluster does not have enough memory to perform the join operation.
B.The two DataFrames have different schemas and cannot be joined.
C.The two DataFrames share the same Spark execution plan.
D.The two DataFrames originate from different Spark plans and cannot be aligned safely.
AnswerD

This error occurs because Pandas-on-Spark needs to ensure data integrity. By default, it refuses to perform operations between two different DataFrames unless they are explicitly joined or aligned. This prevents implicit, high-latency shuffles that would occur if the library attempted to match rows across disparate execution graphs.

Why this answer

Pandas-on-Spark prevents operations between two different DataFrames if they originate from different Spark execution plans or have different index configurations. This is designed to prevent implicit, expensive shuffles that could lead to data loss or integrity issues during joins. Recognizing this constraint is crucial for debugging complex data pipelines where multiple transformations occur, as developers must often align indices or combine data explicitly before performing cross-DataFrame operations.

Exam trap

Candidates often assume Pandas-on-Spark behaves exactly like standard Pandas, failing to realize that Spark enforces strict lineage and plan alignment to prevent dangerous, implicit cross-partition shuffles.

5
MCQmedium

When performing a join between a very small table and a massive table, which Spark SQL optimization technique should be applied to prevent a full shuffle?

A.Use the /*+ BROADCAST(small_table) */ hint.
B.Increase the shuffle partitions to 2000.
C.Enable the 'autoBroadcastJoinThreshold' to a very low value.
D.Convert the massive table into an unmanaged view.
AnswerA

The BROADCAST hint explicitly instructs the Spark optimizer to broadcast the smaller table to all worker nodes. This eliminates the need for a shuffle, which is the most expensive part of a join, and is a standard way to ensure high-performance execution in Spark SQL for asymmetric join operations.

Why this answer

Broadcasting is a critical optimization technique for star-schema joins. By sending a copy of the small table to every executor, Spark avoids the expensive shuffle phase associated with shuffling the massive table. This significantly reduces network I/O and latency.

For a Databricks developer, recognizing when to use hints or rely on the optimizer to perform broadcast joins is vital for writing performant, scalable SQL queries on large datasets.

Exam trap

Test-takers sometimes try to use partition pruning or caching hints instead of the specific broadcast hint required to eliminate shuffles during joins.

6
MCQmedium

A developer is writing a Spark Connect application that must run a pandas UDF on a remote Databricks cluster. The code uses the spark.conf.set() API to pass a custom Python module to the executors. Which statement describes the correct behavior?

A.spark.conf.set() automatically packages the referenced module and sends it to the executors as part of the Spark Connect session configuration.
B.The pandas UDF will work because Spark Connect serializes all local Python modules along with the UDF closure and ships them to the remote cluster.
C.spark.conf.set() can only set Spark SQL configuration properties; it cannot transfer arbitrary Python modules to executors, so the pandas UDF will fail with an ImportError.
D.spark.conf.set() can transfer the module only if the module is already present in the Spark Connect client's current working directory.
AnswerC

spark.conf.set() is strictly for Spark configuration properties. It has no mechanism to ship a Python module to the remote executors, so any pandas UDF that imports that module will raise an ImportError. To distribute code with Spark Connect, the module must be installed as a cluster library or uploaded to a workspace path.

Why this answer

spark.conf.set() is designed exclusively for Spark configuration properties and cannot distribute Python code. In a Spark Connect architecture, the client and executors are decoupled, so any custom Python dependencies used by pandas UDFs must be installed on the cluster as libraries or uploaded to a path that the cluster can access. Setting a configuration value will not make the module available.

Exam trap

The trap here is assuming that spark.conf.set() can be used as a generic code-distribution mechanism because it accepts arbitrary key-value pairs.

7
MCQeasy

Which SQL command is used to view the history of operations performed on a Delta table, including timestamps and operation types?

A.SHOW METADATA ON table_name
B.SELECT * FROM audit_log(table_name)
C.DESCRIBE HISTORY table_name
D.GET TABLE VERSION table_name
AnswerC

DESCRIBE HISTORY is the standard command for viewing the transaction log of a Delta table. It displays information such as the operation, user, timestamp, and version, which are critical for debugging and data lineage analysis. This command allows users to monitor table evolution and identify specific modifications.

Why this answer

The DESCRIBE HISTORY command is a core utility in Databricks for auditing and troubleshooting. It provides a detailed log of all modifications, including writes, updates, and deletes, along with version numbers. This is essential for understanding table evolution, debugging data pipelines, and implementing data governance.

Knowing this command is mandatory for any Spark developer responsible for maintaining and auditing production-level Delta Lake tables.

Exam trap

Test-takers often confuse DESCRIBE HISTORY with standard table description commands like DESCRIBE DETAIL or DESCRIBE TABLE, missing the temporal aspect of operations.

8
MCQhard

A PySpark job reads a Delta table, applies a filter on a timestamp column, and then performs a window function partitioned by customer_id ordered by event_time. The job is slow, and the physical plan shows the filter is applied after the window. The developer wants the filter to reduce data before the window shuffle. Which action should the developer take?

A.Increase spark.sql.windowExec.buffer.spill.threshold so the window operator can spill more data to disk.
B.Repartition the DataFrame by customer_id before applying the filter so the window avoids a shuffle.
C.Apply the filter on the timestamp column immediately after reading the Delta table, before calling the window function, so predicate pushdown and early filtering reduce rows entering the shuffle.
D.Cache the DataFrame before the window and call count() to materialize it, then apply the filter.
AnswerC

Filtering right after the read lets Spark push the predicate into the Delta scan where possible and reduces the number of rows that must be shuffled for the window. This lowers shuffle size, memory pressure, and runtime, and it is the direct way to get the filter to act before the window partitioning.

Why this answer

The physical plan shows the filter after the window, meaning the window shuffle processes all rows. Moving the filter to immediately after the read lets Spark push it into the Delta scan where possible and shrink the dataset before the window shuffle, reducing shuffle volume, memory use, and overall runtime.

Exam trap

The trap here is tuning window spill or repartitioning by the window key, when the real win is applying the filter before the window so fewer rows ever enter the shuffle.

9
MCQhard

A developer is using Spark SQL to process a streaming DataFrame from a Kafka source. They need to perform a stateful operation that maintains state across micro-batches to count occurrences of each key over a sliding window of 10 minutes, sliding every 5 minutes. Which Spark SQL operation should they use?

A.Use the foreachBatch sink to manually maintain state in an external database.
B.Use groupBy with window('timestamp', '10 minutes', '5 minutes') and then count.
C.Use a tumbling window with window('timestamp', '10 minutes') and then count.
D.Use the dropDuplicates operator to remove duplicates within 10 minutes, then count.
AnswerB

Spark SQL structured streaming supports windowed aggregations using the window function. Specifying a window duration of 10 minutes and slide duration of 5 minutes creates overlapping windows. Grouping by the window and key, then counting, maintains state across micro-batches to produce counts per window. This is the correct approach for sliding window aggregations in structured streaming.

Why this answer

Structured streaming in Spark SQL supports windowed aggregations through the window function. Specifying a window duration and slide duration enables sliding windows. Grouping by the window and key, then applying an aggregation like count, maintains state across micro-batches and produces results for each window.

This is the built-in, fault-tolerant approach for stateful stream processing.

Exam trap

The trap here is confusing tumbling windows with sliding windows; tumbling windows do not overlap, while sliding windows require both window and slide durations.

10
MCQmedium

When performing a 'Z-ORDER' operation on a Delta table, how does it improve query performance?

A.It compresses data more tightly than standard Parquet compression.
B.It reorders data to maximize the effectiveness of data skipping.
C.It automatically creates a secondary index for every column in the table.
D.It removes all null values from the table to reduce storage size.
AnswerB

Z-Ordering rearranges data within files to ensure that related values are physically grouped together. This maximizes the probability that a query filter will result in skipping entire files, as the file-level statistics (min/max) become much more discriminative, directly reducing the total amount of data read from storage.

Why this answer

Z-Ordering is a technique that maps multi-dimensional data to one dimension while preserving locality. By co-locating related information in the same files, Z-Ordering enables the Delta Lake reader to skip more data when filtering. This is highly effective for high-cardinality columns, as it dramatically increases the effectiveness of data skipping, leading to significantly faster query response times in large, partitioned Delta tables.

Exam trap

Students often mistake Z-Ordering for standard partitioning or indexing, assuming it physically sorts the entire table into a single ordered sequence.

11
MCQmedium

You are optimizing a Spark SQL query that performs a large join between a 10GB table and a 5MB lookup table. To ensure performance efficiency, which command should you use to hint to the optimizer?

A.SELECT /*+ MERGE(t1, t2) */ * FROM t1 JOIN t2
B.SELECT /*+ SHUFFLE(t1, t2) */ * FROM t1 JOIN t2
C.SELECT /*+ BROADCAST(t2) */ * FROM t1 JOIN t2
D.SELECT /*+ SKEW(t1) */ * FROM t1 JOIN t2
AnswerC

The BROADCAST hint explicitly instructs the Spark catalyst optimizer to perform a broadcast hash join. By duplicating the smaller table to all executors, Spark eliminates the need for expensive wide transformations and data reshuffling, allowing the join to occur locally within each task, which maximizes performance for this specific scenario.

Why this answer

Spark SQL uses cost-based optimization, but small table broadcasts significantly reduce network shuffle overhead. By using the BROADCAST hint, you force the engine to send the small table to every executor, avoiding a full shuffle of the 10GB dataset. This is a critical optimization technique in Databricks environments where minimizing cross-node data movement is essential for reducing total job latency and improving cluster resource utilization.

Exam trap

Students frequently rely entirely on the Catalyst optimizer to catch small tables, forgetting that certain complex expressions prevent automatic broadcasting.

12
MCQhard

Refer to the exhibit. Which configuration issue is most likely causing this warning in a Spark application?

A.spark.driver.memory is set too high.
B.The requested spark.executor.memory exceeds node capacity.
C.The shuffle service is not enabled on the cluster.
D.The number of partitions is set too high for the cluster.
AnswerB

When an application requests more memory per executor than a single worker node can provide, the cluster manager cannot allocate the executors. The TaskScheduler will wait indefinitely for these resources, causing this warning as the job remains stuck in a pending state.

Why this answer

This warning indicates the driver is unable to find executors that meet the resource requirements specified for the job. This usually happens when the requested memory or CPU per executor exceeds what is available on the cluster's worker nodes. Checking the resource configuration against the cluster's physical limits is the first step in resolving this scheduling deadlock, as the driver remains idle waiting for resources that will never become available.

Exam trap

Candidates often choose incorrect configuration tweaks like increasing cores or changing shuffle partitions. They miss that the root cause is a resource constraint where the requested memory exceeds physical node capacity.

13
MCQeasy

What is the primary purpose of the 'pyspark.pandas' module in the Databricks environment?

A.To allow running standard Pandas code on a single node more quickly.
B.To provide a Pandas-like interface that executes on the Spark engine.
C.To convert Spark DataFrames to NumPy arrays for machine learning.
D.To manage Spark cluster configurations via Python dictionaries.
AnswerB

This is the core design philosophy of the Pandas-on-Spark project. It translates high-level Pandas API calls into optimized Spark execution plans, allowing users to use familiar syntax to write distributed programs that scale to petabytes of data across a Spark cluster.

Why this answer

The 'pyspark.pandas' module acts as a bridge, providing a familiar Pandas API for data scientists while running on the scalable Spark engine. This allows users to leverage existing Pandas skills without needing to learn complex PySpark syntax, while still benefiting from distributed computing. It is the core tool for scaling up data science workloads that would otherwise hit a 'single-node' wall on standard Pandas implementations.

Exam trap

Test-takers sometimes believe the module executes traditional single-node Pandas code faster, rather than recognizing it translates Pandas syntax to run on a distributed Spark engine.

14
MCQmedium

When analyzing a Spark job's execution plan, what does a 'BroadcastHashJoin' indicate compared to a 'SortMergeJoin'?

A.BroadcastHashJoin requires both tables to be pre-sorted.
B.BroadcastHashJoin avoids a shuffle operation.
C.SortMergeJoin is always faster than BroadcastHashJoin.
D.BroadcastHashJoin only works for inner joins.
AnswerB

Because the smaller table is sent to every executor node, the larger table remains in its original partition structure, and no data is shuffled across the network. This makes it a much faster join strategy compared to SortMergeJoin, which requires full shuffles of both tables to align the keys.

Why this answer

A 'BroadcastHashJoin' indicates that Spark has decided to send the smaller table to all executors to perform the join in memory, avoiding a shuffle. A 'SortMergeJoin' involves shuffling both tables, which is significantly more expensive. Understanding when Spark chooses one over the other helps developers identify if they need to explicitly broadcast small tables or adjust configuration thresholds to optimize join performance and minimize costly cluster-wide shuffle operations.

Exam trap

Candidates often think BroadcastHashJoin speeds up execution by sorting data faster, missing that its primary advantage is completely eliminating network shuffling.

15
MCQmedium

A developer is building a Structured Streaming pipeline that reads from a Kafka topic and writes to a Delta table. The pipeline must tolerate occasional downstream failures and reprocess data without duplicates. The developer sets a checkpoint location and uses the default output mode. Which statement correctly describes how the checkpoint location contributes to fault tolerance in this scenario?

A.The checkpoint location stores the last processed offset and query metadata, enabling the query to resume exactly where it left off after a restart.
B.The checkpoint location caches the entire streamed DataFrame in memory, allowing faster recovery after a driver restart.
C.The checkpoint location stores a copy of the Kafka topic's data, enabling replay from the checkpoint instead of Kafka.
D.The checkpoint location automatically deduplicates records in the Delta table by comparing primary keys.
AnswerA

The checkpoint location persists the streaming query's progress, including offsets and state, so after a failure the query can resume from the last committed offset and avoid reprocessing or data loss. This is fundamental to Structured Streaming's exactly-once semantics when used with a replayable source and idempotent sink.

Why this answer

The checkpoint location is critical for fault tolerance in Structured Streaming. It records the progress of the query, including offsets and state, so that after a failure the query can resume from the last committed offset. This, combined with a replayable source and an idempotent sink, enables exactly-once processing.

The other options misattribute caching, deduplication, or data storage to the checkpoint.

Exam trap

The trap here is assuming that the checkpoint location stores actual data or performs deduplication, when it only stores metadata and state.

16
MCQhard

You are using Spark SQL to analyze a Delta table named transactions that is partitioned by a column region. You need to run a query that filters on region and also on a non-partitioned column amount. The table has statistics collected on region and amount. Which of the following best describes how Spark SQL will optimize the query?

A.Spark SQL will perform a full table scan because the filter on amount is not on a partition column, and then apply the filter after reading all data.
B.Spark SQL will use partition pruning based on the region filter and then apply data skipping on amount using the collected statistics to skip files where amount does not match the filter.
C.Spark SQL will dynamically repartition the data based on the amount filter to optimize the query, using adaptive query execution.
D.Spark SQL will only use partition pruning on region and will not use any statistics for amount because statistics are only collected on partition columns.
AnswerB

Spark SQL leverages partition pruning to eliminate entire partitions based on the region filter. Additionally, Delta Lake collects statistics on non-partitioned columns like amount, enabling data skipping at the file level. When statistics indicate that a file's min/max range for amount does not overlap with the filter, that file is skipped. This combination drastically reduces I/O.

Why this answer

Spark SQL uses partition pruning for the region filter and Delta Lake's data skipping for the amount filter, thanks to collected statistics. This minimizes the amount of data read. The other options incorrectly assume limitations or alternative optimizations.

Exam trap

The trap here is underestimating Delta Lake's data skipping capabilities on non-partition columns or confusing it with dynamic optimizations like AQE.

17
MCQhard

A Spark application running on Databricks uses broadcast joins for a small dimension table. A developer notices that the broadcast variable is not being sent to executors as expected, causing a shuffle instead. Which configuration property directly controls the maximum size of a table that Spark will automatically broadcast?

A.spark.sql.autoBroadcastJoinThreshold
B.spark.broadcast.blockSize
C.spark.sql.broadcastTimeout
D.spark.sql.shuffle.partitions
AnswerA

spark.sql.autoBroadcastJoinThreshold sets the maximum size in bytes of a table that Spark will broadcast automatically during a join. If the small table's size exceeds this threshold, Spark falls back to a shuffle join. Adjusting this property directly influences whether a broadcast join is chosen, making it the correct control for the scenario.

Why this answer

The automatic selection of a broadcast join is governed by spark.sql.autoBroadcastJoinThreshold, which defaults to 10 MB in Spark. If the small table's estimated size is below this threshold, Spark broadcasts it; otherwise, it uses a shuffle join. Other properties like shuffle partitions, broadcast block size, and broadcast timeout affect execution details but not the decision to broadcast based on table size.

Exam trap

The trap here is conflating properties that affect broadcast execution (block size, timeout) with the one that controls the size-based decision to broadcast, which is autoBroadcastJoinThreshold.

18
MCQmedium

A developer is writing a Spark Connect application that needs to read a CSV file from cloud storage and then perform a groupBy aggregation. The developer wants to minimize data transfer between the client and the server. Which of the following approaches best achieves this?

A.Use spark.read.csv() to load the file, then call .toPandas() to convert the DataFrame to a pandas DataFrame, and perform the groupBy using pandas.
B.Use spark.read.csv() to load the file, then call .cache() to cache the DataFrame on the client, and perform the groupBy on the cached data.
C.Use spark.read.csv() to load the file, then call .collect() to bring the data to the client, and perform the groupBy using pandas on the client.
D.Use spark.read.csv() to load the file, then call .groupBy().agg() on the DataFrame before any action that returns data to the client.
AnswerD

Performing the groupBy and aggregation on the remote DataFrame allows the server to process the data in a distributed manner. Only the aggregated results are transferred to the client when an action like show() or collect() is called. This minimizes data transfer because the heavy lifting is done server-side, and the client receives a small summary.

Why this answer

In Spark Connect, the client sends operations to the server for execution. To minimize data transfer, transformations like groupBy and aggregation should be performed on the server-side DataFrame. Only the final aggregated results are returned to the client.

Collecting raw data or using toPandas() transfers the entire dataset, which is inefficient. Caching on the server can help with repeated queries but does not reduce the initial data transfer for aggregation.

Exam trap

The trap here is thinking that caching or converting to pandas will reduce network traffic, when actually performing the aggregation remotely is what minimizes data transfer.

19
MCQmedium

A data engineer has a PySpark DataFrame `events` with columns `event_ts` (TimestampType) and `user_id`. They must produce a new DataFrame where each row shows the event and the timestamp of that same user's previous event, ordered by `event_ts` within each `user_id`. Which code snippet correctly accomplishes this?

A.events.withColumn("prev_ts", lag("event_ts").over(Window.partitionBy("user_id").orderBy("event_ts")))
B.events.withColumn("prev_ts", lead("event_ts").over(Window.orderBy("event_ts")))
C.events.groupBy("user_id").agg(max("event_ts").alias("prev_ts"))
D.events.orderBy("event_ts").withColumn("prev_ts", first("event_ts"))
AnswerA

`lag` is an analytic window function that returns the value from the preceding row within the window frame. Partitioning by `user_id` and ordering by `event_ts` makes the previous row the same user's chronologically earlier event, exactly the required semantics, and `lag` returns null for the first event of each user without dropping the row.

Why this answer

A window function with `partitionBy("user_id").orderBy("event_ts")` defines a frame scoped to each user in chronological order, and `lag` reads the value one row back inside that frame. That yields the same user's prior event timestamp on every row, returning null only for each user's earliest event, which matches the requested output exactly.

Exam trap

The trap here is assuming that `orderBy` on a DataFrame establishes ordering for analytic functions, when ordering must instead be declared inside the `Window` specification.

20
MCQmedium

You are querying a large Delta table partitioned by 'event_date'. You need to calculate the daily count of unique users, but the query is running slowly due to data skew on high-traffic dates. Which SQL approach effectively mitigates this skew during the aggregation?

A.Increase the 'spark.sql.shuffle.partitions' configuration to a significantly higher number.
B.Use the 'DISTINCT' keyword on all columns in the SELECT statement.
C.Add a new column with a random integer suffix to the grouping key, aggregate by the salted key, then aggregate again to remove the suffix.
D.Convert the table to a broadcast join using a dummy table.
AnswerC

Salting distributes the skewed data across multiple tasks by splitting the hot key into multiple sub-keys. This allows Spark to process the aggregation in parallel across different executors. A second aggregation stage is then required to sum the sub-totals, effectively removing the salt and providing the correct final count.

Why this answer

Salting the grouping key by appending a random integer suffix distributes the skewed keys across multiple partitions. By creating a temporary column that combines the original key with a random value, you ensure that the aggregation logic is parallelized across the cluster. This technique is essential in Spark SQL when a specific key value results in a task significantly larger than others, preventing straggler tasks from bottlenecking the entire job.

Exam trap

Examinees often forget the second aggregation step when implementing salting, leaving the random suffix attached to the final output data.

21
MCQhard

A developer is working with a Pandas API on Spark DataFrame `psdf` that has a default index. They call `psdf.sort_values('amount')` and then attempt to use `.loc` with an integer label to retrieve a specific row. They find that the integer label does not correspond to the row position they expect. What is the most likely explanation?

A.The default index in the Pandas API on Spark is a sequence index that is not guaranteed to match row order after operations like `sort_values`.
B.The `.loc` indexer in the Pandas API on Spark always uses positional indexing, so integer labels are treated as row positions.
C.The default index is a distributed index that is only valid on the driver, so `.loc` cannot use it on executors.
D.`sort_values` in the Pandas API on Spark resets the index by default, so integer labels always match the new sorted positions.
AnswerA

The default index is a synthetic sequence that is assigned per partition and then combined. After a shuffle-inducing operation like `sort_values`, the index values are not renumbered to reflect the new row order. Therefore, using an integer label with `.loc` does not reliably retrieve the row at that position. This is a key difference from local pandas, where `sort_values` preserves the original index labels.

Why this answer

The default index in the Pandas API on Spark is a synthetic sequence that is not renumbered after operations like `sort_values`. As a result, integer labels do not reliably map to row positions. To access rows by position, use `.iloc`.

To make labels meaningful, explicitly set or reset the index before relying on label-based access.

Exam trap

The trap here is assuming that the default integer index behaves like a positional index and stays aligned with row order after sorting.

22
MCQeasy

Which term describes the unit of work that is dispatched by the Driver to a specific Executor?

A.Job
B.Stage
C.Task
D.Executor
AnswerC

A task is a single execution unit that runs on one partition of data. It is the final level of granularity in Spark's execution model. The Driver sends these tasks to executors to perform the actual transformations defined in the user's Spark application code on distributed data partitions.

Why this answer

A Task is the smallest unit of execution in Spark. The Driver takes a stage, splits it into multiple tasks based on the partitions of the data, and schedules them for parallel processing on executors. Knowing this is critical for performance tuning; if a job has too many tasks, the overhead of scheduling becomes significant, while too few tasks fail to leverage the available cluster parallelism.

Exam trap

Candidates frequently confuse 'Task' with 'Job' or 'Stage'. They often think a job is the smallest unit of execution, failing to realize that tasks are the granular units running on individual partitions.

23
MCQmedium

Which of the following describes the behavior of a Delta table when a 'DELETE' operation is performed?

A.It deletes the entire table and recreates it without the target rows.
B.It physically removes the data from all files in a synchronous manner.
C.It identifies affected files, rewrites them excluding the target rows, and updates the transaction log.
D.It only marks the rows as deleted without affecting the underlying files.
AnswerC

Delta Lake uses a metadata-driven approach where it only processes the files containing the records to be deleted. By writing new files and updating the transaction log, it ensures ACID compliance and enables time travel, representing the efficient, performant way Delta Lake handles record-level deletions.

Why this answer

Delta Lake implements deletes by rewriting only the files containing the data to be removed, while maintaining a record of the change in the transaction log. This is much more efficient than traditional systems that might perform full table scans or require complex locking. Understanding this 'copy-on-write' or 'merge-on-read' approach is vital for Databricks developers to predict performance and costs when executing large-scale DML operations.

Exam trap

Candidates often assume DELETE drops the entire table or runs an instant metadata-only operation, forgetting that Delta Lake must physically rewrite the specific data files containing target rows.

24
MCQhard

A developer is writing a Spark Connect application that uses a Python UDF to transform a column. The UDF depends on a third-party Python library that is installed on the developer's laptop but not on the Databricks cluster. The developer runs the code and receives an error indicating the module cannot be found. What is the most appropriate fix?

A.Install the third-party library on the Databricks cluster or include it as a cluster library so it is available to the Python workers that execute the UDF.
B.Wrap the UDF body in a try/except ImportError block so the library is downloaded automatically at runtime by Spark Connect.
C.Convert the UDF to a Pandas UDF, because Pandas UDFs execute on the client and can access client-installed libraries.
D.Set the PYTHONPATH environment variable on the client laptop to include the library, because Spark Connect forwards client environment variables to the server.
AnswerA

In Spark Connect, Python UDFs are serialized and executed on the server in Python worker processes. Any imported modules must be present in that server environment. Installing the library on the cluster, or attaching it as a cluster library, ensures the worker processes can import it. Installing it only on the client laptop does not help because the UDF does not run locally.

Why this answer

Because Spark Connect ships Python UDFs to the server for execution, any imported third-party modules must be installed in the server's Python environment. The client laptop's environment is irrelevant to UDF execution. The correct fix is to provision the library on the Databricks cluster, either through cluster libraries or an init script, so the Python workers can import it when the UDF runs.

Exam trap

The trap here is assuming that because the UDF is defined in client code, its imports are resolved on the client, when in fact the UDF runs on the server.

25
MCQmedium

A Spark application on Databricks uses a broadcast variable to distribute a large lookup table to all executors. The developer notices that the broadcast variable is not being used efficiently, as executors are still fetching the data multiple times. Which component is responsible for ensuring that the broadcast data is distributed only once per executor and cached there?

A.The Driver's Block Manager
B.The DAG Scheduler
C.The Executors' Block Managers
D.The Cluster Manager
AnswerC

Each executor has a Block Manager that manages cached data, including broadcast variables. When a broadcast variable is created, the driver divides it into blocks and informs executors. Executors fetch blocks from the driver or from other executors that already have them, and the Block Manager caches the assembled broadcast data on that executor. This ensures each executor fetches the data once and reuses it, reducing network overhead.

Why this answer

Broadcast variables are distributed using a BitTorrent-like protocol where the driver divides the data into blocks. Executors use their Block Managers to fetch these blocks from the driver or from other executors, and then cache the assembled broadcast data locally. This ensures that each executor retrieves the broadcast data only once, even if multiple tasks on that executor need it.

The Block Manager is the key component for caching and serving broadcast blocks on executors.

Exam trap

The trap here is attributing broadcast distribution to the driver's Block Manager or the DAG Scheduler, when the executors' Block Managers are responsible for fetching and caching the broadcast data locally.

26
MCQmedium

When a Spark application is running in Databricks, what determines the number of tasks that can run in parallel?

A.The total number of nodes in the cluster.
B.The number of CPU cores available across the executors.
C.The amount of driver memory available.
D.The size of the source data files.
AnswerB

Spark parallelism is directly tied to the number of available cores. Each core can process one task simultaneously. By increasing the number of cores per executor or the number of executors in the cluster, you directly increase the application's ability to process data in parallel, reducing runtime.

Why this answer

The number of tasks that run in parallel is determined by the number of slots available on the executors. Each executor provides a certain number of CPU cores, and each core can typically handle one task at a time. This relationship between CPU cores, executor memory, and task parallelism is vital for optimizing Spark jobs, as it directly influences how efficiently a cluster processes large-scale data sets and transformations.

Exam trap

Candidates often confuse 'number of executors' with 'parallelism.' While more executors help, the actual number of concurrent tasks is strictly limited by the total count of available CPU cores.

27
MCQhard

In the context of Databricks, what occurs when a Spark stage is described as 'Shuffle-heavy'?

A.All data is processed locally on each executor without network transfers.
B.The Driver is performing all the heavy data transformations.
C.Data is being exchanged between executors to satisfy a transformation requirement.
D.The cluster manager is automatically scaling the number of nodes.
AnswerC

Shuffle-heavy stages imply that the required data for a transformation, such as a join or group-by, is scattered across executors. Spark must redistribute this data across the network so that specific keys are aggregated on specific executors, which is a resource-intensive operation known as a shuffle.

Why this answer

A shuffle-heavy stage involves moving large amounts of data across the network between executors. This happens during operations like joins or groupings where data needs to be repartitioned based on keys. This architectural bottleneck is the most common cause of performance degradation in distributed Spark applications, as it forces heavy network I/O and disk serialization, highlighting the importance of efficient data partitioning strategies.

Exam trap

Candidates often confuse shuffle-heavy stages with memory issues caused by local data skew or driver out-of-memory errors, failing to recognize that shuffles specifically involve data exchange across the network between executors.

28
MCQmedium

A developer needs to add a column `full_name` to DataFrame `people` by concatenating `first_name` and `last_name` with a single space, and must handle rows where `last_name` is null by producing just the first name. Which expression is correct?

A.people.withColumn("full_name", col("first_name") + lit(" ") + col("last_name"))
B.people.withColumn("full_name", when(col("last_name").isNull(), col("first_name")).otherwise(col("first_name")))
C.people.withColumn("full_name", concat_ws(" ", col("first_name"), col("last_name")))
D.people.withColumn("full_name", concat(col("first_name"), lit(" "), col("last_name")))
AnswerC

`concat_ws` joins its arguments with the given separator and, importantly, skips null arguments rather than returning null. So a null `last_name` yields just the first name with no trailing space, which is exactly the null-handling behavior required. It also avoids the awkward empty-string artifacts that string addition can introduce.

Why this answer

`concat_ws` inserts the separator between non-null arguments and treats nulls as absent, so a null last name produces a clean first-name-only value with no dangling space. That matches the requirement for both the populated and the null case in one expression, without needing any explicit conditional branching.

Exam trap

The trap here is assuming `concat` and `concat_ws` behave identically with nulls, when only `concat_ws` skips them.

29
Multi-Selectmedium

A developer is troubleshooting a Spark Connect client that intermittently fails with connection errors to a Databricks cluster. Which two configuration practices help ensure stable connectivity? (Choose two.)

Select 2 answers
A.Set `spark.sql.adaptive.enabled` to false to stabilize the connection.
B.Increase `spark.sql.shuffle.partitions` to 2000 to reduce the number of RPC calls.
C.Set `spark.remote.connect.grpc.maxInboundMessageSize` to a value large enough for the plans being sent.
D.Disable TLS between the client and the cluster to reduce handshake overhead.
E.Configure client-side retry and timeout settings for the gRPC channel used by Spark Connect.
AnswersC, E

Large logical plans can exceed the default gRPC message size limit, causing connection or serialization errors. Raising the maximum inbound message size on both client and server allows bigger plans to be transmitted. This is a documented Spark Connect configuration that addresses failures when plans grow beyond defaults, making it a valid practice for stable connectivity.

Why this answer

Stable Spark Connect connectivity depends on transport-level configuration. Raising the maximum gRPC message size prevents failures when large logical plans are serialized, and configuring retry and timeout policies on the gRPC channel lets the client recover from transient network interruptions. Shuffle partitioning, TLS disabling, and adaptive execution settings do not address connection errors and may harm security or performance.

Exam trap

The trap here is conflating server-side execution tuning settings such as shuffle partitions or adaptive execution with client-server transport configuration that actually governs Spark Connect connection stability.

30
Multi-Selectmedium

A developer is building a Structured Streaming job that reads from a Delta table as a stream and writes to another Delta table. The job must support exactly-once processing and allow the output to be updated incrementally. Which two options are required to achieve exactly-once semantics? (Choose two.)

Select 2 answers
A.Set the output mode to `complete`.
B.Ensure the sink is idempotent or transactional, such as Delta Lake.
C.Configure a checkpoint location for the query.
D.Use the `foreachBatch` sink to write to the Delta table.
E.Use `trigger(processingTime='0 seconds')` for continuous processing.
AnswersB, C

Exactly-once semantics require that the sink can handle replays without duplicating data. Delta Lake provides transactional writes and idempotent merges, which allow the streaming query to retry a micro-batch without creating duplicates. In this scenario, writing to a Delta table as the sink ensures that even if a batch is reprocessed after failure, the result remains consistent, thus satisfying exactly-once.

Why this answer

Exactly-once in Structured Streaming relies on two pillars: a reliable checkpoint to track progress and an idempotent or transactional sink to handle replays. A checkpoint location stores offsets and state, enabling recovery without data loss. A sink like Delta Lake ensures that re-executed batches do not duplicate output.

Together, they provide end-to-end exactly-once. Other options affect output mode, custom sink logic, or trigger frequency, none of which guarantee exactly-once.

Exam trap

The trap here is thinking that a specific output mode or trigger setting alone can guarantee exactly-once, when checkpointing and sink idempotency are the real requirements.

31
MCQmedium

A data engineering team is migrating a client application to use Spark Connect. The application connects to a remote Databricks cluster. Which architectural component processes the client's DataFrame operations and executes them against the Spark cluster?

A.The local SparkSession running within the client application process
B.The Spark Connect server running on the remote cluster driver node
C.The Databricks workspace REST API endpoint used for cluster management
D.The distributed executor nodes running inside the worker instances
AnswerB

The Spark Connect server operates directly on the driver node, receiving gRPC requests from the remote client, compiling logical plans into physical execution plans, and managing the resulting DataFrame actions across the cluster workers efficiently.

Why this answer

Spark Connect introduces a decoupled client-server architecture where the client application sends dataframe plan representations via gRPC to a server component running on the driver node. This server translates the plan and executes it, which significantly reduces local memory overhead on the client machine and isolates client dependencies from the cluster environment.

Exam trap

Candidates often mistakenly believe the client application executes the logic locally. They fail to identify the driver node's server component as the actual engine that plans and runs the code.

32
MCQeasy

What is the purpose of the 'ANALYZE TABLE' command in Databricks?

A.To remove unused files and clean up storage.
B.To update the table schema after adding a column.
C.To generate statistics used by the optimizer for query planning.
D.To verify the integrity of the Delta log.
AnswerC

ANALYZE TABLE computes statistics like count, min, max, and null counts for columns. The cost-based optimizer uses this data to decide the best join strategy. This is a best practice in Databricks for any table that is frequently used in complex SQL queries to ensure optimal execution paths.

Why this answer

The ANALYZE TABLE command collects table statistics, such as row counts and column distributions. This information is crucial for the Spark Catalyst optimizer to make informed decisions about join strategies, such as when to broadcast a table or how to order joins. Without accurate statistics, the optimizer might choose inefficient execution plans, leading to degraded performance in complex multi-join queries.

Exam trap

Many test-takers think ANALYZE TABLE actually cleans up storage, optimizes file sizes, or runs data quality validation checks on the table.

33
MCQmedium

A developer is migrating a legacy PySpark application to use Spark Connect. Which architectural change is fundamental to how Spark Connect executes operations compared to traditional Spark sessions?

A.The driver process is eliminated entirely from the Spark cluster.
B.Spark Connect executes all transformations locally on the client machine to reduce latency.
C.Spark Connect serializes logical plans using Protocol Buffers to communicate with the remote server.
D.The client must have the full Hadoop distribution installed to handle data shuffling.
AnswerC

Spark Connect utilizes the Protocol Buffers (protobuf) format to encode logical plans. This binary serialization ensures efficient communication over gRPC, allowing clients to transmit complex Spark SQL plans to the server in a cross-language, platform-independent manner, significantly improving interoperability between different environments and the Databricks remote cluster.

Why this answer

Spark Connect decouples the client-side session from the server-side Spark cluster using a client-server protocol based on gRPC. Unlike traditional Spark where the entire driver runs on the cluster, Spark Connect allows a local or remote client to submit plans as unresolved logical plans. This separation allows lightweight clients, such as IDEs or local scripts, to interact with Databricks clusters without needing the full Spark driver dependencies locally.

Exam trap

Candidates often confuse Spark Connect with traditional client-server setups, incorrectly assuming that the entire driver or heavy Spark execution dependencies still run locally on the client machine.

34
MCQeasy

A data engineer has a DataFrame `df` with columns `order_id`, `customer_id`, and `order_total`. They need to create a new DataFrame containing only the rows where `order_total` is greater than 100 and only the columns `order_id` and `order_total`. Which combination of DataFrame operations accomplishes this most efficiently?

A.df.where("order_total > 100").groupBy("order_id", "order_total").count()
B.df.select("order_id", "order_total").where(df.customer_id > 100)
C.df.rdd.filter(lambda r: r.order_total > 100).map(lambda r: (r.order_id, r.order_total)).toDF()
D.df.filter(df.order_total > 100).select("order_id", "order_total")
AnswerD

filter followed by select is the idiomatic, lazy transformation chain. Catalyst can push the filter below the projection and even down to the data source when the format supports predicate pushdown, minimizing I/O. Both operations are narrow transformations, so no shuffle occurs, and the resulting DataFrame contains exactly the requested rows and columns.

Why this answer

Chaining filter (or where) with select on the DataFrame API keeps both transformations narrow, enables Catalyst to push the predicate down to the source, and prunes unneeded columns. The alternative using an aggregation introduces a shuffle, the RDD variant abandons Catalyst optimizations, and the remaining option filters on the wrong column and references a dropped field.

Exam trap

The trap here is mixing up filter with select ordering or referencing a column after it has been projected away, which produces an AnalysisException rather than the intended subset.

35
MCQmedium

Based on the exhibit, what is the most likely reason for this error in a Databricks notebook?

A.The Spark cluster is configured with insufficient executor memory.
B.The DataFrame contains too many columns to be processed.
C.The user is attempting to pull a large distributed dataset into the driver memory.
D.The DataFrame has not been properly cached before calling to_pandas.
AnswerC

The 'to_pandas' operation is a collector that moves data from all Spark executors to the driver. This is intended for small datasets only. When the dataset is too large to fit in the driver's memory, the application will crash, necessitating a different approach like limiting output.

Why this answer

The 'to_pandas' method collects the entire distributed DataFrame into the driver node's memory. When the DataFrame size exceeds the available memory of the driver, the job fails. This is a common pitfall when transitioning from local Pandas to Pandas-on-Spark, as users might attempt to pull entire datasets into a single machine instead of performing operations within the Spark cluster's distributed environment using the provided API.

Exam trap

Candidates migrating from local Pandas often use 'to_pandas()' indiscriminately on large distributed datasets, forgetting that it gathers all data onto the driver node.

36
Multi-Selectmedium

You are developing a data pipeline using Pandas API on Spark. You need to perform operations that are efficient and avoid unnecessary data shuffling. Which two of the following operations are considered expensive because they may trigger a full shuffle or collect data to the driver? (Choose two.)

Select 2 answers
A.`psdf.head(5)`
B.`psdf.filter(psdf['value'] > 100)`
C.`psdf['new_column'] = psdf['value'] * 2`
D.`psdf.groupby('column').agg({'value': 'sum'})`
E.`psdf.sort_values(by='column')`
AnswersD, E

This is correct. `groupby` followed by an aggregation typically requires shuffling data so that all rows with the same key are on the same partition. This shuffle can be expensive, especially if the cardinality of the grouping column is high. However, it is a common operation and can be optimized with proper partitioning.

Why this answer

Sorting and grouping aggregations are expensive in Pandas API on Spark because they require shuffling data across the cluster. Sorting needs a global order, and grouping needs to co-locate rows with the same key. In contrast, element-wise operations and filters are narrow and do not shuffle data, making them efficient.

Exam trap

The trap here is assuming that all pandas-like operations are equally efficient, but operations that require data shuffling are significantly more expensive.

37
MCQmedium

A data engineer is tuning a Spark Structured Streaming job on Databricks that reads from a Kafka topic with 12 partitions. The job uses a static allocation of executors, each with 4 cores. The engineer notices that only 4 tasks are running concurrently, even though there are 12 Kafka partitions and 3 executors are available. Which Spark configuration is most likely causing this limitation?

A.spark.executor.cores is set to 4, limiting each executor to 4 concurrent tasks.
B.spark.default.parallelism is set to 4, overriding the number of partitions from Kafka.
C.spark.sql.shuffle.partitions is set to 4, limiting the number of tasks for shuffle operations.
D.spark.executor.instances is set to 1, so only one executor with 4 cores is available.
AnswerD

If spark.executor.instances is set to 1, only a single executor with 4 cores is launched, allowing at most 4 concurrent tasks. Despite having 3 executors' worth of resources potentially available, the static allocation configuration limits the job to one executor. This directly explains the observed concurrency of 4 tasks, matching the executor's core count.

Why this answer

The concurrency of tasks in Spark is determined by the total number of cores available across all executors. If only one executor with 4 cores is allocated, only 4 tasks can run in parallel, regardless of the number of input partitions. The configuration spark.executor.instances controls how many executors are requested, and setting it to 1 restricts the job to a single executor's worth of cores.

Exam trap

The trap here is assuming that the number of input partitions directly dictates concurrency, ignoring the executor allocation configuration that caps the available cores.

38
MCQmedium

A data engineer is using Pandas API on Spark and needs to perform a join between two Pandas-on-Spark DataFrames `psdf1` and `psdf2` on a common column `id`. They write the following code: ```python result = psdf1.merge(psdf2, on='id', how='inner') ``` Which statement best describes the execution and potential issue with this operation?

A.The merge is performed locally on the driver after collecting both DataFrames, which can cause out-of-memory errors.
B.The merge automatically broadcasts the smaller DataFrame to all nodes, avoiding a shuffle.
C.The merge is executed as a distributed sort-merge join, which may require a shuffle of both DataFrames across the network.
D.The merge requires that both DataFrames have the same number of partitions, otherwise it fails with an error.
AnswerC

Pandas API on Spark translates merge operations into Spark joins. For an inner join on a column, Spark typically uses a sort-merge join, which shuffles both DataFrames to co-locate matching keys. This shuffle can be expensive but is necessary for distributed execution. The operation is generally scalable but may be slow if data is skewed.

Why this answer

The merge operation in Pandas API on Spark translates to a Spark join, which typically involves shuffling data to co-locate matching keys. This distributed execution allows handling large datasets but can introduce network overhead. The actual join strategy depends on data size and Spark configuration, but a shuffle is common.

Exam trap

The trap here is assuming that merge in Pandas API on Spark behaves like pandas and operates in-memory on a single node, when it actually triggers a distributed Spark join.

39
MCQmedium

A Databricks notebook job calls a PySpark UDF built on a Python function that performs string parsing. The job completes successfully on a small sample, but on the full production dataset it fails with a PythonException and the executor logs show high garbage collection time. Which change is the most appropriate first step to make the job reliable without changing business logic?

A.Set spark.sql.execution.arrow.pyspark.enabled to true so the UDF uses Arrow for every row it processes.
B.Mark the UDF with the deterministic flag and register it with spark.udf.register so Spark can cache its results automatically.
C.Replace the Python UDF with a Spark SQL built-in function such as regexp_extract or split, which runs inside the JVM and avoids Python serialization and per-row interpreter overhead.
D.Increase spark.executor.memory and spark.executor.cores so each executor has more headroom to run the Python workers.
AnswerC

Built-in Spark SQL functions execute in the JVM with code generation, so they avoid Python worker startup, serialization, and interpreter overhead per row. For string parsing, regexp_extract, split, or transform are usually equivalent to the Python logic. This directly reduces executor memory pressure and GC time while preserving the same results. It is the least invasive change and the standard tuning step for Python UDF hotspots.

Why this answer

A scalar Python UDF forces each row through a Python worker, incurring serialization, interpreter startup, and per-row overhead that shows up as GC pressure at scale. Rewriting the logic with Spark SQL built-in functions keeps execution in the JVM with whole-stage code generation, eliminating that overhead and typically resolving both the reliability and performance symptoms. It preserves the business logic while removing the root cause rather than masking it with more resources.

Exam trap

The trap here is assuming that more executor memory or cores will fix a Python UDF hotspot, when the real cost is the per-row Python worker and serialization overhead.

40
Multi-Selectmedium

A developer is using Pandas API on Spark and needs to perform operations that involve multiple DataFrames. They encounter a 'compute.ops_on_diff_frames' error. Which two actions can resolve this error? (Choose two.)

Select 2 answers
A.Set the configuration 'compute.ops_on_diff_frames' to True using spark.conf.set.
B.Convert both DataFrames to PySpark DataFrames and perform the operation using Spark SQL functions.
C.Ensure both DataFrames are derived from the same base DataFrame or have the same index.
D.Use the 'psdf1.merge(psdf2)' method instead of direct comparison.
E.Call 'psdf1.to_pandas()' and 'psdf2.to_pandas()' to perform the operation in pandas.
AnswersA, B

Setting the configuration 'compute.ops_on_diff_frames' to True allows operations between different DataFrames by enabling the computation of operations on different frames. This is the intended way to resolve the error when the operation is necessary, though it may have performance implications because it can trigger a shuffle or collect data. It is a valid solution when the operation is required.

Why this answer

The 'compute.ops_on_diff_frames' error occurs when operations involve columns from different Pandas API on Spark DataFrames. The two valid solutions are to enable the configuration 'compute.ops_on_diff_frames' to True, which allows such operations, or to convert the DataFrames to PySpark DataFrames and use Spark SQL functions, which bypasses the Pandas API on Spark restriction. The other options are either not general solutions or not scalable.

Exam trap

The trap here is assuming that simply merging or aligning indexes will resolve the error, but the error is specifically about operations on different frames and requires either enabling the configuration or using native Spark operations.

41
MCQmedium

You are migrating a legacy Pandas codebase to Databricks using the Pandas API on Spark. You have a DataFrame 'pdf' and need to calculate the average of a column 'revenue' while ensuring the computation remains distributed across the cluster. Which command is the idiomatic approach to achieve this?

A.pdf.to_pandas().mean()
B.pdf.apply(lambda x: x.mean())
C.pdf['revenue'].mean()
D.pdf.rdd.map(lambda x: x.revenue).mean()
AnswerC

The Pandas API on Spark implements the standard Pandas Series interface. Calling mean() directly on the column triggers a distributed Spark aggregation. This executes the calculation in parallel across worker nodes, which is the most efficient and idiomatic way to handle distributed numeric data processing.

Why this answer

The Pandas API on Spark maintains a familiar syntax while pushing execution to the Spark engine. By calling .mean() on the series, the API translates the operation into a Spark aggregation plan. This is critical for scalability, as it avoids collecting the entire dataset to the driver node, which would cause an OutOfMemory error on large datasets exceeding driver memory capacity.

Exam trap

Candidates often try to convert the DataFrame to a Pandas object using toPandas() before calculating the mean. This pulls all data to the driver, leading to immediate OOM errors on large datasets.

42
MCQmedium

A Spark job is experiencing data skew during a join operation on a key column. Which strategy is most effective for mitigating this issue without changing the business logic?

A.Increase the spark.sql.shuffle.partitions configuration value significantly.
B.Broadcast the larger table to all executor nodes.
C.Add a random prefix to the join key of the skewed table and replicate the join key of the other table.
D.Cache the skewed table in memory before performing the join.
AnswerC

Salting distributes the skewed keys across different partitions by creating a composite key. By replicating the join key in the smaller table, you ensure that the original join condition is still satisfied while allowing Spark to process the previously bottlenecked key across several parallel tasks simultaneously.

Why this answer

Salting the join key by appending a random integer helps distribute the skewed keys across multiple partitions. This prevents a single executor from handling the bulk of the data, which is the primary cause of long-running tasks in skewed joins. Understanding how to repartition data based on a salted key is critical for developers tasked with optimizing performance in distributed systems where key distribution is inherently uneven across the cluster nodes.

Exam trap

Candidates often forget that when salting a join key on one table, the matching table must also be expanded or replicated to join all the salted variants.

43
MCQeasy

Which library import is required to enable the Pandas API on Spark within a Databricks notebook?

A.import pandas as pd
B.import pyspark.pandas as ps
C.import spark.pandas as ps
D.import databricks.pandas as pd
AnswerB

This is the correct namespace for the Pandas API on Spark. By aliasing it as 'ps', developers follow the standard convention to access the distributed implementation of Pandas, ensuring that all DataFrame operations are automatically compiled into efficient Spark plans for distributed execution.

Why this answer

To leverage the Pandas API on Spark, you must import the specific pandas-on-spark namespace. This bridges the gap between local Pandas syntax and Spark's distributed execution engine. Properly importing this library ensures that subsequent calls to 'ps' objects are routed to the Spark optimizer instead of the standard local Pandas library installed on the driver node.

Exam trap

Candidates often mistakenly import standard local pandas or pyspark.sql modules, confusing standard dataframe operations with the specialized namespace required to enable the Pandas API on Spark.

44
MCQeasy

A developer has a DataFrame `df` with columns `id` and `score`, and several rows contain null values in `score`. They want a new DataFrame in which rows with a null `score` are removed, keeping only rows where `score` is present. Which single call achieves this?

A.df.na.fill(0, subset=["score"])
B.df.filter(col("score").isNull())
C.df.drop("score")
D.df.na.drop(subset=["score"])
AnswerD

na.drop with the subset argument removes rows where any of the listed columns contain null, so restricting it to score drops exactly the rows missing a score while leaving other columns untouched. It returns a new DataFrame and does not mutate the original, matching the requirement precisely.

Why this answer

Dropping rows based on nulls in a specific column is done with na.drop and the subset argument, which limits the null check to the named columns. Filling values keeps the rows, filtering for nulls keeps the wrong rows, and dropping a column removes the field entirely, so none of those match the stated goal of discarding incomplete rows.

Exam trap

The trap here is mixing up DataFrame.drop, which removes columns, with na.drop, which removes rows, because both share the word drop and are easy to confuse under time pressure.

45
MCQmedium

In the context of the Spark Driver, which component is specifically responsible for tracking the location of cached data blocks across the executors?

A.TaskScheduler
B.DAGScheduler
C.BlockManagerMaster
D.SparkEnv
AnswerC

The BlockManagerMaster acts as the central authority for metadata regarding the location of all blocks within the cluster. It communicates with individual BlockManagers on each executor, ensuring the driver knows exactly where RDD partitions are stored in memory or on disk for efficient query planning.

Why this answer

The BlockManagerMaster is a component within the Spark Driver that maintains a registry of where every block of data resides within the cluster. It receives status updates from the BlockManager on each executor whenever blocks are stored or evicted. Understanding this architecture is crucial for troubleshooting memory pressure and cache-related performance bottlenecks in large-scale distributed applications where data locality significantly impacts shuffle and join operations.

Exam trap

Candidates frequently guess 'DAG Scheduler' or 'Task Scheduler' because they are familiar names, failing to realize the BlockManagerMaster is the specific registry for data location.

46
MCQmedium

Which THREE factors should a developer consider when choosing a partition count for a shuffle operation?

A.The total size of the data being shuffled.
B.The total number of available cores in the cluster.
C.The memory limit of the driver node.
D.The specific task being performed (e.g., aggregation vs. join).
E.The number of rows in the source file header.
AnswerA, B, D

Data size directly influences how much data each task must handle. Larger datasets require more partitions to keep task sizes manageable and prevent OOM errors, whereas small datasets can be processed with fewer partitions to reduce the overhead associated with launching and managing tasks in the Spark cluster.

Why this answer

Selecting the right partition count is a balancing act between parallelism and overhead. Too few partitions lead to underutilization of the cluster, while too many partitions create excessive overhead for the scheduler. Developers must balance the data volume, the available cluster resources (cores), and the specific requirements of the operation to ensure optimal performance and avoid common performance pitfalls like task scheduling bottlenecks or executor memory issues.

Exam trap

Candidates often pick static rules of thumb like 'always use 200 partitions' instead of evaluating data volume, cluster cores, and operation types.

47
MCQeasy

A developer is writing a Structured Streaming query that reads from a JSON file source and writes to the console for debugging. The query uses `outputMode("append")`. Which statement describes the output behavior?

A.No output is produced until the query is stopped.
B.Only new rows added since the last micro-batch are written to the console.
C.Only rows that have been updated since the last micro-batch are written to the console.
D.The entire result table is rewritten to the console after every micro-batch.
AnswerB

In append mode, only new rows that have been added to the result table since the last trigger are output. For a non-aggregated streaming query, this means each new record is emitted once. This matches the typical debugging use case where you want to see incoming data as it arrives. Therefore this statement correctly describes append mode behavior.

Why this answer

Append mode in Structured Streaming outputs only new rows that are added to the result table since the last micro-batch. For a simple file source without aggregations, each incoming record is emitted once. This is ideal for debugging because you see data as it arrives.

Complete mode rewrites the whole table, and update mode emits only updated rows, neither of which matches the described behavior.

Exam trap

The trap here is mixing up append mode with complete or update mode, especially when aggregations are not involved.

48
MCQeasy

A developer has a DataFrame `df` and wants to remove duplicate rows considering only the columns `user_id` and `event_type`, keeping the first occurrence according to the current row order. Which DataFrame operation achieves this?

A.df.distinct()
B.df.groupBy('user_id', 'event_type').agg(first('*'))
C.df.na.drop(subset=['user_id', 'event_type'])
D.df.dropDuplicates(['user_id', 'event_type'])
AnswerD

`dropDuplicates` accepts a subset of columns and removes rows that share the same values in those columns, retaining one arbitrary row per group. In practice, when no shuffle-induced reordering has occurred, the first occurrence in the current partition order is kept, which matches the scenario's intent. It is the idiomatic DataFrame API method for this requirement.

Why this answer

`dropDuplicates` with a column subset is the direct DataFrame API for removing rows that repeat on those columns while keeping the rest of each row intact. It avoids the over-aggressive behavior of `distinct()` and the column-collapsing behavior of `groupBy().agg()`. The null-dropping method targets missing values, not duplicates, so it does not meet the requirement.

Exam trap

The trap here is confusing `dropDuplicates` with `distinct`, when only `dropDuplicates` lets you scope deduplication to a subset of columns.

49
MCQmedium

A data engineer must produce a report that shows each department's total salary, but only for departments where the total salary exceeds 500,000. The source DataFrame is created from a Delta table with columns department and salary. Which Spark SQL query correctly returns the desired result?

A.SELECT department, SUM(salary) AS total_salary FROM employees GROUP BY department WHERE total_salary > 500000
B.SELECT department, SUM(salary) AS total_salary FROM employees GROUP BY department WHERE SUM(salary) > 500000
C.SELECT department, SUM(salary) AS total_salary FROM employees GROUP BY department HAVING SUM(salary) > 500000
D.SELECT department, SUM(salary) AS total_salary FROM employees WHERE SUM(salary) > 500000 GROUP BY department
AnswerC

This query correctly groups rows by department, computes the total salary per group, and then applies HAVING to filter groups whose aggregate exceeds 500,000. In Spark SQL, HAVING is the proper clause for aggregate-based filtering, and it is evaluated after GROUP BY, so it works as required.

Why this answer

Filtering on an aggregate result requires the HAVING clause, which executes after GROUP BY. The query that groups by department, sums salary, and then applies HAVING with the aggregate condition returns only departments whose total salary exceeds 500,000, exactly matching the requirement.

Exam trap

The trap here is assuming that WHERE can filter aggregated results or that a SELECT alias can be used in WHERE, when in Spark SQL only HAVING can filter on aggregates after grouping.

50
MCQmedium

You have a Structured Streaming job that reads from a Kafka topic and writes to a Delta table. You need to ensure that the job processes each record exactly once, even after failures. Which of the following should you configure?

A.Configure the Kafka source with `startingOffsets` set to `earliest`.
B.Enable idempotent writes by setting the Delta table property `delta.enableChangeDataFeed` to true.
C.Use `foreachBatch` to manually deduplicate records based on a unique key.
D.Set the `checkpointLocation` option to a reliable storage location.
AnswerD

The checkpoint location stores the progress information of the streaming query, including which offsets have been processed. On restart, Spark uses this to resume from where it left off, ensuring each record is processed exactly once. Combined with idempotent sinks like Delta Lake, this provides end-to-end exactly-once guarantees. Therefore, setting a checkpoint location is essential.

Why this answer

Exactly-once processing in Structured Streaming relies on checkpointing to record progress and idempotent sinks to avoid duplicates. The checkpoint location stores offset information, allowing the query to resume without reprocessing. Delta Lake supports idempotent writes when used with checkpoints.

Other options like Change Data Feed or manual deduplication do not provide the necessary fault tolerance.

Exam trap

The trap here is assuming that any Delta table property or deduplication logic automatically ensures exactly-once semantics, when actually checkpointing is the core mechanism.

51
Multi-Selecthard

An analytics engineer is designing a Structured Streaming pipeline that reads from an Apache Kafka topic and writes JSON-formatted output to cloud object storage. The pipeline must maintain exactly-once processing semantics and support automatic recovery from cluster restarts. Which TWO actions are mandatory to achieve these requirements? (Choose 2)

Select 2 answers
A.Configure a valid checkpoint location using the .option("checkpointLocation", path) method.
B.Enable Delta Lake format as the sink to leverage ACID transactions and transactional metadata.
C.Set the output mode of the streaming query to complete mode.
D.Use an idempotent or transactional sink combined with proper source offset management.
E.Increase the driver memory allocation to at least 64GB to store all Kafka offset metadata.
AnswersA, D

A checkpoint location records Kafka offsets and commit metadata durably, letting Structured Streaming resume exactly where it stopped after a restart. Without it, the query cannot recover progress, so exactly-once delivery and automatic restart recovery are impossible.

Why this answer

Achieving end-to-end exactly-once guarantees in Spark Structured Streaming requires idempotent or transactional sinks combined with persistent checkpoint directories. The checkpoint mechanism saves the exact state and offsets, allowing the streaming query to resume seamlessly after an interruption without duplicating data processing.

Exam trap

Candidates often forget that exactly-once semantics requires BOTH a transactional/idempotent sink AND a persistent checkpoint location, selecting only one of these mandatory components.

52
MCQeasy

Which of the following best describes the purpose of a Spark Session in a Databricks environment?

A.It serves as the sole interface for raw RDD manipulation.
B.It is the unified entry point to program Spark with the DataFrame and Dataset APIs.
C.It directly manages the physical allocation of CPU and memory on the cluster.
D.It is required to execute code on the Spark Driver process only.
AnswerB

SparkSession provides a single, unified interface for all Spark functionality, including SQL, DataFrames, and Streaming. By consolidating previous context types into one, it simplifies the initialization process and provides a consistent way for developers to interact with the cluster and manage spark configurations, metadata, and data sources.

Why this answer

The SparkSession is the unified entry point for programming Spark with the Dataset and DataFrame APIs. It replaces the separate contexts used in older versions, such as SQLContext and HiveContext, simplifying development. In Databricks, the session is pre-configured and manages connections to the underlying Spark infrastructure, ensuring that users can focus on data manipulation without manually initializing complex environment settings or handling various specialized contexts for different libraries.

Exam trap

Test-takers often select legacy context types like HiveContext or SQLContext, forgetting that SparkSession is the modern unified entry point for Databricks development.

53
MCQhard

Refer to the exhibit. What is the most likely cause of the repeated ExecutorLostFailure messages in the logs?

A.The driver node is experiencing a network latency issue.
B.The Spark job is attempting to use too many partitions.
C.The executor process reached its memory limit and was killed.
D.The shuffle partition count is set too low for the data.
AnswerC

When a Spark executor consumes more memory than allocated, the underlying container (like YARN or Kubernetes) will kill it, leading to the ExecutorLostFailure log. This often occurs during heavy data processing or shuffles where memory consumption exceeds the configured JVM heap limits or container memory limits.

Why this answer

ExecutorLostFailure indicates that an executor has died, often due to exceeding memory limits or heartbeats failing. When processing large data, the executor's heap memory can be exhausted, leading to a crash. This signifies that the cluster resources are insufficient for the current workload, requiring either more memory per executor or more efficient data processing strategies to prevent the executor from being terminated by the operating system or the cluster manager.

Exam trap

Candidates often mistake 'ExecutorLostFailure' for a network issue, ignoring the fact that it is frequently the result of the OOM killer terminating the executor due to excessive memory usage.

54
MCQmedium

A data engineer has a PySpark DataFrame `readings` with columns `sensor_id` (string) and `celsius` (double). The engineer must produce a new DataFrame where every temperature is converted to Fahrenheit using the formula `celsius * 9/5 + 32`, while keeping both the original `sensor_id` and a column named `fahrenheit`, and must avoid collecting data to the driver. Which DataFrame operation should be used?

A.readings.collect().map(lambda r: (r.sensor_id, r.celsius * 9/5 + 32))
B.readings.rdd.map(lambda r: (r.sensor_id, r.celsius * 9/5 + 32)).toDF(["sensor_id", "fahrenheit"])
C.readings.select("sensor_id", (col("celsius") * 9/5 + 32).alias("fahrenheit"))
D.readings.withColumn("fahrenheit", col("celsius") * 9/5 + 32).drop("celsius")
AnswerC

select() is a narrow transformation that projects existing columns and can also project arbitrary Column expressions with an alias, producing the requested schema without any driver-side collection. The arithmetic on the celsius Column is translated into a Catalyst expression and evaluated distributively on each executor partition, so the resulting DataFrame is lazy and only materializes when an action such as show() or write() is invoked.

Why this answer

The requirement is a column-wise transformation that preserves sensor_id and adds fahrenheit, evaluated across executors. select() with a Column expression and alias is the canonical DataFrame API approach: it is lazy, Catalyst-optimized, and does not move data to the driver. Converting to the RDD API is unnecessary, dropping celsius changes the schema, and collect() pulls everything to the driver, which the scenario forbids.

Exam trap

The trap here is assuming that any transformation which computes a new value must use the RDD map() API, when the DataFrame column API already supports the same arithmetic lazily and with optimizer support.

55
MCQeasy

Which SQL function is used to create a temporary view that persists only for the duration of the current Spark session?

A.CREATE GLOBAL TABLE
B.CREATE TEMPORARY VIEW
C.CREATE PERSISTENT VIEW
D.CREATE SESSION TABLE
AnswerB

This command creates a temporary view that exists only within the current SparkSession. It is the ideal tool for ad-hoc analysis or intermediate transformations where the data does not need to be saved to long-term storage or shared across different clusters or users within the organization's wider data environment.

Why this answer

The CREATE TEMPORARY VIEW statement is the standard method for registering a DataFrame or table as a temporary view. These views are scoped to the SparkSession, making them invisible to other sessions or users. This is critical for modularizing complex SQL pipelines where intermediate results need to be referenced by name without polluting the global metastore or requiring permanent persistence in underlying storage.

Exam trap

Candidates often confuse 'TEMPORARY VIEW' with 'GLOBAL TEMPORARY VIEW'. They fail to realize that global views persist across sessions, whereas standard temporary views are strictly session-scoped and disappear upon termination.

56
MCQmedium

A data engineer submits a PySpark job that performs a wide transformation via a join operation across two large datasets. During execution, several tasks in the shuffle stage fail repeatedly due to transient network timeouts between worker nodes. How does Apache Spark's architecture handle these failed tasks?

A.The cluster manager automatically terminates the entire Spark application and generates a fatal core dump on the driver node.
B.The driver node marks the specific task as failed and resubmits it for execution, respecting the maximum task retry configuration.
C.All executors connected to the cluster are immediately restarted to clear corrupted memory partitions from the shuffle service.
D.The transformation is automatically converted from a wide transformation into a narrow transformation to avoid shuffle network traffic.
AnswerB

The driver tracks task status across the DAG scheduler and task scheduler. When a task throws an exception or experiences a timeout, the scheduler flags it as failed and schedules a retry on available executor slots.

Why this answer

Spark's driver node manages task scheduling and monitors execution. When a task fails due to a transient error, the task scheduler automatically resubmits the exact same task up to a configured maximum number of retries before failing the entire stage or job. This ensures fault tolerance without requiring manual intervention for temporary infrastructure glitches during distributed shuffles.

Exam trap

Candidates often assume that an entire stage or job immediately fails upon any task failure, forgetting that Spark's driver implements a built-in retry mechanism specifically for individual tasks before declaring a stage failure.

57
MCQmedium

Which of the following is the most efficient way to convert a Spark DataFrame into a format suitable for low-latency SQL queries in Databricks?

A.Write the data as a collection of CSV files in the cloud storage.
B.Write the data into a Delta table.
C.Keep the data as a temporary view in the driver's memory.
D.Write the data as JSON files to exploit document-based query engines.
AnswerB

Delta tables are optimized for performance with features like Z-Ordering, data skipping, and statistics. By leveraging these features, Delta tables provide the best balance of write performance and low-latency read performance for SQL queries in Databricks, making them the preferred choice for analytical data storage in the lakehouse.

Why this answer

Delta Lake is the gold standard for Spark workloads because it brings ACID transactions, schema enforcement, and high performance to data lakes. Converting DataFrames to Delta tables enables indexing, data skipping, and file-level statistics, which are essential for low-latency SQL access. This approach replaces older formats like Parquet, offering superior capabilities and seamless integration with the Databricks engine, making it the standard practice for modern data lake architecture.

Exam trap

Candidates often suggest converting to Parquet or JSON, believing these are the standard for SQL. They overlook that Delta Lake is the native, optimized format for the Databricks Lakehouse architecture.

58
MCQeasy

A data analyst uses Spark Connect to run a PySpark job against a Databricks cluster. They call `df.show()` to preview the DataFrame. Where does the actual computation for `show()` occur?

A.On the Databricks cluster's Spark driver and executors.
B.In the Databricks workspace's web browser via the notebook UI.
C.On a separate gateway node that proxies requests to the cluster.
D.On the client machine where the Spark Connect client is running.
AnswerA

With Spark Connect, the client sends the DataFrame operations as unresolved logical plans to the Spark Connect server running on the Databricks cluster. The server then translates these into Spark jobs executed by the driver and executors. The results of actions like `show()` are computed remotely and returned to the client for display.

Why this answer

Spark Connect follows a client-server architecture where the client sends a logical plan to the server, which then executes it using the cluster's Spark driver and executors. Actions like `show()` trigger remote computation, and only the results are returned to the client. This design enables thin clients and centralizes processing on the cluster.

Exam trap

The trap here is assuming that because the client calls `show()`, the computation happens locally or in the browser, when in fact Spark Connect delegates execution to the remote cluster.

59
MCQeasy

A developer wants to start using Spark Connect from a local Python environment to connect to an existing Databricks cluster. Which step is required to establish the connection?

A.Install the PySpark package that includes Spark Connect support and create a remote SparkSession using the Databricks workspace URL and authentication token.
B.Deploy a Spark driver on the local machine and configure it to join the remote cluster as an additional worker node.
C.Configure the local machine as a Databricks workspace member and install the Databricks Runtime locally to match the cluster version.
D.Open an SSH tunnel to the cluster's driver node and run the application directly on that node using spark-submit.
AnswerA

To use Spark Connect from a local environment, you need a PySpark installation that includes the Spark Connect client, and you must create a SparkSession configured with the remote server URL and authentication. Databricks provides connection details such as the workspace URL and a token. This setup allows the client to communicate with the cluster over gRPC.

Why this answer

Establishing a Spark Connect session from a local environment requires the Spark Connect client libraries and a remote SparkSession configured with the Databricks workspace URL and authentication token. This enables the thin client to send logical plans to the cluster. The other options describe traditional Spark deployment models or unnecessary local installations that do not align with Spark Connect's client-server design.

Exam trap

The trap here is confusing Spark Connect with classic Spark deployment, where you might run spark-submit on the cluster or set up a local driver.

60
MCQmedium

A data engineer has a Pandas-on-Spark DataFrame `psdf` with a default index. They call `psdf.sort_values('amount', ascending=False)`. After the operation, they notice that the resulting DataFrame's index values no longer match the original row positions. Which statement best describes the behavior of the index after sorting?

A.The index is dropped entirely, and the resulting DataFrame has no index.
B.The index values are reordered along with the rows, so the original index labels remain attached to their corresponding rows but are no longer sorted.
C.The index is reset to a sequential integer range starting at 0, preserving the new row order.
D.The index is converted to a distributed sequence based on Spark partition IDs, ensuring efficient subsequent operations.
AnswerB

In Pandas API on Spark, sort_values sorts the rows while carrying the index labels with them. The index is not reset; it simply becomes unsorted. This matches pandas behavior and is important when merging or aligning data, as the index labels still identify the original rows.

Why this answer

Sorting in Pandas API on Spark reorders rows but preserves the original index labels, which become unsorted. This is consistent with pandas semantics and ensures that index-based alignment still works. The index is not reset, dropped, or replaced with partition identifiers unless the user explicitly performs such an operation.

Exam trap

The trap here is assuming that sorting resets the index, as some might expect from SQL ORDER BY or from Spark DataFrame operations that produce a new row order without a persistent index.

61
MCQhard

A Databricks Structured Streaming job reads JSON files from a cloud storage directory and writes aggregated results to a Delta table. The source directory receives new files continuously and files are never modified after being written. The pipeline must tolerate late-arriving event data by up to 30 minutes and must not reprocess already-emitted windows when the query is restarted. Which combination of configurations is required to meet these requirements?

A.Configure `spark.sql.streaming.checkpointLocation` to a reliable cloud storage path, use `withWatermark("eventTime", "30 minutes")`, and set the output mode to `update`.
B.Set the source option `maxFilesPerTrigger` to a high value, define a watermark of 30 minutes on the event-time column, and rely on the default checkpoint location provided by the Spark session.
C.Set a checkpoint location on a durable file system, apply `withWatermark("eventTime", "30 minutes")`, and use the `append` output mode with a Delta table sink.
D.Use `withWatermark("eventTime", "30 minutes")`, set the output mode to `complete`, and configure a checkpoint location on DBFS.
AnswerC

A durable checkpoint location preserves query progress and state across restarts, satisfying the no-reprocessing requirement. The 30-minute watermark allows the engine to accept and incorporate late events up to 30 minutes past the window boundary. The `append` output mode emits a window's final result only after the watermark passes the window end, ensuring each window is emitted exactly once to the Delta sink.

Why this answer

The pipeline needs durable state recovery and late-data tolerance without re-emitting finalized windows. A checkpoint location on reliable storage ensures the query resumes from where it left off. A 30-minute watermark defines how long late events are accepted.

The append output mode emits each window only once, after the watermark passes the window end, which matches the no-reprocessing requirement when writing to Delta.

Exam trap

The trap here is assuming that any watermark combined with any output mode will prevent reprocessing, when only append mode guarantees a window is emitted once after finalization.

62
MCQeasy

A developer runs `spark.sql("SELECT * FROM sales")` and receives an error stating the table or view cannot be found, even though a Parquet directory exists at `dbfs:/mnt/raw/sales/`. The developer wants to query that Parquet data using Spark SQL without moving or copying the files. Which action should the developer take?

A.Create a table using `CREATE TABLE sales USING parquet LOCATION 'dbfs:/mnt/raw/sales/'` and then query it.
B.Set `spark.sql.warehouse.dir` to `dbfs:/mnt/raw/sales/` and rerun the query.
C.Execute `REFRESH TABLE sales` so Spark reloads the metadata from disk.
D.Run `MSCK REPAIR TABLE sales` to register the directory with the metastore.
AnswerA

Defining a table with `USING parquet` and a `LOCATION` clause registers the existing directory in the metastore so Spark SQL can resolve the name `sales`. Because the data stays in place, no copying occurs, and subsequent queries read the Parquet files directly. This matches the requirement to query existing files without relocation.

Why this answer

Spark SQL resolves table names through the metastore catalog, so a directory on storage is invisible until a table definition points at it. Using `CREATE TABLE ... USING parquet LOCATION ...` registers the path without moving data, enabling immediate querying by name.

Commands that repair or refresh metadata presuppose an existing table and cannot create one.

Exam trap

The trap here is confusing metadata-maintenance commands such as `MSCK REPAIR TABLE` or `REFRESH TABLE` with table creation, when those commands only operate on tables that already exist in the catalog.

63
MCQmedium

A data engineer is processing a 500 GB Parquet dataset on Databricks using the Pandas API on Spark. They need to extract a single scalar value, the maximum timestamp, to pass to a downstream orchestration tool. They use psdf['timestamp'].max(). Which statement correctly describes how this operation executes?

A.It is executed locally by converting the entire column to a pandas Series on the driver before computing the maximum.
B.It is an immediate, blocking operation that triggers a Spark job and returns a Python scalar.
C.It returns a new single-row pandas-on-Spark DataFrame that must be collected to obtain the value.
D.It is executed lazily and returns a scalar only when the DataFrame is collected or persisted to storage.
AnswerB

A reduction like max() on a pandas-on-Spark Series returns a single value, which cannot be represented lazily as a distributed collection. The implementation therefore submits a Spark job immediately, waits for the result, and returns a local Python scalar. This matches pandas semantics for scalar-returning operations and is the documented behavior for reductions in the pandas API on Spark.

Why this answer

Scalar-returning reductions in the pandas API on Spark, such as Series.max(), are eager: they immediately trigger a Spark job and return a local Python scalar. They do not return a lazy distributed object, because a single value has no distributed representation. This behavior aligns with pandas and is important when mixing pandas-on-Spark with orchestration code that expects a concrete value.

Exam trap

The trap here is assuming all pandas-on-Spark operations are lazy like Spark transformations, when scalar-returning reductions actually execute eagerly and return a local Python value.

64
MCQmedium

A developer runs a PySpark job on Databricks that filters a Delta table and then calls count() and show(). The Spark UI shows two separate scans of the same table. The developer wants to avoid the second scan without changing the filter logic. Which action should be taken?

A.Call checkpoint() on the filtered DataFrame to write it to a reliable path before count().
B.Enable spark.sql.adaptive.enabled and set spark.sql.adaptive.coalescePartitions.enabled to true.
C.Call persist() with StorageLevel.MEMORY_AND_DISK on the filtered DataFrame before count() and show().
D.Set spark.sql.files.maxPartitionBytes to 256 MB so each scan reads fewer, larger partitions.
AnswerC

persist() with MEMORY_AND_DISK materializes the filtered DataFrame on the first action and reuses the stored partitions for the second action, eliminating the duplicate scan. It is equivalent in effect to cache() but with an explicit storage level, and it directly targets the repeated scan shown in the Spark UI without altering the filter logic.

Why this answer

Persisting the filtered DataFrame with MEMORY_AND_DISK materializes it on the first action and lets the second action read the stored partitions instead of rescanning the Delta table. AQE, maxPartitionBytes, and checkpointing do not provide in-memory reuse across actions; they change plan shape or write to disk rather than caching the intermediate result for repeated access.

Exam trap

The trap here is assuming that adaptive execution or read-partition tuning will prevent a second scan, when only an explicit persist or cache keeps the intermediate DataFrame available across actions.

65
MCQhard

A Spark application running on a Databricks cluster uses a broadcast variable to distribute a small lookup table to all executors. During execution, the driver serializes the broadcast variable and sends it to each executor. Which component is responsible for storing the broadcast data on the executor side and making it available to tasks?

A.Block Manager
B.Task Scheduler
C.Shuffle Service
D.DAG Scheduler
AnswerA

The Block Manager on each executor is responsible for storing broadcast data. When the driver broadcasts a variable, it sends the data to each executor's Block Manager, which caches it in memory (and optionally on disk). Tasks can then access the broadcast variable locally without network overhead. This is a core part of Spark's broadcast mechanism.

Why this answer

Broadcast variables are distributed to executors using a BitTorrent-like protocol, and each executor's Block Manager stores the data. The Block Manager caches the broadcast data in memory and makes it available to tasks. This avoids shipping the data with each task, reducing network overhead and memory usage.

The Block Manager is integral to Spark's storage layer.

Exam trap

The trap here is assuming that the Task Scheduler or Shuffle Service handles broadcast data storage, when it is actually the Block Manager.

66
Multi-Selectmedium

A developer is working with a Spark SQL DataFrame that contains a column 'tags' which is an array of strings. The developer needs to filter rows where the array contains the string 'spark' and also transform the array to uppercase. Which TWO Spark SQL functions should be used to achieve these requirements? (Choose two.)

Select 2 answers
A.upper(tags)
B.array_contains(tags, 'spark')
C.transform(tags, x -> upper(x))
D.filter(tags, x -> x = 'spark')
E.explode(tags)
AnswersB, C

The array_contains function checks if a given value exists in an array. It returns a boolean, which can be used in a filter condition. This directly addresses the requirement to filter rows where the array contains 'spark'. It is the standard function for this purpose in Spark SQL.

Why this answer

To filter rows where the array contains 'spark', array_contains is the direct and efficient function. To transform each element of the array to uppercase, transform with a lambda using upper is the correct approach. Together, they satisfy both requirements without altering the DataFrame's structure.

Exam trap

The trap here is confusing element-level filtering within an array (using filter) with row-level filtering based on array contents (using array_contains).

67
Multi-Selecthard

A developer is using the Pandas API on Spark and wants to write efficient code. They are reviewing operations that can cause a full shuffle of data across the cluster. Which TWO operations should they be cautious about because they typically require a shuffle? (Choose two.)

Select 2 answers
A.`psdf[['id', 'amount']]`
B.`psdf.groupby('region').sum()`
C.`psdf['amount'] + 10`
D.`psdf.head(5)`
E.`psdf.sort_values('amount')`
AnswersB, E

`groupby` followed by an aggregation requires data with the same key to be brought together, which necessitates a shuffle. Spark performs a shuffle to partition rows by the grouping key before aggregating. This is a fundamental distributed operation and is expensive when the number of distinct keys is large or when data is skewed. Caching or pre-partitioning can mitigate the cost.

Why this answer

Operations that require global data reorganization, such as sorting and grouping, trigger shuffles. `sort_values` needs a global order, and `groupby` with aggregation needs rows with the same key co-located. By contrast, element-wise arithmetic, column selection, and `head` are narrow transformations that operate within partitions without moving data across the network.

Exam trap

The trap here is assuming that any pandas-like operation on a distributed DataFrame is equally expensive, when in fact narrow transformations avoid shuffles.

68
MCQhard

A developer is using Spark Connect to connect to a Databricks cluster. They attempt to read a CSV file from a path that exists on the client machine's local disk. The operation fails with a file not found error. What is the most likely reason for this failure?

A.The CSV reader requires a schema to be explicitly provided when using Spark Connect.
B.The file path is interpreted relative to the server's file system, not the client's, so the server cannot find the file.
C.Spark Connect does not support reading CSV files; only Parquet and Delta are supported.
D.The client must first upload the CSV file to the server's local file system using spark.uploadFile().
AnswerB

In Spark Connect, all data access is performed by the server. When you specify a path, it is resolved on the server's file system, not the client's. If the file exists only on the client's local disk, the server cannot read it, resulting in a file not found error. The file must be accessible from the cluster, such as in cloud storage or a mounted volume.

Why this answer

Spark Connect operates in a client-server model where the server executes all data operations. File paths are resolved on the server's file system. If a developer refers to a local file on the client machine, the server cannot access it, causing a file not found error.

The correct approach is to place data in a location accessible to the cluster, such as cloud storage.

Exam trap

The trap here is assuming that the client and server share a file system, which is not the case in Spark Connect's decoupled architecture.

69
Multi-Selectmedium

Which THREE components are part of the Spark execution environment that resides on the Driver node?

Select 3 answers
A.DAGScheduler
B.BlockManager
C.TaskScheduler
D.BlockManagerMaster
E.Executor Backend
AnswersA, C, D

The DAGScheduler is a critical component of the Spark Driver. It computes the execution graph of stages for a job, determining the dependencies between stages and the order in which they must be executed, making it essential for proper Spark job coordination and optimization.

Why this answer

The Spark Driver hosts key components for managing the cluster, including the DAGScheduler, which decomposes jobs into stages; the BlockManagerMaster, which manages metadata for cached blocks; and the TaskScheduler, which handles the execution of tasks. These components collectively ensure that the application logic is translated into a series of executable stages and that tasks are distributed efficiently, maintaining the central control architecture of a Spark application.

Exam trap

Candidates frequently include executor-side components like shuffle service or worker daemons when asked specifically about internal services residing on the Driver node.

70
MCQhard

A developer is using Spark SQL to join two DataFrames: a large fact table 'orders' and a smaller dimension table 'customers'. The join key is customer_id. The developer notices that the join is causing a shuffle and wants to avoid it. Which Spark SQL technique should be used to eliminate the shuffle for this join?

A.Use a broadcast hint: SELECT /*+ BROADCAST(customers) */ * FROM orders JOIN customers ON orders.customer_id = customers.customer_id
B.Set spark.sql.autoBroadcastJoinThreshold to -1 to force broadcast joins.
C.Repartition both DataFrames on customer_id before joining.
D.Use a merge hint: SELECT /*+ MERGE(customers) */ * FROM orders JOIN customers ON orders.customer_id = customers.customer_id
AnswerA

The broadcast hint tells Spark to broadcast the smaller 'customers' table to all executors, avoiding a shuffle of the large 'orders' table. This is the correct technique when one side of the join is small enough to fit in memory. Spark SQL supports the BROADCAST hint, and it is the standard way to eliminate shuffle for such joins. The hint must be placed immediately after SELECT.

Why this answer

The broadcast hint instructs Spark to send the smaller table to all executors, so the large table can be joined locally without shuffling. This is the optimal approach when one side of the join is small enough to fit in memory. Other options either disable broadcast, use an invalid hint, or introduce additional shuffles.

The broadcast join is a key optimization in Spark SQL for star-schema joins.

Exam trap

The trap here is confusing the autoBroadcastJoinThreshold setting: setting it to -1 disables broadcast joins, while increasing it enables broadcasting for larger tables.

71
MCQeasy

What is the primary benefit of using Spark Connect in a Databricks environment compared to traditional Spark clients?

A.It eliminates the need for any network communication.
B.It provides a more stable way to run long-running driver processes.
C.It allows developers to use a lightweight client without a full Spark driver installation.
D.It automatically scales the remote cluster based on local CPU usage.
AnswerC

Spark Connect enables thin clients to execute Spark code. Developers don't need to install full Spark packages or manage JVM compatibility on their local machines. This simplifies the developer workflow by allowing them to use standard Python environments to interact with massive Databricks clusters effortlessly.

Why this answer

The main benefit of Spark Connect is its ability to decouple the client application from the Spark cluster version and environment. By using a gRPC interface, the client does not need a local JVM or the same Spark version as the cluster. This allows developers to use any version of Python and lightweight libraries without worrying about dependency hell or local Spark installation requirements.

Exam trap

Candidates mistakenly believe Spark Connect is used to speed up cluster-side processing, whereas its actual primary purpose is client-side decoupling and environment simplification for developers.

72
Multi-Selecthard

Which TWO of the following are true concerning Spark SQL's handling of NULL values?

Select 2 answers
A.The COUNT(column_name) function excludes NULL values from the count.
B.NULL values are treated as zero in all mathematical operations.
C.The COUNT(*) function includes rows where all columns contain NULL values.
D.The 'IS NULL' condition is not supported in Spark SQL; use '== NULL' instead.
E.Joining on columns that contain NULL values will always result in an inner join match.
AnswersA, C

In Spark SQL, aggregate functions that target a specific column, such as COUNT(col), ignore NULL values. This behavior is standard ANSI SQL and is vital to understand when calculating metrics like non-null record counts, as failing to account for this can lead to significant errors in business reporting.

Why this answer

Correctly managing NULLs is crucial for data accuracy. Spark SQL treats NULLs as unknown values. Aggregate functions like SUM and COUNT(col) skip NULLs, while count(*) includes them.

Understanding these nuances is essential for developers to write robust SQL queries that correctly interpret missing data, avoiding common pitfalls in reporting and data quality validation processes within Databricks production environments.

Exam trap

Test-takers frequently assume COUNT(*) and COUNT(column_name) treat NULL values identically, leading to incorrect calculations when missing data is present.

73
Multi-Selecthard

A Spark job is running slower than expected due to excessive shuffling. Which TWO of the following techniques would directly reduce the volume of data transferred over the network?

Select 2 answers
A.Broadcast join for small tables.
B.Increase spark.sql.shuffle.partitions.
C.Filter and select columns early.
D.Enable dynamic resource allocation.
E.Increase spark.driver.memory.
AnswersA, C

Broadcast joins send the entire small table to every executor, allowing the join to occur locally. This eliminates the need to shuffle the large table, which is the most expensive part of a join, thereby reducing network overhead and significantly improving the performance of the overall job.

Why this answer

Reducing network traffic is critical in Spark performance tuning. By utilizing features like broadcast joins, you avoid the shuffle phase entirely when one table is small. Additionally, using filter and select operations early in the transformation pipeline ensures that only the necessary rows and columns are transmitted, significantly decreasing the total data volume shuffled during wide transformations.

Exam trap

Candidates often suggest increasing cluster size to solve shuffling issues. While this helps performance, it does not reduce the *volume* of data shuffled; only filtering or broadcasting does that.

74
MCQhard

A developer is troubleshooting a Spark Connect client that intermittently fails to create a session against a Databricks cluster. The cluster is configured to auto-terminate after 20 minutes of inactivity. The client script runs on a schedule every hour. What is the most likely cause of the intermittent session creation failures?

A.The auto-terminated cluster is not running when the hourly script attempts to connect, so the session cannot be established until the cluster is started.
B.The Spark Connect client library is incompatible with the Python version on the client machine.
C.The personal access token expires every hour and must be regenerated before each run.
D.Spark Connect sessions cannot be created from scheduled scripts and must be created interactively.
AnswerA

With a 20-minute idle timeout and an hourly schedule, the cluster terminates between runs. Spark Connect requires a running cluster to accept the gRPC session. Unless the client or job is configured to start the cluster, session creation fails. This matches the intermittent, schedule-linked pattern described.

Why this answer

Spark Connect needs a live server to accept the connection. A cluster that auto-terminates after 20 minutes will be stopped when an hourly job runs, so the client cannot establish a session unless it triggers a start or the job is configured to start the cluster. The schedule and idle timeout together explain the intermittent failures.

Exam trap

The trap here is blaming credentials or library versions for intermittent failures when the cluster lifecycle is the variable that matches the schedule.

75
Multi-Selecthard

A developer is tuning a Spark job that performs a join between a large fact table and a medium-sized dimension table. The job suffers from data skew, with a few keys having a disproportionately large number of rows. The developer wants to mitigate the skew. Which two actions are most effective? (Choose two.)

Select 2 answers
A.Enable Adaptive Query Execution (AQE) and set spark.sql.adaptive.skewJoin.enabled to true.
B.Broadcast the medium-sized dimension table to all executors.
C.Use a repartition on the join key before the join to evenly distribute the data.
D.Manually salt the skewed keys in the fact table by adding a random suffix and replicate the dimension table accordingly.
E.Increase spark.sql.shuffle.partitions to a very high number.
AnswersA, D

AQE with skew join optimization automatically detects skewed partitions during the shuffle and splits them into smaller sub-partitions. This balances the workload across tasks without manual intervention. It is a built-in feature that directly addresses skew by dynamically handling oversized partitions, making it an effective solution.

Why this answer

Data skew during a join occurs when a few keys have many more rows than others, causing some tasks to run much longer. Adaptive Query Execution with skew join optimization dynamically splits skewed partitions, while manual salting distributes hot keys across multiple tasks. Both approaches balance the workload and reduce the impact of skew.

Exam trap

The trap here is assuming that increasing shuffle partitions or repartitioning on the join key will fix skew, when they can actually worsen it by concentrating hot keys.

Page 1 of 4

Page 2

All pages