Courseiva

CCNA Data Transformation, Cleansing, Quality Questions

25 questions · Data Transformation, Cleansing, Quality · All types, answers revealed

1
MCQhard

You are building a pipeline and notice that the 'Gold' layer tables are experiencing significant write latency due to frequent small file commits. What is the most effective way to resolve this while maintaining ACID integrity?

A.Increase the 'spark.sql.shuffle.partitions' to 5000 to distribute writes more widely.
B.Run the 'OPTIMIZE' command periodically on the Gold layer tables.
C.Switch the table from Delta format to standard Parquet files to improve write performance.
D.Use the 'vacuum' command every 5 minutes to clear out the small files.
AnswerB

The OPTIMIZE command is specifically built to compact small files in Delta tables. By running it on a schedule or as part of the pipeline, you ensure that Gold tables remain performant for readers. It is an essential maintenance task in any production-grade Delta Lake environment to ensure high-performance query execution.

Why this answer

The 'OPTIMIZE' command with 'ZORDER' is the standard way to fix the small file problem in Delta Lake. It compacts small files into larger, better-performing ones while physically organizing data to speed up reads. This is critical for Gold tables, which are typically read by BI tools.

Maintaining performance here is essential for providing end-users with a responsive, high-performance experience when accessing critical business metrics and dashboards.

Exam trap

Candidates frequently suggest vacuuming or partitioning to fix small file issues, confusing storage cleanup and partitioning strategies with the actual file compaction performed by OPTIMIZE.

2
MCQmedium

A Data Engineer is using Delta Live Tables to process a stream of user events. The `user_id` column should be unique in the target table, but the source may contain duplicate events due to retries. The engineer wants to keep only the latest event for each `user_id` based on the `event_timestamp`. Which Delta Live Tables feature should be used?

A.Use `APPLY CHANGES INTO target` with `KEYS (user_id)` and `SEQUENCE BY event_timestamp`, and set `STORED AS SCD TYPE 2`.
B.Use `@dp.expect_or_drop("unique_user", "user_id IS NOT NULL")` and then apply `dropDuplicates(["user_id"])` on the resulting DataFrame.
C.Use `APPLY CHANGES INTO target` with `KEYS (user_id)` and `SEQUENCE BY event_timestamp`, and set `STORED AS SCD TYPE 1`.
D.Use `@dp.expect_or_drop("unique_user", "row_number() OVER (PARTITION BY user_id ORDER BY event_timestamp DESC) = 1")` in a streaming table definition.
AnswerC

This configuration uses `APPLY CHANGES` to upsert records by `user_id`, keeping the latest based on `event_timestamp`. SCD Type 1 ensures only the current record is stored, so each `user_id` appears once. It handles duplicates by overwriting with the latest event, which is exactly what is needed.

Why this answer

To deduplicate and keep only the latest event per `user_id`, `APPLY CHANGES` with SCD Type 1 and a sequence column is the correct Delta Live Tables feature. It performs upserts based on the key and sequence, ensuring one row per key with the latest data. SCD Type 2 would keep history, and window functions or dropDuplicates are not suitable for streaming deduplication.

Exam trap

The trap here is attempting to use window functions or dropDuplicates for streaming deduplication, which are either unsupported or limited in streaming contexts.

3
MCQhard

A Data Engineer is using Delta Live Tables to process a streaming source that contains duplicate records based on an 'event_id'. The engineer needs to ensure that only the latest record for each 'event_id' is retained in the target table, and the pipeline should handle late-arriving data. Which DLT feature should be used?

A.Use Delta Lake's MERGE INTO with a window function to rank records
B.Create a materialized view with a GROUP BY event_id and MAX(timestamp)
C.Use a streaming live table with a foreachBatch function to manually deduplicate
D.Apply changes with deduplication using the APPLY CHANGES API with a sequence column
AnswerD

The APPLY CHANGES API (formerly APPLY CHANGES INTO) supports deduplication by specifying a sequence column (e.g., event timestamp) and a key (event_id). It ensures only the latest record per key is retained, handling late-arriving data by ordering on the sequence column. This directly meets the requirement.

Why this answer

The APPLY CHANGES API in DLT is designed for change data capture and deduplication. By specifying a key column and a sequence column, it ensures that only the latest record for each key is retained, even with late-arriving data. This declarative approach simplifies pipeline code and leverages DLT's built-in handling of streaming data and state management.

Exam trap

The trap here is assuming that a simple MERGE or aggregation can handle late-arriving data; only the APPLY CHANGES API provides native sequencing and deduplication for streams.

4
MCQeasy

A Data Engineer is tasked with cleaning a dataset in Databricks. The dataset contains a column 'phone_number' with various formats, including parentheses, dashes, and spaces. The engineer needs to standardize all phone numbers to a digits-only format (e.g., '1234567890'). Which approach is most efficient and scalable?

A.Use a Python UDF with the re.sub() method to strip non-digit characters.
B.Use the translate() function to replace parentheses and dashes with empty strings.
C.Use the regexp_replace() function in Spark SQL to remove all non-digit characters.
D.Use the split() function to split on non-digit characters and then concatenate the parts.
AnswerC

regexp_replace() is a built-in Spark SQL function that can remove all non-digit characters from a string using a regular expression like '[^0-9]'. It operates in a distributed manner, making it efficient for large datasets. This is the simplest and most scalable approach for standardizing phone numbers.

Why this answer

regexp_replace() is a built-in, distributed function that efficiently removes all non-digit characters in one step. It leverages Spark's optimized execution engine and is the most scalable and straightforward method for this cleansing task. Other options involve less efficient UDFs, incomplete character replacement, or complex splitting logic.

Exam trap

The trap here is opting for a Python UDF because it seems familiar, but UDFs are slower and should be avoided when built-in functions suffice.

5
MCQmedium

A Data Engineer needs to enforce a NOT NULL constraint on a specific column in a Delta table while maintaining the ability to perform high-performance streaming writes. Which approach is the most efficient and native method to ensure this data quality requirement?

A.Apply a filter transformation in the DataFrame after the data is written to the table.
B.Use an external Delta Live Tables expectation to quarantine bad records.
C.Add a CHECK constraint to the table using the ALTER TABLE ADD CONSTRAINT command.
D.Perform a manual check within the Spark Structured Streaming loop before appending to the sink.
AnswerC

The ALTER TABLE ADD CONSTRAINT command natively integrates with Delta Lake's transaction log to enforce validation at the moment of ingestion. It is highly performant and ensures that no transaction containing a null value in the specified column will be committed, effectively preventing data quality issues at the source.

Why this answer

Using Delta Lake's CHECK constraints is the most efficient way to enforce data quality at write time. By defining a constraint, the Delta engine validates every incoming row against the business logic before committing the transaction. This avoids post-process cleanup jobs, reduces storage waste, and ensures that downstream consumers always receive valid data, which is critical for maintaining robust data pipelines in a Lakehouse architecture.

Exam trap

Candidates often try to implement data quality checks using external post-processing scripts or complex notebook logic rather than utilizing native table constraints.

6
Multi-Selecthard

A Data Engineer is implementing a medallion architecture. Which THREE steps are critical for effectively implementing a high-quality 'Silver' layer from 'Bronze' data?

Select 3 answers
A.Enforce strict schema validation on incoming Bronze files.
B.Perform deduplication to ensure unique records based on business keys.
C.Apply business logic and complex transformations to create aggregate summary tables.
D.Convert all column names to uppercase to ensure case-insensitive consistency.
E.Standardize data formats (e.g., timestamps, currency codes) across all source systems.
AnswersA, B, E

Schema enforcement at the Silver layer is critical to ensure data consistency. By validating that columns match expected types and structures, you prevent downstream failures in analytical queries and reporting tools, which often lack the robustness to handle unexpected schema changes or malformed data types automatically.

Why this answer

The Silver layer is the 'single source of truth' for refined data. By applying strict schema enforcement, deduplication, and standardized data types, you ensure that analytical tools receive reliable, high-quality information. Proper implementation here prevents the 'garbage in, garbage out' scenario, allowing data scientists and analysts to focus on modeling and reporting rather than constant, redundant data cleaning tasks, significantly increasing organizational productivity and trust in data.

Exam trap

Candidates often focus only on loading data, ignoring the critical deduplication and standardization steps that distinguish the refined Silver layer from the raw Bronze layer.

7
MCQhard

A Data Engineer is using Delta Live Tables to process a stream of financial transactions. The pipeline must ensure that each `transaction_id` appears only once in the target table, even if the source stream contains duplicates due to at-least-once ingestion. The engineer wants to use the `APPLY CHANGES` API. Which combination of settings will achieve this with minimal data loss?

A.Use `APPLY CHANGES INTO target` with `KEYS (transaction_id)` and `SEQUENCE BY timestamp`, and set `STORED AS SCD TYPE 1`.
B.Use `APPLY CHANGES INTO target` with `KEYS (transaction_id)` and omit the `SEQUENCE BY` clause, and set `STORED AS SCD TYPE 1`.
C.Use `APPLY CHANGES INTO target` with `KEYS (transaction_id)` and `SEQUENCE BY timestamp`, and set `STORED AS SCD TYPE 2`.
D.Use `APPLY CHANGES INTO target` with `KEYS (transaction_id)` and `SEQUENCE BY timestamp`, and set `STORED AS SCD TYPE 2` with `IGNORE NULLS`.
AnswerA

SCD Type 1 with `APPLY CHANGES` uses the specified keys to upsert records, keeping only the latest version based on the sequence column. This ensures each `transaction_id` appears once, with the most recent data. It handles duplicates by overwriting existing rows, which is appropriate for deduplication when the latest record is desired.

Why this answer

To deduplicate and keep only the latest record per `transaction_id`, `APPLY CHANGES` with SCD Type 1 and a sequence column is correct. SCD Type 1 performs upserts, overwriting existing rows, so each key appears once. SCD Type 2 would keep history, resulting in multiple rows.

The sequence column ensures the latest record is applied deterministically.

Exam trap

The trap here is assuming that SCD Type 2 is needed for deduplication, when in fact it preserves history and creates multiple rows per key.

8
MCQhard

Refer to the exhibit. A Data Engineer is attempting to merge data into a table with these constraints defined. If the incoming batch contains rows that violate these rules, what is the default behavior of the Delta Lake engine during the merge operation?

A.The engine silently ignores the invalid rows and completes the merge for valid records only.
B.The transaction fails entirely, and no changes are committed to the Delta table.
C.The invalid rows are automatically routed to a hidden sidecar table for later review.
D.The engine automatically updates the invalid rows to the default column value.
AnswerB

Constraints in Delta Lake are hard requirements. If an operation violates these rules, the commit fails, and the transaction is aborted. This guarantees that the table remains in a consistent state and prevents invalid data from entering the storage layer, which is crucial for maintaining reliable audit trails and reports.

Why this answer

Delta Lake maintains strict ACID compliance. When a transaction violates defined CHECK or NOT NULL constraints, the engine throws an error, and the entire transaction is rolled back. This behavior prevents data corruption and ensures that only valid state transitions occur.

This is essential for maintaining data integrity in complex ETL pipelines where maintaining a 'known good' state is preferred over partial updates or silent failures.

Exam trap

Candidates often believe that Delta Lake will silently drop, quarantine, or ignore invalid rows during a merge operation, missing the strict ACID transaction failure behavior.

9
MCQmedium

When designing a Data Quality framework in Databricks, what is the recommended approach for handling 'quarantined' records?

A.Delete the bad records and notify the team via an automated Slack notification.
B.Move invalid records to a 'quarantine' table with an additional column indicating the error.
C.Update the records in place by setting the invalid fields to NULL.
D.Stop the entire pipeline execution to ensure no bad data reaches the final target.
AnswerB

This approach is the gold standard for robust ETL. By tagging records with the reason for failure, engineers can easily analyze the patterns of error and fix the source issues. It maintains a clean primary table while simultaneously building a valuable dataset of quality issues for analysis.

Why this answer

Storing invalid records in a separate, dedicated table allows for auditing and correction without blocking the main pipeline. This ensures high throughput for valid data while providing a clear path for reprocessing bad data once the underlying issue is fixed. It is a fundamental pattern for resilient data engineering, ensuring that data is never silently dropped and that stakeholders maintain confidence in the data's reliability.

Exam trap

Candidates frequently suggest deleting invalid records outright. They often overlook the requirement for auditing and reprocessing, which necessitates moving data to a quarantine table rather than simply discarding it.

10
MCQmedium

A Data Engineer needs to verify that the column 'user_id' is unique in a critical Gold table. What is the most efficient, non-blocking way to perform this check in a production environment?

A.Run a daily query: SELECT COUNT(user_id) - COUNT(DISTINCT user_id).
B.Define a primary key constraint in the Delta table definition.
C.Use a custom UDF to check for duplicates inside a Spark streaming loop.
D.Perform a left-anti join with the previous day's data every time the pipeline runs.
AnswerB

Delta Lake supports primary key constraints, which are natively enforced during the transaction. This is the most efficient and robust way to guarantee uniqueness, as the engine rejects any attempt to insert a duplicate value, maintaining the 'single source of truth' integrity required for production-grade analytical and operational data.

Why this answer

Using a Delta constraint or a DLT expectation is the most efficient way to enforce uniqueness at the storage layer. Unlike a full table scan query, which is reactive and performance-intensive, native constraints are checked during the commit process, providing proactive quality assurance. This ensures that the table never enters an invalid state, which is vital for the integrity of downstream machine learning models and reporting applications.

Exam trap

Candidates often suggest running a 'SELECT COUNT(DISTINCT id)' query as a post-process check. This is inefficient and reactive, whereas Delta constraints are proactive and enforced at the write level.

11
MCQeasy

A data engineer is using PySpark to cleanse a DataFrame containing customer addresses. The 'zip_code' column has some values with leading zeros that were stripped during CSV ingestion. The engineer needs to restore all zip codes to a fixed 5-character length by padding with leading zeros. Which function should be used?

A.regexp_replace(zip_code, '^', '0')
B.format_string('%05d', zip_code)
C.rpad(zip_code, 5, '0')
D.lpad(zip_code, 5, '0')
AnswerD

The lpad function pads the left side of a string with a specified character until it reaches the desired length. Using lpad(zip_code, 5, '0') ensures every zip code becomes exactly 5 characters, restoring leading zeros that were lost. This is the correct and idiomatic way to fix the issue in PySpark without complex logic.

Why this answer

The lpad function is designed to pad strings on the left to a specified length. It correctly restores leading zeros for zip codes that lost them during ingestion, ensuring all values are exactly 5 characters. Other functions either pad on the wrong side, assume numeric types, or do not achieve the required fixed length.

Exam trap

The trap here is confusing lpad with rpad, or assuming that zip codes are numeric and can be formatted as integers.

12
MCQhard

A data engineer is using Delta Lake to manage a table that receives frequent updates and deletes. The engineer notices that query performance has degraded over time due to many small files. Which command should be used to optimize the table by compacting small files and improving query performance?

A.ANALYZE TABLE table_name COMPUTE STATISTICS
B.OPTIMIZE table_name
C.VACUUM table_name
D.ALTER TABLE table_name SET TBLPROPERTIES ('delta.autoOptimize.optimizeWrite' = 'true')
AnswerB

The OPTIMIZE command compacts small files into larger ones, reducing the number of files and improving query performance. It also supports Z-Ordering for multi-dimensional clustering. This is the standard Delta Lake operation for file compaction. It is efficient and can be scheduled regularly. This command directly addresses the issue of many small files.

Why this answer

The OPTIMIZE command is designed to compact small files into larger ones, improving read performance. It can also perform Z-Ordering to cluster data. VACUUM removes old files but does not compact, ANALYZE collects statistics, and autoOptimize.optimizeWrite prevents future small files but does not fix existing ones.

Therefore, OPTIMIZE is the correct command to address the current small file issue.

Exam trap

The trap here is confusing VACUUM with OPTIMIZE; VACUUM removes old files but does not compact small files, while OPTIMIZE specifically addresses file compaction.

13
MCQhard

You need to perform a deduplication task on a streaming source that includes late-arriving data. Which Delta Lake feature is best suited to manage this while ensuring efficient state cleanup?

A.Use a standard SQL DELETE query with a subquery to identify and remove duplicates.
B.Use the dropDuplicates() method with watermark settings to manage state.
C.Set the table property 'delta.enableChangeDataFeed' to true and filter on the change log.
D.Increase the 'spark.sql.shuffle.partitions' setting to ensure all duplicates land on the same node.
AnswerB

Using dropDuplicates on a streaming DataFrame, combined with a watermark, allows Spark to manage the state of seen records efficiently. The watermark specifies the time limit for which duplicates are tracked, ensuring the state doesn't grow indefinitely, which is essential for long-running streaming pipelines consuming data with late arrivals.

Why this answer

The `withWatermark` and `dropDuplicates` combination is specifically designed for streaming deduplication. Watermarks tell the engine how long to wait for late-arriving data, allowing it to clear old state from memory. This is critical for high-volume streaming jobs where state growth would otherwise lead to out-of-memory errors or significant performance degradation, ensuring the job remains stable over long periods of execution.

Exam trap

Candidates often select simple batch deduplication methods or manual window operations, failing to recognize that watermarking is essential for managing state and late-arriving data in streaming.

14
MCQmedium

When refining data in a Medallion architecture, why is it recommended to perform schema enforcement as early as possible in the Bronze layer?

A.It eliminates the need for any further schema validation in the Silver or Gold layers.
B.It ensures that the storage cost of the Bronze layer is kept at a minimum.
C.It prevents malformed data from polluting downstream layers and makes debugging easier.
D.It automatically converts all incoming file formats into the optimal Delta format.
AnswerC

Enforcing schema early is the most effective way to identify and fix data quality issues before they become deeply embedded in the refined datasets. By ensuring the Bronze layer is consistent, you simplify the entire transformation pipeline, making it easier to pinpoint the source of any issues when they arise.

Why this answer

Early enforcement catches errors at the ingestion point, preventing corrupt data from propagating into Silver or Gold layers. This practice keeps the 'upstream' data quality high, reducing the need for costly, complex fixes in downstream tables. It ensures that the Medallion architecture remains clean and reliable, minimizing the time spent debugging issues that could have been resolved at the very first step of the data pipeline.

Exam trap

Candidates often believe schema enforcement should happen in the Silver layer after cleaning. They ignore that cleaning data is significantly harder once malformed records have already entered the system.

15
MCQhard

A Data Engineer is using Delta Live Tables (DLT) to build a pipeline that ingests JSON files from cloud storage. The engineer defines a streaming table with expectations to enforce data quality. The expectation `@dlt.expect_or_drop("valid_timestamp", "timestamp IS NOT NULL")` is applied. During a pipeline run, 5% of records have a NULL timestamp. What is the outcome for those records, and how does it affect the pipeline?

A.The records with NULL timestamp are dropped from the target table, and the pipeline continues processing without failure.
B.The records with NULL timestamp are dropped, and the pipeline fails after processing the batch due to the drop threshold being exceeded.
C.The records with NULL timestamp are quarantined in a separate table, and the pipeline fails with an error.
D.The records with NULL timestamp are retained in the target table, but the pipeline fails with a data quality error.
AnswerA

The `expect_or_drop` decorator instructs DLT to drop records that violate the expectation and continue processing. The dropped records are not written to the target table, but the pipeline does not fail. Metrics are recorded to track the number of dropped records. This allows the pipeline to maintain data quality while handling invalid data gracefully, which is the intended behavior for this expectation.

Why this answer

The `expect_or_drop` expectation drops records that violate the condition and allows the pipeline to continue. It does not quarantine records, retain them, or fail the pipeline. This behavior is designed to handle data quality issues without interrupting processing, while still providing metrics on dropped records.

Exam trap

The trap here is assuming that `expect_or_drop` quarantines records or fails the pipeline, when it simply drops them and continues.

16
MCQmedium

You are tasked with handling PII (Personally Identifiable Information) in your data pipeline. Which approach is best for protecting this data while maintaining the ability to perform analytics?

A.Simply drop the PII columns during the Bronze-to-Silver transformation.
B.Encrypt the PII data using a shared key stored in the pipeline code.
C.Hash the PII columns using a salted, non-reversible cryptographic hash function.
D.Use a public, non-salted MD5 hash function to ensure consistency across teams.
AnswerC

Hashing with a salt provides a secure, non-reversible way to mask PII while maintaining referential integrity. This allows analysts to group data by the hash key without seeing the actual sensitive values. It is a highly recommended practice for balancing data utility with strict regulatory and privacy requirements.

Why this answer

Hashing or tokenizing PII allows for unique identification without exposing sensitive information. This is a standard practice for compliance (e.g., GDPR, CCPA). By using consistent hashing, you maintain the ability to join tables or perform group-bys on the hashed key while ensuring that unauthorized users cannot reverse-engineer the sensitive original values, balancing security with functional analytical utility.

Exam trap

Candidates frequently assume that dropping PII columns is the only compliance method, forgetting that cryptographic hashing allows analytics while protecting sensitive data.

17
Multi-Selecthard

Which TWO statements regarding the use of 'APPLY CHANGES INTO' in Delta Live Tables (DLT) are correct?

Select 2 answers
A.It supports schema evolution automatically when adding new columns to the source stream.
B.It can be used to perform deletes on the target table by issuing manual DELETE commands.
C.It requires the source to be a streaming table or a view registered in the pipeline.
D.It allows for multiple primary keys, but only one can be used for sequencing the updates.
E.It automatically creates a history table for SCD Type 1 processing by default.
AnswersA, C

APPLY CHANGES INTO inherently supports schema evolution, allowing the target table to adapt to new columns present in the source stream. This is essential for long-running pipelines where source data structures might change over time, ensuring that the target reflects the latest source state without requiring manual intervention.

Why this answer

APPLY CHANGES INTO is the declarative mechanism for SCD Type 1 or Type 2 processing in DLT. It manages the complexity of merging streaming data into a target table, handling late-arriving data and updates efficiently. Understanding its constraints, such as the requirement for a defined primary key and the inability to perform manual data deletions, is critical for maintaining consistent state in bronze-to-silver transformations.

Exam trap

Candidates often assume 'APPLY CHANGES INTO' works on static tables or supports manual deletes. They frequently overlook that it is designed specifically for streaming, SCD-based incremental updates.

18
MCQmedium

A data engineer is using PySpark to cleanse a large dataset of customer records. The DataFrame `df` contains a string column `phone` with values like '123-456-7890', '(123) 456-7890', and '1234567890'. The engineer needs to standardize these to digits only (e.g., '1234567890'). Which transformation should be used?

A.df.withColumn('phone_clean', split('phone', '[^0-9]'))
B.df.withColumn('phone_clean', translate('phone', '-() ', ''))
C.df.withColumn('phone_clean', regexp_replace('phone', '[^0-9]', ''))
D.df.withColumn('phone_clean', trim('phone'))
AnswerC

The regexp_replace function replaces all non-digit characters with an empty string, effectively removing hyphens, parentheses, and spaces. This standardizes the phone numbers to a contiguous digit string, which is the desired outcome. It operates on the column 'phone' and creates a new column 'phone_clean' without modifying the original data, aligning with typical cleansing practices.

Why this answer

To standardize phone numbers to digits only, all non-digit characters must be removed. The regexp_replace function with the pattern '[^0-9]' efficiently replaces any character that is not a digit with an empty string, resulting in a clean digit-only string. This method is robust and handles various formats without complex string manipulation.

Other functions like translate or split do not directly produce the desired output.

Exam trap

The trap here is assuming that translate can remove characters by mapping them to an empty string, but translate requires equal-length mapping strings and will not work as intended for removal.

19
MCQmedium

A Data Engineer wants to monitor data quality trends over time for a critical table. Which tool provides the most native and easy-to-use visualization of these metrics?

A.Export all data quality logs to an external S3 bucket and use a third-party BI tool.
B.Create a Databricks SQL dashboard using the 'expectations' table provided by DLT.
C.Write a custom Spark job to parse the Delta transaction log and send alerts via email.
D.Manually query the 'information_schema' every hour to track table row counts.
AnswerB

DLT automatically generates system tables that store the results of all quality expectations. These tables are readily available for querying via Databricks SQL, making it the fastest and most efficient way to visualize quality trends natively within the platform, without needing extra infrastructure or complex integrations.

Why this answer

Delta Lake's integration with Databricks SQL and DLT provides native dashboards that track data quality metrics automatically. Using Expectation history logs, engineers can visualize failure rates and quality trends without building custom monitoring solutions. This visibility is essential for proactive maintenance, allowing teams to catch degrading data quality before it impacts critical downstream business reporting, ensuring higher service levels for end-users.

Exam trap

Candidates often assume they must build custom dashboards using external tools like Grafana or Power BI, failing to realize that Databricks SQL provides built-in, native visualization capabilities specifically for DLT quality metrics.

20
MCQhard

You are performing a complex data transformation involving a self-join on a large, skewed table. Which technique is most effective for preventing data skew and improving join performance?

A.Increase the number of executors in the cluster to handle the load.
B.Use the 'repartition' hint on the join keys to force uniform distribution.
C.Apply a 'salt' to the join key to redistribute the skewed data across more partitions.
D.Convert the join into a broadcast join to prevent shuffling entirely.
AnswerC

Salting adds a random factor to the join key, which breaks up the large, heavy partitions caused by skewed values. By distributing the data across more executors, you ensure that no single task is overwhelmed, which is the most effective way to eliminate skew and improve join performance.

Why this answer

Skewed joins are a primary cause of performance failure in distributed computing. Using a 'salted' key—adding a random prefix to the join key—distributes data evenly across partitions during the join. This prevents 'hot' partitions where one executor processes the majority of the data, significantly speeding up the query and preventing OOM (Out of Memory) errors, ensuring consistent performance for large-scale analytical tasks.

Exam trap

Candidates often suggest increasing cluster size or memory, which fails to address the underlying data distribution problem causing skewed partitions in the join operation.

21
MCQmedium

You are migrating a legacy CSV-based ETL process to Databricks. The source CSV files contain inconsistent date formats. Which approach provides the most scalable way to handle these inconsistencies during the bronze-to-silver transformation?

A.Convert all columns to string type to avoid parsing errors, and handle formatting in the visualization tool.
B.Use the 'from_unixtime' function with a hardcoded string format for all records.
C.Use the 'to_timestamp' function with an array of acceptable formats to parse the column.
D.Delete all rows with invalid date formats using a 'drop' expectation in a DLT pipeline.
AnswerC

The 'to_timestamp' function in Spark SQL accepts a format string or an array of formats. This allows the engine to attempt parsing against multiple patterns, which is the most robust and performant way to handle format inconsistencies without writing complex, slow-running row-based logic or custom UDFs.

Why this answer

Using Spark's `to_timestamp` with multiple format strings or a custom UDF is the standard, scalable way to handle format drift. By applying this logic in the Silver layer, you preserve the raw data in the Bronze layer while ensuring the refined data is standardized. This strategy follows the Medallion architecture pattern, allowing for lineage tracking and the ability to reprocess data if requirements change or better parsing logic is developed.

Exam trap

Candidates often attempt to fix inconsistent date formats using single-format parsers or raw string manipulation, ignoring functions that accept multiple fallback format patterns.

22
MCQmedium

A Data Engineer is working on a Delta Live Tables (DLT) pipeline that ingests JSON files from cloud storage. The pipeline must drop rows where the 'email' column is null and also flag rows where 'age' is negative as invalid, but still process them. Which combination of DLT expectations should be used?

A.Use @dlt.expect_all({"valid_email": "email IS NOT NULL", "non_negative_age": "age >= 0"})
B.Use @dlt.expect_or_fail("valid_email", "email IS NOT NULL") and @dlt.expect_or_drop("non_negative_age", "age >= 0")
C.Use @dlt.expect_all_or_drop({"valid_email": "email IS NOT NULL", "non_negative_age": "age >= 0"})
D.Use @dlt.expect_or_drop("valid_email", "email IS NOT NULL") and @dlt.expect("non_negative_age", "age >= 0")
AnswerD

Using expect_or_drop for email nulls removes those rows, while expect for negative age records and retains them, flagging as invalid. This matches the requirement to drop rows with null email and flag negative ages without dropping them.

Why this answer

The correct approach uses expect_or_drop for the email null rule to remove those rows, and expect for the age rule to record violations without dropping. This satisfies both the drop and flag requirements simultaneously. Other expectation types either fail the pipeline, only log metrics, or drop rows that should be retained.

Exam trap

The trap here is confusing expect_or_drop with expect; the former drops rows, while the latter only records metrics.

23
MCQmedium

A Data Engineer is building a Databricks SQL pipeline that ingests clickstream events from a Delta table. The events table contains a nested column `payload` of type STRUCT with fields `page_id` (STRING), `duration` (INT), and `referrer` (STRING). The engineer needs to flatten the `payload` fields into top-level columns and drop any records where `page_id` is NULL. Which SQL expression accomplishes this transformation while preserving all other columns?

A.SELECT *, payload.* AS (page_id, duration, referrer) FROM events WHERE payload.page_id IS NOT NULL
B.SELECT *, payload.page_id AS page_id, payload.duration AS duration, payload.referrer AS referrer FROM events WHERE payload.page_id IS NOT NULL
C.SELECT *, explode(payload) AS (page_id, duration, referrer) FROM events WHERE page_id IS NOT NULL
D.SELECT *, payload[0] AS page_id, payload[1] AS duration, payload[2] AS referrer FROM events WHERE payload[0] IS NOT NULL
AnswerB

This correctly uses dot notation to extract nested fields from the STRUCT column and renames them as top-level columns. The WHERE clause filters out records where the nested page_id is NULL, preserving all other columns via the wildcard. Databricks SQL supports this syntax for nested data, making it a valid and efficient solution for flattening and cleansing clickstream events.

Why this answer

The correct solution uses dot notation to access nested STRUCT fields, renames them to top-level columns, and applies a filter on the nested field to drop NULL page_id records. This is the standard and supported way in Databricks SQL to flatten and cleanse nested data while retaining all other columns. The other options misuse functions or syntax not applicable to STRUCT types.

Exam trap

The trap here is confusing STRUCT field access with array indexing or assuming that explode works on STRUCTs, when it is only for arrays and maps.

24
MCQmedium

A Data Engineer is building a Delta Live Tables (DLT) pipeline to ingest raw JSON data. They need to ensure that records missing the required 'user_id' field are dropped while simultaneously capturing these discarded records in a separate table for auditing purposes. Which approach achieves this in DLT?

A.Apply the 'expect_or_drop' constraint and use a trigger to log dropped records.
B.Use the 'expect_or_fail' constraint to halt the pipeline and flag the error.
C.Define two separate tables in the pipeline, one filtering for valid records and one for invalid records using the NOT condition.
D.Configure a DLT pipeline to use 'expect_all_drop' to automatically split the data stream.
AnswerC

By defining two tables, you leverage the declarative nature of DLT to materialize valid and invalid datasets concurrently. Using the inverse logical condition for the audit table ensures that all records are accounted for, meeting both the ingestion requirement and the audit policy without halting the pipeline's progress.

Why this answer

To handle data quality in DLT, the 'expect_violation_or_drop' constraint is not a standard clause. Instead, the 'expect_or_drop' constraint removes invalid records, but does not preserve them. The correct architectural pattern involves using a separate pipeline or query that filters for the inverse condition (where 'user_id' is null) and writes those records to an 'expect_all_fail' target table, maintaining strict lineage and auditing for schema non-compliance.

Exam trap

Candidates often search for a single DLT command that drops and saves records simultaneously. They fail to realize that DLT requires two distinct logic paths to separate valid and invalid data.

25
MCQmedium

A Data Engineer is building a Lakeflow Spark Declarative Pipelines pipeline that ingests JSON sensor events. The pipeline must drop records where the `sensor_id` is NULL, ensure that `event_time` is not in the future, and continue processing without failing the update. Which combination of expectations should be used?

A.Use `@dp.expect_all({"valid_sensor": "sensor_id IS NOT NULL", "valid_time": "event_time <= current_timestamp()"})` on the dataset.
B.Use `@dp.expect_or_fail("valid_sensor", "sensor_id IS NOT NULL")` and `@dp.expect_or_drop("valid_time", "event_time <= current_timestamp()")` on the dataset.
C.Use `@dp.expect_all_or_fail({"valid_sensor": "sensor_id IS NOT NULL", "valid_time": "event_time <= current_timestamp()"})` on the dataset.
D.Use `@dp.expect_or_drop("valid_sensor", "sensor_id IS NOT NULL")` and `@dp.expect_or_drop("valid_time", "event_time <= current_timestamp()")` on the dataset.
AnswerD

These expectations drop records that violate the conditions while allowing the pipeline update to complete successfully. `expect_or_drop` is the correct decorator when you want to discard bad records and not fail the pipeline. Both conditions are expressed as SQL expressions, which are evaluated per row. The pipeline continues processing, and dropped records are tracked in event logs and metrics.

Why this answer

The pipeline must drop records that violate the conditions and continue processing. `expect_or_drop` is designed for this: it discards invalid rows and allows the update to succeed. Using `expect_or_fail` would halt the pipeline, and `expect_all` would not remove the bad records, leaving them in the target table.

Exam trap

The trap here is confusing `expect_all` (which only logs metrics) with `expect_or_drop` (which actually removes records), or assuming that `expect_or_fail` is needed to enforce data quality.

Ready to test yourself?

Try a timed practice session using only Data Transformation, Cleansing, Quality questions.