Back to interview questions

100+ Databricks Interview Questions and Answers

100+ Databricks Interview Questions and Answers

Explore 120 Databricks interview questions and answers covering Spark, SQL, Delta Lake, pipelines, governance, and production data engineering architecture.

Explore 120 Databricks interview questions and answers covering Spark, SQL, Delta Lake, pipelines, governance, and production data engineering architecture.

By

Team Sherlock.sh

Add Sherlock as a preferred source on Google

Databricks supports data engineering and SQL analytics on a lakehouse architecture, with Apache Spark and Delta Lake central to many workflows. Data engineers need to explain how their pipelines transform data, maintain correctness, recover from failures, and meet performance and access requirements.

This guide to 100+ Databricks Interview Questions and Answers contains 120 questions across beginner, intermediate, and experienced levels. It covers Spark execution, SQL, Delta tables, ingestion, streaming, orchestration, governance, and production architecture, with practical examples for candidates and hiring teams evaluating hands-on data engineering skills.

How can recruiters detect AI-assisted cheating, deepfakes, and impersonation during Databricks interviews?

Databricks assessments often combine SQL or PySpark exercises with pipeline debugging and architecture discussions. Candidates need to explain why a join creates a shuffle, how a retry affects a write, and what a Delta operation guarantees. Real-time generated answers or unauthorized help can obscure whether that reasoning is their own.

Sherlock AI helps recruiters detect potential AI-assisted cheating, deepfakes, candidate impersonation, and unauthorized real-time assistance during Databricks data engineering and architecture interviews.

Combine interview-integrity checks with a small data-transformation exercise and follow-up questions about the execution plan, schema, and failure behavior. Ask candidates to explain the assumptions behind their solution and how they would investigate an unexpected result. Review suspicious activity in context rather than treating a signal as proof of misconduct.

Databricks Interview Questions

Use this question bank to select topics that fit the role and platform responsibilities. Start with Spark, SQL, and Delta fundamentals, then add implementation and operational scenarios. A focused subset of the 120 questions is more useful than trying to cover every topic in one interview.

Databricks Interview Questions for Beginners

These beginner questions establish the roles of workspaces, compute, notebooks, DataFrames, SQL, and Delta tables. They connect platform terminology to basic transformations and the distinction between writing an expression and executing distributed work.

  1. What is Databricks, and what does it add beyond open-source Apache Spark?

  2. How does a lakehouse differ from a data lake and a traditional data warehouse?

  3. Why does separating compute from storage matter in Databricks?

  4. How are a Databricks account and a workspace different?

  5. What can you do in a Databricks notebook, and why is notebook execution order important?

  6. What is Databricks Runtime, and why should a project record its runtime version?

  7. How do all-purpose compute, jobs compute, serverless compute, and SQL warehouses serve different workloads?

  8. What do the driver and executors do in a Spark application?

  9. What is SparkSession, and how is it used in a Databricks notebook?

  10. How does a Spark DataFrame differ from an RDD and a local pandas DataFrame?

  11. How are Spark SQL queries related to DataFrame transformations?

  12. What does lazy evaluation mean in Spark?

  13. What is the difference between a Spark transformation and an action?

  14. Why might you define an explicit schema instead of relying on schema inference?

  15. How do select, filter, and withColumn change a PySpark DataFrame?

  16. What does groupBy do, and how do aggregate functions summarize data?

  17. How does an inner join differ from a left outer join?

  18. How do SQL NULL values affect comparisons, filters, and counts?

  19. How is a temporary view different from a persistent table?

  20. What does Delta Lake add to a folder of Parquet files?

  21. What do ACID properties mean for a Delta table write?

  22. What information does the Delta transaction log coordinate?

  23. How does schema enforcement differ from schema evolution?

  24. What is Delta time travel, and what is table history used for?

  25. How do Unity Catalog managed tables differ from external tables?

  26. What are catalogs, schemas, and tables in the Unity Catalog namespace?

  27. Why are table permissions different from permission to open a notebook or use compute?

  28. What is a Unity Catalog volume, and when would you use one instead of a table?

  29. Why are DBFS root and DBFS mounts not the default choice for a new Databricks design?

  30. What do bronze, silver, and gold represent in a medallion architecture?

  31. How does batch processing differ from Structured Streaming?

  32. What is Auto Loader, and what type of ingestion problem does it solve?

  33. What is a streaming checkpoint, and why does each query need its own location?

  34. How does event time differ from processing time?

  35. How do jobs, tasks, and triggers fit together in Lakeflow Jobs?

  36. Why should notebooks and jobs use validated parameters rather than hard-coded values?

  37. How do Lakeflow pipelines differ from manually orchestrating transformation notebooks?

  38. What does MLflow track during a machine-learning experiment?

  39. How should a notebook access a secret without embedding the value in its source code?

  40. What are the main sources of Databricks workload cost, and why is runtime alone not a complete cost measure?

Databricks Interview Questions for Intermediate

These intermediate questions focus on joins, aggregations, incremental ingestion, schema changes, streaming, and query performance. They examine how implementation choices affect correctness, restart behavior, and the cost of processing real datasets.

  1. How would you read a CSV with an explicit schema and separate malformed records from valid data?

  2. How would you flatten a nested JSON array while preserving the parent record identifier?

  3. How would you distinguish NULL, an empty string, and an invalid numeric value in a cleaning rule?

  4. When would you use unionByName rather than union, and what schema checks still matter?

  5. How would you keep the latest record per business key using a window function and a deterministic tie-breaker?

  6. When are left semi and left anti joins more appropriate than an inner or left join?

  7. When can a broadcast join help, and what can make broadcasting the wrong choice?

  8. Which Spark operations usually cause a shuffle, and why does that matter?

  9. How do repartition and coalesce differ when changing a DataFrame's partition count?

  10. How would you use EXPLAIN or DataFrame.explain to investigate an inefficient query plan?

  11. Which Spark UI metrics would you inspect to distinguish skew, shuffle spill, and slow input reads?

  12. When is caching a DataFrame useful, and when can it make a workload worse?

  13. Why might a built-in Spark SQL function be preferable to a Python UDF?

  14. What can adaptive query execution change at runtime, and what problems does it not solve automatically?

  15. Why do small files hurt table performance, and how does OPTIMIZE address the problem?

  16. How do liquid clustering, directory partitioning, and Z-ordering differ as table-layout choices?

  17. How would you write a MERGE that updates existing business keys and inserts new ones?

  18. Why can multiple source rows matching one target row make MERGE fail or become ambiguous?

  19. How would you introduce a new source column without silently accepting every future schema change?

  20. How would you inspect table history, query an older version, and decide whether RESTORE is appropriate?

  21. What checks should precede VACUUM when long-running readers and streaming consumers exist?

  22. How would you configure Auto Loader with a durable checkpoint and schema location to ingest files into a governed table?

  23. What does Auto Loader's rescued data column capture, and how should a pipeline respond to schema drift?

  24. When would COPY INTO be sufficient, and when would you choose Auto Loader instead?

  25. How do append, update, and complete output modes differ for a streaming aggregation?

  26. How would you combine an event-time window with a watermark, and what happens to very late records?

  27. When would you use AvailableNow rather than a continuously running micro-batch trigger?

  28. How would you make a foreachBatch write safe to retry?

  29. What does change data feed expose, and how do its configuration and retention requirements affect a consumer?

  30. How do SCD Type 1 and Type 2 differ, and where can AUTO CDC simplify their implementation?

  31. How would you choose between retaining, dropping, quarantining, or failing on an invalid pipeline record?

  32. How would you configure task dependencies, retries, and repair runs for a multi-task job?

  33. How should job parameters and task values be used to pass control information between tasks?

  34. What should unit tests and integration tests check in a PySpark transformation pipeline?

  35. How do Git folders and Declarative Automation Bundles support repeatable development and deployment?

  36. What privileges does a group need to read a Unity Catalog table, and why is SELECT alone sometimes insufficient?

  37. How do a storage credential and an external location work together without exposing cloud keys to every notebook?

  38. How do row filters and column masks differ from ordinary table-level grants?

  39. Which code, data, parameter, metric, and environment details should an MLflow run retain for reproducibility?

  40. How would you attribute workload usage to teams and compare the cost of two pipeline designs?

Databricks Interview Questions for Experienced

These experienced-level questions examine architecture, governance, operational recovery, and performance at scale. They emphasize how to evaluate trade-offs across workloads, data boundaries, deployment changes, and evolving platform capabilities.

  1. How would you organize workspaces, catalogs, schemas, and service identities for several teams sharing one lakehouse?

  2. How would you choose between scheduled batch, incremental micro-batches, and low-latency streaming for a new data product?

  3. A file-ingestion pipeline stopped for several days. How would you resume it without losing data or reprocessing everything blindly?

  4. How would you apply an out-of-order CDC feed that contains updates, deletes, and multiple events for the same key?

  5. Under what conditions can a streaming pipeline claim exactly-once results, and where can duplicate effects still occur?

  6. How would you change a stateful streaming query when its existing checkpoint is incompatible with the new logic?

  7. A streaming job's state grows continuously and batches slow down. How would you diagnose and redesign it?

  8. How would you design a stream-stream join with bounded state and a justified late-data policy?

  9. How would you backfill historical data while a live ingestion pipeline continues to run?

  10. How would you prove that an incremental pipeline has neither lost nor double-counted business events?

  11. Two MERGE jobs intermittently conflict on the same Delta table. How would you reduce conflicts without weakening correctness?

  12. When would you choose Serializable rather than WriteSerializable isolation, and what tradeoff would you test?

  13. How would you evaluate a Delta table feature upgrade when several engines and older runtimes read the table?

  14. How would you roll out a column rename or type change across producers, tables, streams, and downstream consumers?

  15. How would you select clustering keys and verify that a table-layout change actually helps the workload?

  16. A join is dominated by one hot key. How would you distinguish a semantic data problem from execution skew and choose a remedy?

  17. How would your investigation differ for driver out-of-memory failures and executor out-of-memory failures?

  18. How would you benchmark Photon and explain a workload that shows little benefit?

  19. A dashboard is slow only during business-hour concurrency peaks. How would you separate queueing, compute limits, and query inefficiency?

  20. How would you choose between serverless and classic compute for a workload with strict dependency, network, latency, and cost requirements?

  21. How would you migrate externally managed data into Unity Catalog managed tables while preserving consumers and rollback options?

  22. How would you prevent direct cloud-storage access from bypassing Unity Catalog policies?

  23. What must a cross-region disaster-recovery plan preserve beyond table files, and how would you test its RPO and RTO?

  24. How would you respond to an accidental destructive table change when time travel is available but retention is limited?

  25. How would you design and verify a sensitive-record deletion process across current tables, retained files, derived datasets, and downstream copies?

  26. Which freshness, completeness, correctness, and operational signals would you include in a production data pipeline's service objectives?

  27. How would you combine lineage and audit evidence to investigate an unexpected exposure of a sensitive column?

  28. How would you promote a bundle through development, staging, and production while keeping configuration and rollback under control?

  29. How would you secure unattended deployments and job execution without tying them to one employee's credentials?

  30. How would you build a failure-injection test that proves a pipeline can retry safely after a partial write?

  31. How would you upgrade the runtime and libraries of a critical job without assuming that passing unit tests guarantees compatibility?

  32. How would you migrate legacy DBFS-root or mount-based workloads to governed storage without breaking their dependencies?

  33. How would you decide between governed data sharing, federation, and copying extracts for an external consumer?

  34. What compatibility and governance questions must be answered before multiple engines access the same open table data?

  35. How would you promote and roll back a registered ML model while preserving evidence about its training run and approvals?

  36. How would you prevent future information from leaking into historical training features or model evaluation?

  37. Databricks usage doubled while row volume barely changed. How would you isolate the cost driver before changing compute size?

  38. How would you coordinate writes to two tables and an external API when not every destination can participate in one transaction?

  39. How would you make a historical business report reproducible after source corrections, code changes, and table retention expiry?

  40. How would you review a proposed lakehouse design that promises zero duplicates, instant recovery, and lower costs without measured evidence?

Databricks Interview Questions and Answers

The answers follow the same order as the question bank. They explain the expected behavior, then show an example or trade-off where it clarifies the decision. Read code alongside its stated schema, compute, cloud, and runtime assumptions before adapting it.

Databricks Interview Questions and Answers for Beginners

The beginner answers explain the building blocks of a Databricks workflow. Examples make data types, transformation results, table behavior, and execution timing explicit without assuming that every notebook runs on the same compute configuration.

1. What is Databricks, and what does it add beyond open-source Apache Spark?

Databricks is a managed platform for data engineering, analytics, and AI that combines distributed processing with storage, governance, collaboration, and operational services. Apache Spark is a processing engine; Databricks supplies a broader environment in which teams develop and operate workloads.

For example, a team can use Spark transformations to clean orders, Delta tables to store transactional data, Unity Catalog to control access, notebooks to investigate results, and Lakeflow Jobs to schedule production processing. Databricks also provides SQL warehouses and managed MLflow capabilities.

The distinction matters when assigning responsibilities: Spark explains much of the execution model, while workspace permissions, managed compute, billing, and deployment workflows are platform concerns. An open-source Spark feature is not automatically available on every Databricks compute configuration.

2. How does a lakehouse differ from a data lake and a traditional data warehouse?

A lakehouse combines the flexible storage associated with data lakes with table reliability, governance, and analytical capabilities associated with data warehouses.

A data lake commonly stores files in object storage, including raw and unstructured data. Files alone do not supply a shared transactional table contract. A traditional warehouse emphasizes governed, structured tables and SQL analytics, often with a more tightly managed storage and serving architecture. Modern products can blur these boundaries.

In a Databricks lakehouse, Delta Lake provides transactional tables over data files, Unity Catalog governs assets, and separate compute serves engineering, SQL, and ML workloads. For example, raw event files can become validated event tables and then dashboard aggregates. The architecture still requires explicit quality rules, ownership, and workload design; storing Parquet files does not establish those properties by itself.

3. Why does separating compute from storage matter in Databricks?

Separating compute from storage allows durable data to outlive the resources processing it. Compute can be stopped, replaced, or resized without treating its local disks as the permanent copy of a table.

For example, an ingestion job and a SQL warehouse can access the same governed table using different compute resources. This avoids requiring one continuously running cluster to serve every workload and lets each workload scale according to its needs.

The separation also creates practical boundaries. Stopping compute does not eliminate object-storage charges, and local caches or temporary files may disappear. Storage permissions, network access, and table concurrency still need configuration. Classic and serverless deployments place resources differently, so the cloud-specific architecture must be checked rather than assuming all processing occurs in the customer's cloud account.

4. How are a Databricks account and a workspace different?

A Databricks account is the organization-level management boundary; a workspace is an environment where people and automation develop and run workloads. One account can contain multiple workspaces.

Account-level administration includes identities, workspace management, usage management, and Unity Catalog metastore relationships. A workspace contains working assets and interfaces such as notebooks, jobs, and compute configurations. Organizations might separate development and production into different workspaces while managing identities centrally.

A workspace is not necessarily a completely isolated copy of the organization's data. Eligible workspaces can share access through a Unity Catalog metastore, subject to permissions and workspace bindings. Account administration, workspace access, and permission to read a particular table therefore answer different questions and should not be treated as interchangeable privileges.

5. What can you do in a Databricks notebook, and why is notebook execution order important?

A Databricks notebook combines executable code, explanatory Markdown, results, and visualizations in a collaborative document. Depending on its attached compute, it can support languages such as Python, SQL, Scala, and R, and can be run interactively or as a job task.

Execution order matters because a cell can depend on variables, temporary views, imports, or configuration created by an earlier execution. The visible top-to-bottom order does not prove that the current session was executed that way. Editing an upstream cell also does not automatically refresh every downstream result.

For a reproducible workflow, define dependencies explicitly, keep initialization near the start, and verify a clean top-to-bottom run. Move reusable logic into functions or modules, and avoid relying on hidden session state left by exploratory work.

6. What is Databricks Runtime, and why should a project record its runtime version?

Databricks Runtime is the versioned set of core software components used by configured Databricks compute, including Apache Spark and integrated libraries and optimizations. A runtime version is more specific than saying that a workload uses Spark.

Record it because changes can affect API availability, SQL behavior, Python dependencies, performance, and compatibility with enabled table features. A reproducible job configuration should also capture installed libraries and relevant settings; the runtime number alone is insufficient.

For classic production jobs, an appropriate supported LTS release can provide a stable upgrade baseline, but upgrades still need workload tests. Serverless environments use their own managed environment and version controls rather than exposing every classic runtime setting. Upstream Spark's latest documentation should not be mistaken for the Spark version bundled with a project's runtime.

7. How do all-purpose compute, jobs compute, serverless compute, and SQL warehouses serve different workloads?

These options differ by workload and management model, and they are not four mutually exclusive categories.

  • All-purpose compute: reusable interactive compute for exploration, development, and collaboration.

  • Jobs compute: compute configured for automated job execution, commonly created for a run and terminated afterward; compatible tasks may share it within a job.

  • Serverless compute: a managed provisioning model available for supported notebooks, jobs, pipelines, and SQL workloads, reducing infrastructure configuration.

  • SQL warehouses: compute optimized for SQL queries, dashboards, and BI connections; serverless warehouses are one option.

Choose using language and library requirements, access mode, networking, startup behavior, concurrency, and measured cost. A SQL warehouse is not a general replacement for arbitrary Python execution, and serverless does not support every setting available on classic compute.

8. What do the driver and executors do in a Spark application?

The driver coordinates a Spark application, while executors perform distributed work. The driver builds and schedules work, tracks task progress, and receives results needed by the application. Executors run tasks over data partitions and may cache data or write shuffle and output data.

For example, when a query aggregates transactions by store, executors read and process partitions; the driver coordinates the stages rather than loading every transaction into one Python process.

This distinction helps explain failures. A large collect() can exhaust driver memory even when executor capacity is sufficient. Conversely, an oversized partition or expensive task can exhaust executor memory. Spark can use memory and disk; distributed processing does not imply that every dataset must fit entirely in RAM.

9. What is SparkSession, and how is it used in a Databricks notebook?

SparkSession is the entry point for Spark's DataFrame and SQL APIs. It provides methods to read data, create DataFrames, run SQL, and access session configuration and catalog operations.

A Databricks notebook connected to Spark-capable compute normally provides an existing session named spark; creating a separate local Spark application is unnecessary for ordinary notebook work.

PySpark example

orders = spark.createDataFrame(
    [(101, 25), (102, 40)],
    "order_id INT, amount INT"
)
orders.createOrReplaceTempView("demo_orders")
spark.sql("SELECT SUM(amount) AS total FROM demo_orders").show()
orders = spark.createDataFrame(
    [(101, 25), (102, 40)],
    "order_id INT, amount INT"
)
orders.createOrReplaceTempView("demo_orders")
spark.sql("SELECT SUM(amount) AS total FROM demo_orders").show()
orders = spark.createDataFrame(
    [(101, 25), (102, 40)],
    "order_id INT, amount INT"
)
orders.createOrReplaceTempView("demo_orders")
spark.sql("SELECT SUM(amount) AS total FROM demo_orders").show()

For this two-row illustrative dataset, the expected total is 65. The temporary view belongs to the session and does not create a durable table. The session also does not grant access to data that the executing identity is not authorized to read.

10. How does a Spark DataFrame differ from an RDD and a local pandas DataFrame?

A Spark DataFrame is a distributed, schema-aware collection expressed through a query plan. Spark can optimize its relational operations because it knows the columns, types, and expressions involved.

An RDD is a lower-level distributed collection with operations over individual elements. It offers different control but exposes less relational information to Spark's SQL optimizer; some Databricks compute or access modes restrict RDD APIs.

A local pandas DataFrame normally resides in one Python process and is convenient for data that fits that process's memory. Calling toPandas() on a Spark DataFrame transfers the result into driver memory; it does not keep the result distributed. Keep large processing in Spark, and convert only a bounded, appropriately sized result when a local library genuinely needs pandas.

11. How are Spark SQL queries related to DataFrame transformations?

Spark SQL and DataFrame transformations are two ways to express relational operations to Spark's SQL execution engine. A SQL query returns a DataFrame, and a DataFrame can be exposed as a temporary view for SQL.

For example, in a Spark-capable notebook, these expressions describe the same filtered projection:

PySpark example

items = spark.createDataFrame(
    [(1, 5), (2, 0)], "item_id INT, stock INT"
)
items.createOrReplaceTempView("demo_items")
via_api = items.filter("stock > 0").select("item_id")
via_sql = spark.sql(
    "SELECT item_id FROM demo_items WHERE stock > 0"
)
items = spark.createDataFrame(
    [(1, 5), (2, 0)], "item_id INT, stock INT"
)
items.createOrReplaceTempView("demo_items")
via_api = items.filter("stock > 0").select("item_id")
via_sql = spark.sql(
    "SELECT item_id FROM demo_items WHERE stock > 0"
)
items = spark.createDataFrame(
    [(1, 5), (2, 0)], "item_id INT, stock INT"
)
items.createOrReplaceTempView("demo_items")
via_api = items.filter("stock > 0").select("item_id")
via_sql = spark.sql(
    "SELECT item_id FROM demo_items WHERE stock > 0"
)

Both results contain item_id = 1 when evaluated. Choose the interface that makes the transformation clearest. Equivalent built-in expressions can receive similar optimization, but different UDFs, casts, or query shapes can produce different plans; language choice alone does not guarantee identical performance.

12. What does lazy evaluation mean in Spark?

Lazy evaluation means Spark usually records transformations as a plan instead of immediately computing every resulting row. Execution is triggered when an action needs a result, allowing Spark to optimize the combined plan first.

For example, defining a filter followed by a column selection lets the engine consider both operations together rather than necessarily materializing a complete intermediate dataset. explain() can reveal the planned execution without returning the dataset itself.

Laziness also affects debugging: a failure involving data values may appear at show(), count(), or a write rather than where the transformation was declared. It is not a promise that absolutely no work happens beforehand; schema inference, metadata access, and analysis can inspect inputs or raise errors before the main data-processing action.

13. What is the difference between a Spark transformation and an action?

A transformation describes a new distributed result; an action requests execution to produce a result or write data. DataFrame transformations such as select, filter, and join return new DataFrames without mutating the original source.

In a Spark-capable notebook:

PySpark example

numbers = spark.range(0, 6)
even_numbers = numbers.filter("id % 2 = 0")
row_count = even_numbers.count()
numbers = spark.range(0, 6)
even_numbers = numbers.filter("id % 2 = 0")
row_count = even_numbers.count()
numbers = spark.range(0, 6)
even_numbers = numbers.filter("id % 2 = 0")
row_count = even_numbers.count()

The filter is a transformation. DataFrame.count() is an action returning the Python integer 3 for this example. A write is also an action even though it need not return rows to the driver.

Names require context: groupBy(...).count() constructs an aggregated DataFrame, whereas DataFrame.count() returns a scalar. Repeated actions can repeat upstream work, so adding counts after every step can be expensive.

14. Why might you define an explicit schema instead of relying on schema inference?

An explicit schema makes the expected columns and types a deliberate contract rather than a guess based on observed input. It can avoid inference work and prevent an identifier such as 0007 from becoming an integer or a sparse column from receiving an unintended type.

For this illustrative CSV read, /Volumes/demo/ingest/landing must already be an accessible Unity Catalog volume, and the file must have matching customer_id,amount headers in that order. Use compatible Spark compute.

PySpark example

incoming = (spark.read
    .schema("customer_id STRING, amount DECIMAL(12,2)")
    .option("header", True)
    .option("enforceSchema", False)
    .option("mode", "FAILFAST")
    .csv("/Volumes/demo/ingest/landing/orders.csv"))
incoming = (spark.read
    .schema("customer_id STRING, amount DECIMAL(12,2)")
    .option("header", True)
    .option("enforceSchema", False)
    .option("mode", "FAILFAST")
    .csv("/Volumes/demo/ingest/landing/orders.csv"))
incoming = (spark.read
    .schema("customer_id STRING, amount DECIMAL(12,2)")
    .option("header", True)
    .option("enforceSchema", False)
    .option("mode", "FAILFAST")
    .csv("/Volumes/demo/ingest/landing/orders.csv"))

FAILFAST rejects records the CSV parser classifies as corrupt, not every invalid row. Field-count mismatches can still yield nulls or discarded extra fields; column pruning also affects parsing. Required-field, field-count, and business checks such as positive amounts remain separate.

15. How do select, filter, and withColumn change a PySpark DataFrame?

select chooses or computes output columns, filter keeps rows satisfying a condition, and withColumn adds a column or replaces one with the same name. Each returns a new DataFrame; none edits the original dataset in place.

In a Spark-capable notebook:

PySpark example

from pyspark.sql import functions as F

stock = spark.createDataFrame(
    [("A", 4, 3), ("B", 0, 8)],
    "sku STRING, quantity INT, unit_price INT"
)
result = (stock
    .filter(F.col("quantity") > 0)
    .withColumn("value", F.col("quantity") * F.col("unit_price"))
    .select("sku", "value"))
from pyspark.sql import functions as F

stock = spark.createDataFrame(
    [("A", 4, 3), ("B", 0, 8)],
    "sku STRING, quantity INT, unit_price INT"
)
result = (stock
    .filter(F.col("quantity") > 0)
    .withColumn("value", F.col("quantity") * F.col("unit_price"))
    .select("sku", "value"))
from pyspark.sql import functions as F

stock = spark.createDataFrame(
    [("A", 4, 3), ("B", 0, 8)],
    "sku STRING, quantity INT, unit_price INT"
)
result = (stock
    .filter(F.col("quantity") > 0)
    .withColumn("value", F.col("quantity") * F.col("unit_price"))
    .select("sku", "value"))

The expected result is one row, A, 12, when an action evaluates it. stock still has both original rows and three original columns. Select only columns that downstream work needs, and use expressions from the appropriate DataFrame rather than unrelated column references.

16. What does groupBy do, and how do aggregate functions summarize data?

groupBy identifies groups of rows with the same key values; an aggregate then produces summary values for each group. Functions such as sum, avg, min, max, and count answer different questions and change the result's level of detail.

PySpark example

from pyspark.sql import functions as F

sales = spark.createDataFrame(
    [("east", 10), ("east", 20), ("west", 5)],
    "region STRING, amount INT"
)
summary = sales.groupBy("region").agg(
    F.sum("amount").alias("revenue"),
    F.count("*").alias("sale_count")
)
from pyspark.sql import functions as F

sales = spark.createDataFrame(
    [("east", 10), ("east", 20), ("west", 5)],
    "region STRING, amount INT"
)
summary = sales.groupBy("region").agg(
    F.sum("amount").alias("revenue"),
    F.count("*").alias("sale_count")
)
from pyspark.sql import functions as F

sales = spark.createDataFrame(
    [("east", 10), ("east", 20), ("west", 5)],
    "region STRING, amount INT"
)
summary = sales.groupBy("region").agg(
    F.sum("amount").alias("revenue"),
    F.count("*").alias("sale_count")
)

On Spark-capable compute, the expected summaries are east: 30, 2, and west: 5, 1; row order is unspecified. Grouping does not preserve every original transaction. Also distinguish counting rows from counting non-null values: count("amount") excludes null amounts, while count("*") includes those rows.

17. How does an inner join differ from a left outer join?

An inner join returns matching row combinations from both inputs. A left outer join also preserves unmatched left-side rows, filling the right-side columns with NULL.

This self-contained SQL example can run in a Databricks SQL warehouse or Spark SQL session:

SQL example

WITH orders(order_id, customer_id) AS (
  VALUES (10, 1), (11, 9)
), customers(customer_id, customer_name) AS (
  VALUES (1, 'Mira')
)
SELECT o.order_id, c.customer_name
FROM orders o
LEFT JOIN customers c ON o.customer_id = c.customer_id
ORDER BY

WITH orders(order_id, customer_id) AS (
  VALUES (10, 1), (11, 9)
), customers(customer_id, customer_name) AS (
  VALUES (1, 'Mira')
)
SELECT o.order_id, c.customer_name
FROM orders o
LEFT JOIN customers c ON o.customer_id = c.customer_id
ORDER BY

WITH orders(order_id, customer_id) AS (
  VALUES (10, 1), (11, 9)
), customers(customer_id, customer_name) AS (
  VALUES (1, 'Mira')
)
SELECT o.order_id, c.customer_name
FROM orders o
LEFT JOIN customers c ON o.customer_id = c.customer_id
ORDER BY

The expected rows are 10, Mira and 11, NULL. Replacing LEFT JOIN with INNER JOIN removes order 11. A left join does not guarantee one output row per left row: duplicate right-side keys multiply matches. A later filter requiring a right-side value can also remove the unmatched rows.

18. How do SQL NULL values affect comparisons, filters, and counts?

NULL represents a missing or unknown value, not zero or an empty string. Ordinary comparisons involving null usually return unknown, so WHERE retains only rows whose predicate is true. Use IS NULL, not = NULL, to find missing values.

In Databricks SQL or Spark SQL:

SQL example

WITH sample(value) AS (
  VALUES (10), (CAST(NULL AS INT)), (20)
)
SELECT COUNT(*) AS all_rows,
       COUNT(value) AS known_values,
       SUM(value) AS total
FROM

WITH sample(value) AS (
  VALUES (10), (CAST(NULL AS INT)), (20)
)
SELECT COUNT(*) AS all_rows,
       COUNT(value) AS known_values,
       SUM(value) AS total
FROM

WITH sample(value) AS (
  VALUES (10), (CAST(NULL AS INT)), (20)
)
SELECT COUNT(*) AS all_rows,
       COUNT(value) AS known_values,
       SUM(value) AS total
FROM

The expected result is 3, 2, 30. Most aggregates ignore null inputs, while COUNT(*) counts rows. A filter such as value <> 10 does not retain the null row. Spark's null-safe equality operator, <=>, treats two nulls as equal when that is the intended comparison policy.

19. How is a temporary view different from a persistent table?

A local temporary view gives a session-scoped name to a query or DataFrame; it does not materialize a durable copy of the rows. Its lifetime is tied to the Spark session, so another independent job should not assume that the view exists.

A persistent table has catalog metadata and durable table data that authorized sessions can access beyond the lifetime of the creating notebook. Unity Catalog tables also participate in governance through the catalog namespace and privileges.

Use a temporary view to combine SQL and DataFrame logic during one workflow. Use a table when later jobs or consumers need a durable dataset. A persistent ordinary view is another option: it saves a query definition, which should not be confused with storing the query's results in a table.

20. What does Delta Lake add to a folder of Parquet files?

Delta Lake adds a transactional table layer to data files, commonly Parquet. Its transaction log defines the committed table state instead of asking readers to treat every file found in a directory as current data.

This enables atomic commits, consistent reads, schema enforcement, supported updates and merges, and access to retained historical versions. Batch and streaming workloads can use the same table abstraction rather than maintaining unrelated file-management conventions.

For example, rewriting several files during an update should not expose a half-finished replacement to readers. A Delta-aware reader follows the committed snapshot. Reading the underlying folder as plain Parquet can ignore that snapshot and produce incorrect results. Delta still needs appropriate retention, permissions, and business validation; it is not automatically a backup or a deduplication policy.

21. What do ACID properties mean for a Delta table write?

ACID describes the guarantees around a Delta transaction:

  • Atomicity: its changes become visible together, or no new committed table state is published.

  • Consistency: the committed state respects enforced schema and constraints.

  • Isolation: concurrent work follows the supported isolation rules instead of exposing partial writes.

  • Durability: committed changes are recorded in durable storage.

For example, readers should see a valid snapshot while another process updates the table. A conflicting writer may fail safely and require a correctly designed retry.

These properties do not invent missing business rules. They do not automatically make order IDs unique or make separately executed notebook writes one transaction. Databricks also supports eligible multi-statement, multi-table transactions with specific table and compute requirements; that capability must be explicitly used and verified.

22. What information does the Delta transaction log coordinate?

The Delta transaction log coordinates which data belongs to each committed table version and how that data must be interpreted. It records actions such as adding or removing logical files, together with table metadata, schema, and protocol or feature requirements.

A reader uses this information to construct a consistent snapshot. File statistics can help avoid reading irrelevant data, and log checkpoints summarize state so readers need not replay every historical commit. These table-log checkpoints are distinct from Structured Streaming query checkpoints.

For example, an update can replace files or use supported table features while preserving the logical table contract. Removing a file from the current snapshot does not necessarily delete it physically immediately. Applications should use compatible table APIs, never manually edit or delete the transaction log.

23. How does schema enforcement differ from schema evolution?

Schema enforcement checks a write against a table's schema and rejects incompatible data unless a supported conversion or explicitly enabled evolution applies. Schema evolution intentionally changes that schema as requirements change.

For example, a new nullable campaign_code column might be an approved additive change. Enabling evolution for the relevant write can admit it, whereas enforcement without that change protects the existing contract. A string suddenly appearing in a numeric field should be investigated rather than automatically accepted as harmless evolution.

Input inference, Auto Loader's schema tracking, and the target table's schema are related but separate controls. Changes may require stream restarts and downstream updates. Prefer deliberate, scoped evolution with compatibility tests over a blanket setting intended to make every schema error disappear.

24. What is Delta time travel, and what is table history used for?

Delta time travel reads a retained earlier table snapshot by version or timestamp. Table history describes operations that changed the table, helping explain when a change occurred and which operation produced it.

For an existing accessible Delta table demo.sales.orders, these are read-only SQL examples. Version 4 must exist and remain readable:

SQL example

DESCRIBE HISTORY demo.sales.orders LIMIT 5;

SELECT COUNT(*) AS rows_at_version_4
FROM demo.sales.orders VERSION AS OF 4

DESCRIBE HISTORY demo.sales.orders LIMIT 5;

SELECT COUNT(*) AS rows_at_version_4
FROM demo.sales.orders VERSION AS OF 4

DESCRIBE HISTORY demo.sales.orders LIMIT 5;

SELECT COUNT(*) AS rows_at_version_4
FROM demo.sales.orders VERSION AS OF 4

The count depends on that table's actual data; no particular result is assumed. Historical reads require both sufficient log information and the old data files. Retention cleanup can make a listed version unreadable, so history is not an archival backup. Reading an older version also does not replace the current version.

25. How do Unity Catalog managed tables differ from external tables?

For a Unity Catalog managed table, Databricks manages the table's metadata and the underlying storage lifecycle, with managed-table optimization capabilities where enabled. For an external table, Unity Catalog manages the registered metadata and governed access, while the organization controls the external storage location and data lifecycle.

The lifecycle difference is important: dropping an external table removes its registration without deleting its data files. Dropping a managed table makes its data subject to the platform's managed deletion and recovery lifecycle, rather than preserving it indefinitely as external data.

Managed tables are the recommended default for supported new workloads. External tables suit specific existing-storage or interoperability requirements. Direct cloud-file access is governed by cloud permissions and can bypass Unity Catalog, so an external registration alone does not secure every access path.

26. What are catalogs, schemas, and tables in the Unity Catalog namespace?

Unity Catalog organizes table names in a three-level namespace: catalog.schema.table. A catalog is a broad grouping and governance boundary, a schema groups related objects within it, and a table is the named tabular dataset.

For example, in analytics.retail.daily_sales, analytics is the catalog, retail is the schema, and daily_sales is the table. Schemas can also contain objects such as views, functions, and volumes; they are not simply filesystem folders.

Fully qualified names make dependencies clearer and reduce accidental reads from a different current catalog or schema. This is especially useful when the same short table name exists in development and production. Namespace resolution and authorization remain separate: knowing an object's full name does not grant permission to query it.

27. Why are table permissions different from permission to open a notebook or use compute?

Notebook, compute, and table permissions protect different resources. Permission to open or edit a notebook controls the code artifact. Permission to use compute controls execution capacity. Unity Catalog privileges determine whether the execution identity can access governed data.

For a normal table read, the principal generally needs USE CATALOG on the parent catalog, USE SCHEMA on the parent schema, and SELECT on the table, whether granted directly or through supported inheritance. Workspace bindings and other configuration can impose additional restrictions.

A shared notebook can therefore open successfully but fail when it queries a table. Likewise, an automated job may run as a different identity from its author. Diagnose the effective execution identity and the specific denied resource instead of granting broad workspace or administrator privileges as a shortcut.

28. What is a Unity Catalog volume, and when would you use one instead of a table?

A Unity Catalog volume governs file-oriented data and provides a named storage location with access controls. Use one for assets such as incoming CSV files, documents, images, library artifacts, or operational checkpoint files. Use a table for a governed dataset that consumers query as rows and columns.

An illustrative file path is /Volumes/demo/ingest/landing/incoming/orders.csv. Here demo is the catalog, ingest the schema, and landing the volume. Those objects, the required permissions, and compatible compute must already exist; writing that path in code does not create them.

A CSV can be read from a volume and transformed into a separate table. The table's storage must not be registered inside the volume. Managed and external volumes also differ in who controls their underlying storage lifecycle.

29. Why are DBFS root and DBFS mounts not the default choice for a new Databricks design?

DBFS root and DBFS mounts are deprecated, and Databricks does not recommend them for new designs. Legacy examples often rely on workspace-wide file patterns or separately configured storage credentials that do not provide the intended Unity Catalog governance model.

Use Unity Catalog tables for tabular data and volumes for governed files. Use properly configured external locations and storage credentials when connecting existing cloud storage, and workspace files where appropriate for code and small development artifacts.

For example, replace a new /mnt/... ingestion design with an authorized volume or external-location approach rather than copying an old mount setup. Existing workloads need a dependency-aware migration: inventory readers, writers, permissions, and checkpoint paths before changing them. A legacy path continuing to work is not evidence that it is a suitable production default.

30. What do bronze, silver, and gold represent in a medallion architecture?

Bronze, silver, and gold describe progressively refined data products rather than mandatory product features or three fixed physical databases.

Layer

Main purpose

Example

Bronze

Preserve ingested source data and useful arrival metadata

Raw order events with ingestion timestamps

Silver

Validate, standardize, reconcile, and apply explicit deduplication rules

Typed orders with documented customer keys

Gold

Serve business-specific models and metrics

Daily revenue by store

Bronze supports investigation and replay when its retention permits. Silver should make quality decisions visible, including treatment of rejected records. Gold should define business semantics rather than merely rename cleaned tables.

The layers can be implemented using different tables or schemas as appropriate. Their names do not guarantee accuracy, atomic propagation across layers, or universal suitability for every workload.

31. How does batch processing differ from Structured Streaming?

Batch processing works on a bounded input and completes. Structured Streaming expresses incremental processing over a potentially unbounded source using Spark's DataFrame and SQL model, with progress and state maintained across processing steps.

For example, a batch can summarize yesterday's delivered files once, while a stream continually incorporates newly arriving order events. Structured Streaming commonly uses micro-batches; Databricks also offers real-time mode for supported workloads. A stream does not necessarily require one permanently running process: supported bounded-incremental triggers can process currently available data and then stop.

Streaming adds concerns such as late events, checkpoints, state growth, restart compatibility, and sink behavior. Similar syntax does not make every batch operation valid on an unbounded stream. End-to-end correctness depends on the source and sink contract, not simply choosing readStream.

32. What is Auto Loader, and what type of ingestion problem does it solve?

Auto Loader is Databricks' incremental file-ingestion capability, exposed through the Structured Streaming cloudFiles source. It discovers newly arriving files in supported storage and tracks ingestion progress so a pipeline need not repeatedly process the entire directory.

A common example is ingesting daily JSON exports from an application into a bronze Delta table. Auto Loader can support schema inference and evolution, while checkpoint metadata supports recovery. Lakeflow pipelines can manage some of these operational details.

File ingestion and business-event deduplication are different problems. If two different files contain the same order event, discovering each file once does not remove the duplicate event. Define a reliable file-arrival and overwrite policy, monitor schema surprises, and do not assume discovery order equals event order. Appropriate storage access and durable state are still prerequisites.

33. What is a streaming checkpoint, and why does each query need its own location?

A streaming checkpoint is durable recovery information for one streaming query. It records source progress and committed batches, query identity, and state-store information when the query maintains state.

Reusing the same checkpoint for a compatible restart lets the query resume from its recorded progress. Different queries must use different checkpoint locations because their source positions, state, and commits are not interchangeable.

Place checkpoints in a durable, authorized storage location outside table data directories, and protect them from unrelated cleanup. Deleting a checkpoint or switching to a fresh location starts a new processing history and can cause replay; it is not a harmless reset. Some query changes are incompatible with the existing checkpoint. A checkpoint also cannot, by itself, make effects on an external API exactly-once.

34. How does event time differ from processing time?

Event time is when an event occurred according to its recorded timestamp; processing time is when the system handles it. They differ because networks, devices, files, and upstream systems can delay delivery or send records out of order.

For example, a purchase made at 09:58 but ingested at 10:07 belongs to the 09:00 sales hour under event-time reporting, but to the 10:00 ingestion hour under processing-time reporting. Neither interpretation is universally correct; the metric's business definition decides.

Stateful event-time queries often use watermarks to bound late-data handling and state retention. A watermark advances with observed event-time progress, not simply elapsed wall-clock time. Validate timestamp parsing and time-zone assumptions before using an event-time field, and define how excessively late or invalid timestamps are handled.

35. How do jobs, tasks, and triggers fit together in Lakeflow Jobs?

In Lakeflow Jobs, a job is the overall workflow, a task is a unit of work inside that workflow, and a trigger determines when a run starts. Task dependencies form a directed acyclic graph that controls execution order and possible parallelism.

For example, one job can ingest files, validate the ingested data, and publish a daily summary. Validation depends on ingestion; publication should depend on successful validation. A schedule can start the workflow each morning, while a manual or API-triggered run can handle an authorized rerun.

Task configuration also includes details such as compute, parameters, retries, and timeouts. A retry does not automatically undo previous writes, so task outputs must support safe repetition. Successful orchestration reports execution status, not proof that the resulting business data is correct.

36. Why should notebooks and jobs use validated parameters rather than hard-coded values?

Validated parameters let the same code run safely for different dates, environments, or input ranges without editing its source. Validation catches missing values, bad types, unsupported environments, and unintended ranges before expensive or data-changing work begins.

For a Python notebook on compatible Databricks compute, a date widget can be parsed explicitly:

Python example

from datetime import date

dbutils.widgets.text("run_date", "")
raw_date = dbutils.widgets.get("run_date")
if not raw_date:
    raise ValueError("run_date is required")
run_date = date.fromisoformat(raw_date)
from datetime import date

dbutils.widgets.text("run_date", "")
raw_date = dbutils.widgets.get("run_date")
if not raw_date:
    raise ValueError("run_date is required")
run_date = date.fromisoformat(raw_date)
from datetime import date

dbutils.widgets.text("run_date", "")
raw_date = dbutils.widgets.get("run_date")
if not raw_date:
    raise ValueError("run_date is required")
run_date = date.fromisoformat(raw_date)

A value such as 2026-10-01 becomes a Python date; an invalid date raises an error. Additional rules should check the permitted processing window. Widgets provide strings, not trusted typed input. Use SQL parameter markers for values on supported runtimes rather than concatenating unchecked input into SQL, and keep secrets out of ordinary parameters.

37. How do Lakeflow pipelines differ from manually orchestrating transformation notebooks?

Lakeflow pipelines let developers declare datasets and their transformations while the platform manages dependencies, execution, and incremental processing where supported. Manually orchestrated notebooks require the team to explicitly arrange execution and manage more of the associated operational state.

For example, a declared streaming table can feed a materialized view, with the pipeline deriving their dependency relationship. The developer still owns transformation correctness, quality rules, permissions, and an appropriate refresh strategy. Incremental maintenance is conditional; it is not a guarantee that every query avoids a full recomputation.

Lakeflow Jobs can orchestrate a pipeline alongside other tasks, so these tools are complementary. Current documentation describes Spark Declarative Pipelines on Lakeflow; older material may use Delta Live Tables/DLT or Lakeflow Declarative Pipelines. Databricks extensions should not be assumed available in open-source Spark.

38. What does MLflow track during a machine-learning experiment?

MLflow experiment tracking organizes model-development work into runs and experiments. A run can record parameters, evaluation metrics, tags, code-related metadata, and artifacts such as plots or a trained model. This makes comparisons more reliable than keeping results only in notebook output.

For example, two training runs can log different regularization settings, their validation scores, and the corresponding model artifacts. A useful comparison also records the evaluation dataset or snapshot, feature logic, environment, and other conditions that affect reproducibility.

Some integrations provide autologging, but teams should verify what is actually captured rather than assume that every dependency and input is preserved. Tracking a successful run or registering a model does not establish business approval, production deployment, or freedom from data leakage.

39. How should a notebook access a secret without embedding the value in its source code?

A notebook should retrieve a secret at runtime from an authorized secret store instead of embedding its value in source code, widgets, or version control. In Databricks, one supported pattern uses an existing secret scope and the secrets utility.

This illustrative Python example assumes that the scope and key already exist and the execution identity has permission to read them:

Python example

api_token = dbutils.secrets.get(
    scope="vendor-ingestion",
    key="api-token"
)
api_token = dbutils.secrets.get(
    scope="vendor-ingestion",
    key="api-token"
)
api_token = dbutils.secrets.get(
    scope="vendor-ingestion",
    key="api-token"
)

Pass the value only to the intended authenticated client; do not print it or include it in diagnostic output. Redaction is not a security boundary because authorized secret readers can access the value. Use least-privilege identities and rotation, and prefer Unity Catalog's supported credential mechanisms for governed cloud-storage access.

40. What are the main sources of Databricks workload cost, and why is runtime alone not a complete cost measure?

Workload cost includes billable Databricks usage and, depending on the deployment, cloud infrastructure, storage, requests, networking or egress, and related services. Idle capacity, startup, retries, unnecessary scans, and operational effort can all affect the total.

Runtime alone ignores the rate and quantity of resources consumed. A job that finishes twice as quickly on substantially more expensive capacity can cost more, while a longer job may miss a business deadline even if its compute charge is lower.

Use billing usage records, job metadata, and cloud cost evidence to attribute spend to a workload. DBUs are usage units, not automatically the complete invoice. Compare cost per successful, correct workload outcome under comparable data and cache conditions, and include reliability and latency requirements rather than optimizing duration in isolation.

Databricks Interview Questions and Answers for Intermediate

The intermediate answers connect code with execution and data-management behavior. They state the conditions behind a result, including keys, ordering, state, schema, and write semantics, and distinguish a local fix from a reliable pipeline design.

41. How would you read a CSV with an explicit schema and separate malformed records from valid data?

Use an explicit schema, retain parser failures, and apply business validation separately. In this illustrative Databricks PySpark example, the existing Unity Catalog volume lab.ingest.landing contains a CSV with header order_id,amount; the user needs volume-read access and supported compute. The schema includes Spark's corrupt-record field. Materializing the full cached input before filtering also avoids querying only the corrupt-record column directly from CSV.

Python example

from pyspark.sql import functions as F

raw = (spark.read
    .schema("order_id LONG, amount DECIMAL(12,2), _corrupt_record STRING")
    .option("header", "true")
    .option("enforceSchema", "false")
    .option("mode", "PERMISSIVE")
    .option("columnNameOfCorruptRecord", "_corrupt_record")
    .csv("/Volumes/lab/ingest/landing/orders.csv")
    .cache())
raw.count()  # Materialize all cached columns before branching.
valid_flag = F.coalesce(
    F.col("_corrupt_record").isNull()
    & F.col("order_id").isNotNull()
    & (F.col("amount") >= 0), F.lit(False))
valid = raw.filter(valid_flag).drop("_corrupt_record")
rejected = raw.filter(~valid_flag)
from pyspark.sql import functions as F

raw = (spark.read
    .schema("order_id LONG, amount DECIMAL(12,2), _corrupt_record STRING")
    .option("header", "true")
    .option("enforceSchema", "false")
    .option("mode", "PERMISSIVE")
    .option("columnNameOfCorruptRecord", "_corrupt_record")
    .csv("/Volumes/lab/ingest/landing/orders.csv")
    .cache())
raw.count()  # Materialize all cached columns before branching.
valid_flag = F.coalesce(
    F.col("_corrupt_record").isNull()
    & F.col("order_id").isNotNull()
    & (F.col("amount") >= 0), F.lit(False))
valid = raw.filter(valid_flag).drop("_corrupt_record")
rejected = raw.filter(~valid_flag)
from pyspark.sql import functions as F

raw = (spark.read
    .schema("order_id LONG, amount DECIMAL(12,2), _corrupt_record STRING")
    .option("header", "true")
    .option("enforceSchema", "false")
    .option("mode", "PERMISSIVE")
    .option("columnNameOfCorruptRecord", "_corrupt_record")
    .csv("/Volumes/lab/ingest/landing/orders.csv")
    .cache())
raw.count()  # Materialize all cached columns before branching.
valid_flag = F.coalesce(
    F.col("_corrupt_record").isNull()
    & F.col("order_id").isNotNull()
    & (F.col("amount") >= 0), F.lit(False))
valid = raw.filter(valid_flag).drop("_corrupt_record")
rejected = raw.filter(~valid_flag)

A parseable negative amount is rejected for a different reason than malformed numeric text. Missing or extra CSV tokens are not necessarily parser-corrupt records, so enforce the expected column contract separately. Preserve source evidence and rejection reasons for remediation; release the cache after both outputs are consumed. No Databricks execution is claimed.

42. How would you flatten a nested JSON array while preserving the parent record identifier?

Parse the JSON using a declared nested schema, then select the parent identifier alongside the expanded array element. explode produces one row per element but removes parents with null or empty arrays. explode_outer preserves those parents with a null child, which is useful when missing children must remain visible.

This self-contained transformation uses the spark session in a Databricks Python notebook. The first parent produces two rows and the second produces one null-child row; those are expected results, not an execution report.

Python example

from pyspark.sql import functions as F

parents = spark.createDataFrame([
    ("p1", '{"items":[{"sku":"A","qty":2},{"sku":"B","qty":1}]}'),
    ("p2", '{"items":[]}')
], "parent_id STRING, payload STRING")
parsed = parents.withColumn("doc", F.from_json(
    "payload", "STRUCT<items:ARRAY<STRUCT<sku:STRING,qty:INT>>>"))
flat = (parsed
    .select("parent_id", F.explode_outer("doc.items").alias("item"))
    .select("parent_id", "item.sku", "item.qty"))
from pyspark.sql import functions as F

parents = spark.createDataFrame([
    ("p1", '{"items":[{"sku":"A","qty":2},{"sku":"B","qty":1}]}'),
    ("p2", '{"items":[]}')
], "parent_id STRING, payload STRING")
parsed = parents.withColumn("doc", F.from_json(
    "payload", "STRUCT<items:ARRAY<STRUCT<sku:STRING,qty:INT>>>"))
flat = (parsed
    .select("parent_id", F.explode_outer("doc.items").alias("item"))
    .select("parent_id", "item.sku", "item.qty"))
from pyspark.sql import functions as F

parents = spark.createDataFrame([
    ("p1", '{"items":[{"sku":"A","qty":2},{"sku":"B","qty":1}]}'),
    ("p2", '{"items":[]}')
], "parent_id STRING, payload STRING")
parsed = parents.withColumn("doc", F.from_json(
    "payload", "STRUCT<items:ARRAY<STRUCT<sku:STRING,qty:INT>>>"))
flat = (parsed
    .select("parent_id", F.explode_outer("doc.items").alias("item"))
    .select("parent_id", "item.sku", "item.qty"))

Quarantine malformed JSON before expansion in a production pipeline. Preserve an item identifier or array position when child-level reconciliation matters. Exploding two independent arrays successively can multiply their lengths rather than pair corresponding elements.

43. How would you distinguish NULL, an empty string, and an invalid numeric value in a cleaning rule?

Classify the original text before casting: SQL NULL means missing, an empty or whitespace-only string means blank, and a nonblank value that cannot become the required numeric type is invalid. A successful cast can still violate a business rule. Do not replace all three cases with zero, because that hides data-quality differences and changes aggregates.

The following standalone Databricks SQL example keeps the original value and uses TRY_CAST to tolerate malformed decimal text and overflow. Ordinary casts may raise errors under ANSI behavior.

SQL example

WITH input(raw) AS (
  VALUES (CAST(NULL AS STRING)), (''), ('oops'), ('-2'), ('12.50')
), parsed AS (
  SELECT raw, TRY_CAST(TRIM(raw) AS DECIMAL(12,2)) AS amount
  FROM input
)
SELECT raw, amount,
  CASE
    WHEN raw IS NULL THEN 'missing'
    WHEN TRIM(raw) = '' THEN 'blank'
    WHEN amount IS NULL THEN 'invalid_number'
    WHEN amount < 0 THEN 'negative_amount'
    ELSE 'valid'
  END AS quality_status
FROM

WITH input(raw) AS (
  VALUES (CAST(NULL AS STRING)), (''), ('oops'), ('-2'), ('12.50')
), parsed AS (
  SELECT raw, TRY_CAST(TRIM(raw) AS DECIMAL(12,2)) AS amount
  FROM input
)
SELECT raw, amount,
  CASE
    WHEN raw IS NULL THEN 'missing'
    WHEN TRIM(raw) = '' THEN 'blank'
    WHEN amount IS NULL THEN 'invalid_number'
    WHEN amount < 0 THEN 'negative_amount'
    ELSE 'valid'
  END AS quality_status
FROM

WITH input(raw) AS (
  VALUES (CAST(NULL AS STRING)), (''), ('oops'), ('-2'), ('12.50')
), parsed AS (
  SELECT raw, TRY_CAST(TRIM(raw) AS DECIMAL(12,2)) AS amount
  FROM input
)
SELECT raw, amount,
  CASE
    WHEN raw IS NULL THEN 'missing'
    WHEN TRIM(raw) = '' THEN 'blank'
    WHEN amount IS NULL THEN 'invalid_number'
    WHEN amount < 0 THEN 'negative_amount'
    ELSE 'valid'
  END AS quality_status
FROM

The five rows should receive five different statuses. Use IS NULL, not = NULL; define rounding and allowable ranges separately from parseability.

44. When would you use unionByName rather than union, and what schema checks still matter?

Use unionByName when two DataFrames represent the same logical fields but their column order differs. Ordinary DataFrame union aligns positions, which can silently put compatible-looking values into the wrong columns. Neither operation removes duplicate rows.

In this Databricks PySpark example, an approved optional column is absent from the older input. Allowing missing columns fills it with null; it does not establish that every future schema difference is acceptable.

Python example

older = spark.createDataFrame(
    [(1, "North")], "account_id LONG, region STRING")
newer = spark.createDataFrame(
    [("South", 2, "standard")],
    "region STRING, account_id LONG, service_tier STRING")
combined = older.unionByName(newer, allowMissingColumns=True)
older = spark.createDataFrame(
    [(1, "North")], "account_id LONG, region STRING")
newer = spark.createDataFrame(
    [("South", 2, "standard")],
    "region STRING, account_id LONG, service_tier STRING")
combined = older.unionByName(newer, allowMissingColumns=True)
older = spark.createDataFrame(
    [(1, "North")], "account_id LONG, region STRING")
newer = spark.createDataFrame(
    [("South", 2, "standard")],
    "region STRING, account_id LONG, service_tier STRING")
combined = older.unionByName(newer, allowMissingColumns=True)

The expected output has two rows and a null service_tier for account 1. Before combining production inputs, compare names, types, nested structures, nullability expectations, units, and field meanings. Explicitly normalize permitted conversions and reject unexpected differences. Deduplicate separately using a defined business key and precedence rule.

45. How would you keep the latest record per business key using a window function and a deterministic tie-breaker?

Partition a window by the business key and order records using the business definition of recency, followed by a stable tie-breaker. Keep ROW_NUMBER() = 1. A timestamp alone is insufficient when events share timestamps; ingestion order and partition order are not reliable substitutes for a source sequence.

This standalone Spark SQL or Databricks SQL example uses typed timestamps and a unique source sequence within each account.

SQL example

WITH changes(account_id, updated_at, source_seq, status) AS (
  VALUES
    (1, TIMESTAMP '2026-01-02 10:00:00', 10, 'pending'),
    (1, TIMESTAMP '2026-01-02 10:00:00', 11, 'active'),
    (2, TIMESTAMP '2026-01-01 09:00:00',  3, 'active')
), ranked AS (
  SELECT *, ROW_NUMBER() OVER (
    PARTITION BY account_id
    ORDER BY updated_at DESC NULLS LAST, source_seq DESC
  ) AS position
  FROM changes
)
SELECT account_id, updated_at, source_seq, status
FROM ranked WHERE position = 1

WITH changes(account_id, updated_at, source_seq, status) AS (
  VALUES
    (1, TIMESTAMP '2026-01-02 10:00:00', 10, 'pending'),
    (1, TIMESTAMP '2026-01-02 10:00:00', 11, 'active'),
    (2, TIMESTAMP '2026-01-01 09:00:00',  3, 'active')
), ranked AS (
  SELECT *, ROW_NUMBER() OVER (
    PARTITION BY account_id
    ORDER BY updated_at DESC NULLS LAST, source_seq DESC
  ) AS position
  FROM changes
)
SELECT account_id, updated_at, source_seq, status
FROM ranked WHERE position = 1

WITH changes(account_id, updated_at, source_seq, status) AS (
  VALUES
    (1, TIMESTAMP '2026-01-02 10:00:00', 10, 'pending'),
    (1, TIMESTAMP '2026-01-02 10:00:00', 11, 'active'),
    (2, TIMESTAMP '2026-01-01 09:00:00',  3, 'active')
), ranked AS (
  SELECT *, ROW_NUMBER() OVER (
    PARTITION BY account_id
    ORDER BY updated_at DESC NULLS LAST, source_seq DESC
  ) AS position
  FROM changes
)
SELECT account_id, updated_at, source_seq, status
FROM ranked WHERE position = 1

Account 1 should retain sequence 11. Reject null keys and conflicting rows with identical ordering fields, or add another authoritative tie-breaker. dropDuplicates alone does not promise the latest record, and event-time ordering may need adjustment when corrections carry explicit source versions.

46. When are left semi and left anti joins more appropriate than an inner or left join?

A left semi join answers โ€œwhich left-side rows have at least one match?โ€ A left anti join answers โ€œwhich have no match?โ€ Both return only left-side columns. Use a semi join to retain customers who have qualifying purchases and an anti join to find customers with none.

Unlike an inner join, a semi join does not multiply a customer row merely because several purchases match it. It still preserves duplicate customer rows already present on the left. An anti join expresses exclusion directly, without adding right-side columns and then filtering a left join.

Use an inner or left join when right-side attributes are required, after checking key cardinality. With ordinary equality, null keys do not match each other; use null-safe equality only when that matches the business meaning. Also avoid assuming NOT IN has identical null behavior to an anti join.

47. When can a broadcast join help, and what can make broadcasting the wrong choice?

Broadcasting can help when one join input, after filtering and projection, is small enough to replicate safely to each executor. A broadcast hash join can avoid shuffling the large input by the join key. Verify estimated and observed sizes and inspect the chosen physical plan rather than broadcasting every dimension table by convention.

The wrong choice can cause memory pressure, serialization overhead, timeouts, or repeated broadcast costs under concurrency. Compressed file size is not the same as the in-memory hash relation size. A non-equality condition may require a much more expensive join strategy, and some join types restrict which side can be broadcast.

Prefer accurate statistics and selective inputs first. Use a broadcast hint only with evidence, then compare runtime, spill, memory, and total workload cost. Broadcasting cannot fix an unintended many-to-many join or incorrect keys.

48. Which Spark operations usually cause a shuffle, and why does that matter?

Operations that require records with related keys to meet commonly cause a shuffle: grouped aggregations, distinct or deduplication, many joins, global sorting, and explicit repartitioning. Window functions can also require redistribution and sorting according to their partition and ordering expressions. The actual requirement depends on the existing distribution and selected physical strategy; a broadcast join, for example, avoids shuffling its large side.

A shuffle moves intermediate data across tasks and often machines. Serialization, network transfer, sorting, disk spill, and skew can dominate processing time. It also creates stage boundaries and additional recovery work after failures.

Reduce unnecessary columns and records before expensive exchanges where semantics permit. Consider partial aggregation, suitable join strategies, and sensible partition sizes. Inspect Exchange operators and measured shuffle metrics rather than treating every shuffle as a defect: many correct distributed calculations require one.

49. How do repartition and coalesce differ when changing a DataFrame's partition count?

repartition redistributes a DataFrame through a shuffle and can increase or decrease its partition count. Supplying columns groups equal partitioning keys together, which can help a later operation but can also concentrate a hot key. Repartitioning without keys aims to redistribute work rather than preserve a meaningful row order.

coalesce normally reduces partitions without a full shuffle by combining existing partitions. It is useful near an output boundary when the current distribution is already acceptable. A large reduction can create oversized tasks and reduce upstream parallelism; coalesce(1) is therefore not a general small-file remedy.

Choose a count from data size, task duration, available parallelism, and downstream requirements. Spark execution partitions are not the same as a table's directory partitions, and neither API guarantees one final file per partition under every writer and adaptive execution configuration.

50. How would you use EXPLAIN or DataFrame.explain to investigate an inefficient query plan?

Start with EXPLAIN FORMATTED or df.explain("formatted") to inspect scans, filters, joins, exchanges, and sorts. Use an extended plan when analyzing how logical expressions became physical operations. Look for missing partition or file pruning, unnecessarily wide projections, repeated scans, unexpected Cartesian products, and large shuffles before selective filters.

Then connect operators to evidence from an actual bounded test run: row counts, bytes scanned, task durations, spill, and join cardinality. A complicated plan is not necessarily slow, and an estimate is not an observed measurement.

With adaptive query execution, the initial plan can differ from the completed plan, so inspect runtime query details as well. Change one suspected cause at a time and compare equivalent inputs and cache conditions. Validate output correctness before treating a faster plan as an improvement.

51. Which Spark UI metrics would you inspect to distinguish skew, shuffle spill, and slow input reads?

Compare task distributions within the slow stage, not just its total duration. A few extreme tasks suggest a different problem from every task being equally slow.

Suspected issue

Evidence to compare

Skew

Maximum versus median task time, input or shuffle records, and partition sizes

Shuffle pressure

Shuffle read/write bytes, fetch wait, memory and disk spill, peak execution memory

Slow input

Scan time and bytes, input-task throughput, file counts, and storage-side latency or throttling

Correlate those signals with executor logs, garbage collection, retries, and the SQL plan. High spill can coexist with skew; a large join result can reflect nonunique keys rather than poor distribution. Slow input also includes many tiny-file overheads, not only low storage bandwidth.

Use the Spark UI where the compute mode exposes it, or corresponding query and workload diagnostics. Select a remedy only after locating the expensive operator and confirming its data shape.

52. When is caching a DataFrame useful, and when can it make a workload worse?

Caching is useful when several actions reuse the same expensive, reasonably sized intermediate DataFrame. Cache after useful filtering and projection rather than automatically caching the raw source. Persistence is lazy, so the first action pays the materialization cost; a benchmark that excludes that action can overstate the benefit.

Caching can hurt a one-pass workload, displace more valuable execution memory, increase garbage collection or spill, and retain data that is no longer useful. The storage level and actual cached size matter. Recomputing a cheap transformation can be preferable to storing and reading it.

Measure total runtime across the intended reuse pattern, including cache population, and inspect whether the data is actually retained. Call unpersist() when reuse ends. Distinguish DataFrame persistence from Databricks disk caching and SQL result caching; they solve different reuse problems.

53. Why might a built-in Spark SQL function be preferable to a Python UDF?

Built-in functions expose their meaning and types to Spark's optimizer, enabling expression simplification, generated execution, and other optimizations. A conventional Python UDF adds a Python execution boundary and often serialization costs, while its internal logic is less visible to the engine. Eligible built-ins may also benefit from Photon; that is not a promise that every expression is accelerated.

For example, this transformation needs no Python UDF. In a Databricks Python notebook, it should turn the first value into NORTH while preserving the second as null.

Python example

from pyspark.sql import functions as F

regions = spark.createDataFrame(
    [(" north ",), (None,)], "region STRING")
cleaned = regions.select(F.upper(F.trim("region")).alias("region"))
from pyspark.sql import functions as F

regions = spark.createDataFrame(
    [(" north ",), (None,)], "region STRING")
cleaned = regions.select(F.upper(F.trim("region")).alias("region"))
from pyspark.sql import functions as F

regions = spark.createDataFrame(
    [(" north ",), (None,)], "region STRING")
cleaned = regions.select(F.upper(F.trim("region")).alias("region"))

Use a UDF when supported built-ins cannot express the required logic. Declare types, test null and error handling, and evaluate vectorized alternatives where appropriate. A faster function with different semantics is not a valid replacement.

54. What can adaptive query execution change at runtime, and what problems does it not solve automatically?

Adaptive query execution uses statistics collected during execution to revise supported batch-query plans. It can coalesce small shuffle partitions, switch some join strategies when observed sizes justify it, and split eligible skewed shuffle-join partitions. The benefit is correcting decisions that were difficult to make from static estimates alone.

AQE does not repair incorrect joins, invent missing business constraints, remove Python UDF costs, or automatically solve every form of skew. Its transformations have join-type and configuration limits. It also does not generally reorder joins at runtime, and batch AQE capabilities should not be assumed for stateful streaming queries.

Check the completed physical plan and metrics to see what changed. Keep filters, statistics, and sensible data modeling in place. Treat AQE as a useful optimizer, not a reason to ignore an exploding result set or excessive data movement.

55. Why do small files hurt table performance, and how does OPTIMIZE address the problem?

Many small files increase file-opening, metadata, scheduling, and storage-request overhead relative to useful work. They can make scans and planning slow even when the table's total data volume is modest. Excessively fine directory partitioning and frequent tiny writes are common contributors.

OPTIMIZE rewrites the table's physical files into a more efficient layout. On a non-clustered Delta table, compaction combines smaller files; on a liquid-clustered table, optimization also organizes data by clustering keys. This is not a deletion of logical table rows, and obsolete physical files remain subject to retention and cleanup.

Compare file distributions, bytes scanned, query latency, and maintenance cost before choosing a schedule. Review existing managed-table optimization settings first. Preventing tiny writes can complement compaction, but forcing every write into one task can create a worse bottleneck.

56. How do liquid clustering, directory partitioning, and Z-ordering differ as table-layout choices?

These approaches organize table data differently and should follow the workload's access patterns rather than a universal recipe.

Layout

Main idea

Important tradeoff

Directory partitioning

Separate data by partition-column values

Useful pruning, but excessive cardinality creates many small partitions

Z-ordering

Co-locate related values across selected columns during rewrites

Helps suitable filters but requires maintenance and is not an index

Liquid clustering

Organize files around clustering keys that can change over time

Flexible layout, with table-feature and compute compatibility requirements

Liquid clustering cannot coexist with directory partitioning or Z-ordering on the same table. Changing clustering keys does not instantly reorganize every historical file. Check available automated maintenance, then measure representative filter selectivity, scan reduction, write overhead, and full workload cost. A tiny table may not justify elaborate layout tuning at all.

57. How would you write a MERGE that updates existing business keys and inserts new ones?

Match on a stable, non-null business key, explicitly assign approved columns, and apply an ordering rule so stale events cannot overwrite newer state. Validate one source record per key and the target's key uniqueness before writing.

This illustrative Databricks SQL example requires an existing disposable lab.interview_demo schema and permission to create and modify a new Delta table. The setup is run once; the MERGE may be retried with the same immutable source. Sequence numbers must increase per account, and equal sequences must never contain conflicting payloads.

SQL example

CREATE TABLE lab.interview_demo.account_merge_example (
  account_id BIGINT, balance DECIMAL(12,2), change_seq BIGINT
) USING DELTA;
INSERT INTO lab.interview_demo.account_merge_example
VALUES (1, 100.00, 1);

MERGE INTO lab.interview_demo.account_merge_example AS t
USING (
  SELECT * FROM VALUES
    (CAST(1 AS BIGINT), CAST(125.00 AS DECIMAL(12,2)), CAST(2 AS BIGINT)),
    (CAST(2 AS BIGINT), CAST(50.00 AS DECIMAL(12,2)), CAST(1 AS BIGINT))
  AS v(account_id, balance, change_seq)
) AS s
ON t.account_id = s.account_id
WHEN MATCHED AND s.change_seq > t.change_seq THEN
  UPDATE SET balance = s.balance, change_seq = s.change_seq
WHEN NOT MATCHED THEN
  INSERT (account_id, balance, change_seq)
  VALUES (s.account_id, s.balance, s.change_seq)

CREATE TABLE lab.interview_demo.account_merge_example (
  account_id BIGINT, balance DECIMAL(12,2), change_seq BIGINT
) USING DELTA;
INSERT INTO lab.interview_demo.account_merge_example
VALUES (1, 100.00, 1);

MERGE INTO lab.interview_demo.account_merge_example AS t
USING (
  SELECT * FROM VALUES
    (CAST(1 AS BIGINT), CAST(125.00 AS DECIMAL(12,2)), CAST(2 AS BIGINT)),
    (CAST(2 AS BIGINT), CAST(50.00 AS DECIMAL(12,2)), CAST(1 AS BIGINT))
  AS v(account_id, balance, change_seq)
) AS s
ON t.account_id = s.account_id
WHEN MATCHED AND s.change_seq > t.change_seq THEN
  UPDATE SET balance = s.balance, change_seq = s.change_seq
WHEN NOT MATCHED THEN
  INSERT (account_id, balance, change_seq)
  VALUES (s.account_id, s.balance, s.change_seq)

CREATE TABLE lab.interview_demo.account_merge_example (
  account_id BIGINT, balance DECIMAL(12,2), change_seq BIGINT
) USING DELTA;
INSERT INTO lab.interview_demo.account_merge_example
VALUES (1, 100.00, 1);

MERGE INTO lab.interview_demo.account_merge_example AS t
USING (
  SELECT * FROM VALUES
    (CAST(1 AS BIGINT), CAST(125.00 AS DECIMAL(12,2)), CAST(2 AS BIGINT)),
    (CAST(2 AS BIGINT), CAST(50.00 AS DECIMAL(12,2)), CAST(1 AS BIGINT))
  AS v(account_id, balance, change_seq)
) AS s
ON t.account_id = s.account_id
WHEN MATCHED AND s.change_seq > t.change_seq THEN
  UPDATE SET balance = s.balance, change_seq = s.change_seq
WHEN NOT MATCHED THEN
  INSERT (account_id, balance, change_seq)
  VALUES (s.account_id, s.balance, s.change_seq)

The intended result is account 1 at 125.00 and account 2 at 50.00. Replaying the merge leaves that state unchanged under these assumptions. Concurrent writers still require coordination and conflict handling; the statement does not enforce business-key uniqueness globally.

58. Why can multiple source rows matching one target row make MERGE fail or become ambiguous?

An update needs an unambiguous source value for each target row. If two source events match the same target key and propose different values, selecting either arbitrarily would make the outcome dependent on execution details. A MERGE can therefore reject duplicate matches rather than choose a winner.

Normalize the source first using an authoritative sequence and deterministic tie-breaker. Reject conflicting ties. If every event matters, such as successive balance adjustments, aggregate or process the ordered events rather than simply discarding all but the latest payload. Check target-key uniqueness too.

Duplicate-match detection depends on runtime: Databricks Runtime 16.0 and later consider both ON and WHEN MATCHED conditions, while 15.4 LTS and earlier consider ON conditions. Do not use that difference as a deduplication strategy. Duplicate new keys can also be inserted when they do not match existing target rows.

59. How would you introduce a new source column without silently accepting every future schema change?

Treat the new column as a versioned contract change. Confirm its meaning, type, nullability, default behavior for old rows, privacy classification, and downstream consumers. Add the approved column explicitly or enable evolution only for the reviewed write operation, rather than turning on broad session-wide acceptance of all future changes.

Update the ingestion schema, transformation projection, target schema, quality rules, and tests together. Keep unapproved source fields in a monitored rescued or quarantine path, or fail ingestion according to the agreed policy. Schema inference alone cannot decide that a new field is safe or semantically compatible.

Test historical inputs that lack the column and newer inputs that contain it. A rename or incompatible type change is not equivalent to adding an optional field. Review stream restart requirements, table-feature compatibility, and downstream deployment order before promotion.

60. How would you inspect table history, query an older version, and decide whether RESTORE is appropriate?

Use DESCRIBE HISTORY to identify relevant versions, operations, timestamps, and available operation metrics. Query a candidate with VERSION AS OF and compare keys, counts, and business totals against the current table. A version number is more explicit than an ambiguous timestamp when documenting an investigation.

Choose RESTORE only when making an older snapshot current is the intended recovery action. It creates a new data-changing commit; it does not erase intervening history or automatically undo related tables and external side effects. Downstream streams may observe restored data as new changes, so coordinate consumers and reconciliation.

Verify that both required logs and data files remain available. History entries alone do not guarantee readable time travel after cleanup. For a small bad subset, a reviewed corrective write can preserve legitimate later changes better than restoring the entire table.

61. What checks should precede VACUUM when long-running readers and streaming consumers exist?

Check the table's actual data-file and log-retention settings against the longest reader duration, stream outage, consumer lag, backfill window, and recovery requirement. A stopped stream may need older source files when it resumes; its checkpoint does not preserve those files. Coordinate maintenance with table owners and downstream consumers rather than relying on the default retention period.

Use VACUUM ... DRY RUN to inspect candidate files without deleting them. Confirm that checkpoints and unrelated files are outside the table's data directory, and review clone or feature-specific behavior where applicable. Keep safety checks enabled and do not shorten retention merely to obtain an immediate storage reduction.

After obsolete data files are removed, some older snapshots and change-feed ranges can become unreadable even when history metadata remains. Retention is therefore an operational recovery contract, not just a housekeeping setting.

62. How would you configure Auto Loader with a durable checkpoint and schema location to ingest files into a governed table?

Use a stable checkpoint unique to this ingestion query and a separate schema-metadata directory. This illustrative Databricks PySpark job requires supported Unity Catalog compute; existing lab.ingest.landing and lab.ingest.state volumes; and an existing Delta table lab.bronze.events matching the declared columns. The service identity needs parent-object access, source-volume read, state-volume read/write, and target write privileges.

Python example

schema = "event_id STRING, amount DECIMAL(12,2), _rescued_data STRING"
source = "/Volumes/lab/ingest/landing/events"
state = "/Volumes/lab/ingest/state/events_v1"

incoming = (spark.readStream.format("cloudFiles")
    .option("cloudFiles.format", "json")
    .schema(schema)
    .option("cloudFiles.schemaLocation", state + "/schema")
    .option("cloudFiles.schemaEvolutionMode", "rescue")
    .option("rescuedDataColumn", "_rescued_data")
    .load(source))
query = (incoming.writeStream.format("delta")
    .outputMode("append")
    .option("checkpointLocation", state + "/checkpoint")
    .trigger(availableNow=True)
    .toTable("lab.bronze.events"))
query.awaitTermination()
schema = "event_id STRING, amount DECIMAL(12,2), _rescued_data STRING"
source = "/Volumes/lab/ingest/landing/events"
state = "/Volumes/lab/ingest/state/events_v1"

incoming = (spark.readStream.format("cloudFiles")
    .option("cloudFiles.format", "json")
    .schema(schema)
    .option("cloudFiles.schemaLocation", state + "/schema")
    .option("cloudFiles.schemaEvolutionMode", "rescue")
    .option("rescuedDataColumn", "_rescued_data")
    .load(source))
query = (incoming.writeStream.format("delta")
    .outputMode("append")
    .option("checkpointLocation", state + "/checkpoint")
    .trigger(availableNow=True)
    .toTable("lab.bronze.events"))
query.awaitTermination()
schema = "event_id STRING, amount DECIMAL(12,2), _rescued_data STRING"
source = "/Volumes/lab/ingest/landing/events"
state = "/Volumes/lab/ingest/state/events_v1"

incoming = (spark.readStream.format("cloudFiles")
    .option("cloudFiles.format", "json")
    .schema(schema)
    .option("cloudFiles.schemaLocation", state + "/schema")
    .option("cloudFiles.schemaEvolutionMode", "rescue")
    .option("rescuedDataColumn", "_rescued_data")
    .load(source))
query = (incoming.writeStream.format("delta")
    .outputMode("append")
    .option("checkpointLocation", state + "/checkpoint")
    .trigger(availableNow=True)
    .toTable("lab.bronze.events"))
query.awaitTermination()

The intended behavior is bounded incremental ingestion, potentially across several micro-batches. Keep these state paths across compatible restarts and outside table storage; they are illustrative, not existing user assets. Monitor rescued values before publishing trusted data. Require immutable file arrivals and implement business-event deduplication separately: ingestion tracking does not eliminate duplicate events delivered in different files.

63. What does Auto Loader's rescued data column capture, and how should a pipeline respond to schema drift?

The rescued data column preserves fields that do not fit the ingestion schema, such as unexpected columns, type mismatches, or case mismatches. It is a JSON payload that can include source-file information. It is not equivalent to a malformed-record column: syntactically broken JSON or CSV requires its own parser-error policy.

Monitor rescued-row counts and rates, identify the affected producer and fields, and retain enough raw evidence to repair and replay records. A row can reach bronze successfully while still being unsuitable for a trusted downstream table.

Choose schema evolution deliberately. Rescue mode avoids automatically extending the declared schema; an approved additive-evolution mode can update schema metadata and stop the stream until restart. Review changes before promoting columns, and test existing consumers. Type widening, renames, and required-field changes need separate compatibility and business-rule checks.

64. When would COPY INTO be sufficient, and when would you choose Auto Loader instead?

COPY INTO is often sufficient for straightforward, SQL-driven incremental file loads with a manageable file population and an infrequently changing schema. It tracks loaded files, so repeating the normal load can skip files already processed. Explicit reload options require care because reprocessing files can duplicate business records.

Choose Auto Loader for sustained or large-scale file arrivals, richer schema handling, incremental micro-batch controls, and integration with streaming or Lakeflow pipelines. Its discovery mechanisms are designed for growing file populations, but cloud-specific event configuration and permissions still matter.

Compare expected file counts, arrival rates, latency, schema volatility, operational skills, and replay requirements rather than choosing by row count alone. Either choice needs a clear file-immutability contract, quality validation, monitoring, and business-key deduplication. File-level ingestion tracking is not a universal exactly-once guarantee for the business dataset.

65. How do append, update, and complete output modes differ for a streaming aggregation?

Output modes describe which result rows a streaming query emits, not a universal storage mutation policy.

Mode

Aggregation output

Append

Newly finalized aggregate rows that will no longer change

Update

Aggregate rows changed since the previous trigger

Complete

The entire current aggregate result each trigger

For append-mode event-time windows, a suitable watermark lets Spark determine when results are final, so output can be delayed. Update mode can publish provisional counts earlier, but the destination must interpret repeated keys as replacements or upserts rather than blindly appending them. Complete mode repeatedly emits all groups and does not discard aggregate state through watermark cleanup.

Query and sink support constrain the choice. Evaluate state size, latency, downstream semantics, and recovery behavior together; changing the output mode alone does not convert an append-only destination into an upsert sink.

66. How would you combine an event-time window with a watermark, and what happens to very late records?

Apply the watermark to the event-time column before the windowed aggregation, then use that same marked column in the window. This transformation-only Databricks PySpark example assumes an existing append-only table lab.bronze.clicks with event_id STRING, customer_id STRING, and event_ts TIMESTAMP, plus read permissions. Invalid timestamps and unwanted event duplicates should be handled upstream.

Python example

from pyspark.sql import functions as F

clicks = spark.readStream.table("lab.bronze.clicks")
counts = (clicks
    .withWatermark("event_ts", "30 minutes")
    .groupBy(F.window("event_ts", "15 minutes"), "customer_id")
    .count())
from pyspark.sql import functions as F

clicks = spark.readStream.table("lab.bronze.clicks")
counts = (clicks
    .withWatermark("event_ts", "30 minutes")
    .groupBy(F.window("event_ts", "15 minutes"), "customer_id")
    .count())
from pyspark.sql import functions as F

clicks = spark.readStream.table("lab.bronze.clicks")
counts = (clicks
    .withWatermark("event_ts", "30 minutes")
    .groupBy(F.window("event_ts", "15 minutes"), "customer_id")
    .count())

This defines 15-minute windows; it does not start a sink. Watermark progress derives from observed event times, not elapsed wall-clock time since arrival. Supported semantics protect records within the lateness threshold; older records may still be processed but are not guaranteed acceptance. Append results wait for finalization, which can stall without new event-time progress. Choose the threshold from measured lateness and correction requirements, balancing completeness against state size and output delay.

67. When would you use AvailableNow rather than a continuously running micro-batch trigger?

Use AvailableNow for scheduled incremental processing when the business can tolerate a defined refresh interval. It processes the source data available for that run, can divide it into several micro-batches, and then terminates. Reusing a compatible durable checkpoint allows the next run to continue rather than starting from scratch.

A continuously running processing-time micro-batch query is appropriate when lower arrival-to-output latency justifies ongoing compute and polling overhead. Its interval is a scheduling preference, not a guarantee that each batch finishes within that time.

Verify source and compute support. Current serverless notebook and job restrictions differ from classic streaming compute and Lakeflow pipeline modes; do not assume a processing-time trigger works everywhere. Compare startup overhead, backlog catch-up, source retention, freshness, and cost. AvailableNow is not one indivisible batch or a replacement for recovery planning.

68. How would you make a foreachBatch write safe to retry?

Assume foreachBatch can invoke the same batch again after a failure. Make the sink effect idempotent: for a current-state Delta target, deduplicate source keys deterministically and merge only newer source versions, assigning final values rather than adding the same increment on every retry. Preserve stable input and deterministic transformations.

For a destination supporting transactions, another pattern is a durable processed-batch ledger committed atomically with the effect. Scope the batch key to a stable query generation plus batchId; resetting a checkpoint can reuse batch numbers. A ledger written separately from the effect leaves a failure gap.

Handle empty batches, consume the required full output for stateful queries, and let errors propagate. Test failure after a partial write and before acknowledgment. Each external sink needs its own deduplication or recovery contract; a checkpoint alone cannot make arbitrary API calls exactly once.

69. What does change data feed expose, and how do its configuration and retention requirements affect a consumer?

Change data feed exposes row changes with metadata such as change type, commit version, and commit timestamp. Delta updates can produce both preimages and postimages, so a current-state consumer must distinguish them from inserts and deletes rather than counting every feed row as a new business event.

Configuration is no longer one universal rule. Automatic CDF is available on eligible Unity Catalog tables with supported compute, including Databricks Runtime 19 or later; Delta tables require row tracking. Legacy/manual Delta CDF uses the delta.enableChangeDataFeed table property and captures changes after enablement. Check which mechanism and table features apply before designing the reader.

Persist consumer progress and define initial-snapshot versus change-only behavior. Retention bounds the readable history; a checkpoint does not preserve expired changes. Monitor lag, archive required changes independently, and plan a reconciled reinitialization if the consumer falls behind. Non-additive schema changes can also constrain readable ranges.

70. How do SCD Type 1 and Type 2 differ, and where can AUTO CDC simplify their implementation?

SCD Type 1 overwrites a business entity's current attributes. It is appropriate when only current state matters, but it does not retain prior business values. SCD Type 2 preserves successive versions with validity intervals so reports can associate facts with the version effective at the relevant time.

AUTO CDC in Lakeflow pipelines can manage key matching, sequencing, deletes, and Type 1 or Type 2 application from a change feed. It reduces custom merge and history-maintenance logic, but still requires a reliable key, deterministic sequence, and clear handling of nulls, partial updates, and late changes. Sequence ties must have an intentional resolution.

Use AUTO CDC FROM SNAPSHOT when authoritative ordered snapshots, rather than a change feed, are available. Verify the applicable pipeline edition and feature support. These are Databricks Lakeflow capabilities, not APIs universally available in open-source Spark Declarative Pipelines.

71. How would you choose between retaining, dropping, quarantining, or failing on an invalid pipeline record?

Choose the action from the record's business impact and the ability to repair it. Retain with a quality flag when imperfect data is useful and consumers understand the limitation. Drop only when omission is explicitly acceptable and measured. Quarantine when the record needs investigation or replay. Fail the relevant update when publishing partial or invalid results would be more harmful than missing freshness targets.

Lakeflow expectations support recording violations, dropping invalid rows, or failing on violations. A quarantine path requires explicit routing and retention; it is not automatically created by a drop policy.

Use null-safe validity expressions, such as COALESCE(amount >= 0, false), so nulls cannot disappear from both valid and invalid branches. Track accepted, rejected, and quarantined counts with reasons and owners. Reconciliation and repair procedures matter as much as the initial rule, especially when invalid records affect financial totals or entity relationships.

72. How would you configure task dependencies, retries, and repair runs for a multi-task job?

Represent real data dependencies as a task graph: ingestion must publish a committed input before validation, and publication should depend on successful validation. Allow independent branches to run concurrently, but configure conditional and failure-handling paths deliberately so a success-looking cleanup task cannot authorize bad output.

Set bounded retries and suitable retry delays for transient failures. Deterministic validation errors should not consume endless retries. Make writes restart-safe, record the input range and run identity, and define timeout and concurrent-run limits according to shared resources.

After diagnosis, a repair run can rerun unsuccessful tasks and required dependents without recomputing the entire job. Repairs use current job and task settings, so record code and configuration changes before repairing. They do not roll back previous writes. Verify downstream totals, completeness, and side effects after recovery rather than stopping at a green job status.

73. How should job parameters and task values be used to pass control information between tasks?

Use job parameters for run inputs such as a processing date, environment, or bounded backfill range. Validate and type-convert them at the task boundary; notebook widgets commonly deliver strings. Parameterize SQL values through supported parameter binding rather than interpolating arbitrary text into queries.

Use task values for small JSON-compatible outputs computed by an upstream task, such as an approved table version, row count, or manifest identifier. A downstream parameter can reference {{tasks.ingest.values.input_version}} after the dependency is satisfied. The task-value JSON size limit is 48 KiB, so pass a table or manifest reference instead of collecting a dataset into control metadata.

Do not put secrets in either channel. Missing required values should fail clearly rather than silently use a development default. Task values coordinate execution; durable data and replay evidence belong in governed storage or operational records.

74. What should unit tests and integration tests check in a PySpark transformation pipeline?

Unit tests should exercise deterministic transformations on small, explicitly typed fixtures: nulls, malformed values, duplicate keys, ordering ties, empty inputs, boundary timestamps, and join cardinality. Check values and schema, not just whether a function completes. Compare unordered results appropriately and use justified tolerances for floating-point calculations.

Integration tests should use isolated governed assets on the intended Databricks compute and runtime. Verify permissions, ingestion options, Delta writes, schema evolution, task dependencies, and restart behavior. For streaming, replay bounded inputs and inspect both outputs and checkpoints; inject failure around writes to expose retry gaps.

Keep production data and credentials out of test fixtures. Separate reusable transformation functions from notebook orchestration, and include negative tests that must fail. Local unit tests cannot establish Unity Catalog, Auto Loader, Photon, or deployment compatibility; passing them is necessary evidence, not proof of production readiness.

75. How do Git folders and Declarative Automation Bundles support repeatable development and deployment?

Git folders connect development work to versioned source, branches, commits, and code review. They help collaborators compare and reproduce code changes, but synchronizing a repository does not fully define deployed jobs, permissions, libraries, or environment settings.

Declarative Automation Bundles, formerly Databricks Asset Bundles, package source and resource configuration together. A reviewed bundle can specify jobs, pipelines, artifacts, and environment-specific targets, then be validated and deployed through supported tooling. Keep credentials outside the bundle and use an appropriate automation identity.

Promote the same reviewed revision through test environments with explicit configuration differences. Record deployment evidence and test the actual deployed resources. Reverting a Git commit or deploying an earlier bundle does not automatically reverse table migrations, streamed state, or external effects, so rollback plans must cover those separately.

76. What privileges does a group need to read a Unity Catalog table, and why is SELECT alone sometimes insufficient?

For ordinary reads, a group needs USE CATALOG on the parent catalog, USE SCHEMA on the parent schema, and SELECT on the table, whether granted directly or inherited appropriately. SELECT alone does not supply the parent namespace permissions or access to the chosen compute.

These illustrative administrator-run statements assume the group and objects already exist and the grantor is authorized; they are not executed here.

SQL example

GRANT USE CATALOG ON CATALOG lab TO `analytics_readers`;
GRANT USE SCHEMA ON SCHEMA lab.reporting TO `analytics_readers`;
GRANT SELECT ON TABLE lab.reporting.daily_sales TO

GRANT USE CATALOG ON CATALOG lab TO `analytics_readers`;
GRANT USE SCHEMA ON SCHEMA lab.reporting TO `analytics_readers`;
GRANT SELECT ON TABLE lab.reporting.daily_sales TO

GRANT USE CATALOG ON CATALOG lab TO `analytics_readers`;
GRANT USE SCHEMA ON SCHEMA lab.reporting TO `analytics_readers`;
GRANT SELECT ON TABLE lab.reporting.daily_sales TO

If access still fails, verify effective group membership, object ownership or inherited grants, workspace-catalog bindings, and warehouse or compute permissions. Row filters and masks can further restrict visible data. Prefer grants to appropriate account groups over broad individual exceptions, and test using the reader's actual identity rather than an administrator session.

77. How do a storage credential and an external location work together without exposing cloud keys to every notebook?

A storage credential represents the supported cloud identity or authorization mechanism used to reach object storage. An external location binds that credential to a specific storage path and becomes a Unity Catalog securable object. Administrators manage the cloud trust relationship and location; notebook users receive only the data permissions needed for their work, not raw cloud keys.

For normal use, expose tabular data through registered tables and non-tabular files through volumes. Reading a table does not normally require granting every reader the ability to create external locations or manage storage credentials. Underlying cloud permissions must still permit the requested operation, and the identity mechanism differs by cloud.

Apply least privilege at both layers. Direct cloud-storage grants to users can bypass Unity Catalog controls, so the location object alone is not a complete security boundary against external access.

78. How do row filters and column masks differ from ordinary table-level grants?

Table-level grants decide whether a principal may perform an operation such as reading a table. A row filter narrows the rows visible during a governed query, while a column mask changes the returned value of a protected column. For example, regional analysts might see only their region's orders and receive a redacted contact value unless their group is entitled to the original.

These controls supplement rather than replace parent-object and table privileges. Test both allowed and restricted identities, null handling, policy-function dependencies, and query performance. Confirm the supported runtime, compute, operations, and sharing path before relying on a policy.

For many tables, centrally managed tag-based policies may be more maintainable than repeated table-specific assignments. Also restrict direct storage access and derived exports: query-time filtering or masking does not retroactively protect every previously copied dataset.

79. Which code, data, parameter, metric, and environment details should an MLflow run retain for reproducibility?

Retain the exact code revision and entry point, input dataset identifiers and versions or immutable snapshots, transformation and feature definitions, training parameters, and random seeds where meaningful. Record the Databricks runtime, Python and library versions, dependency environment, and relevant compute configuration so an apparently identical experiment does not silently use different execution conditions.

Log evaluation metrics with their dataset, split strategy, metric definitions, and important slices, plus model artifacts, signatures, and supporting reports. Link the run to any registered model version rather than relying only on a mutable alias. Avoid logging credentials or unnecessary sensitive records.

Autologging helps but must be checked for gaps. Seeds do not guarantee identical distributed results. Table versions become unusable after required files expire, so preserve governed snapshots and artifacts when reproducibility must outlast normal retention.

80. How would you attribute workload usage to teams and compare the cost of two pipeline designs?

Attribute usage with governed team or cost-center tags, job and pipeline identifiers, workspace, SKU, and time period. Investigate missing tags rather than silently charging shared resources to whichever user happened to run them.

This illustrative Databricks SQL query requires access to system.billing.usage. It summarizes a bounded example week, keeping SKUs and units separate; it estimates neither invoice totals nor savings.

SQL example

SELECT
  COALESCE(custom_tags['team'], 'unassigned') AS team,
  sku_name, usage_unit,
  SUM(usage_quantity) AS usage_quantity
FROM system.billing.usage
WHERE usage_date >= DATE '2026-10-01'
  AND usage_date < DATE '2026-10-08'
GROUP BY 1, 2, 3

SELECT
  COALESCE(custom_tags['team'], 'unassigned') AS team,
  sku_name, usage_unit,
  SUM(usage_quantity) AS usage_quantity
FROM system.billing.usage
WHERE usage_date >= DATE '2026-10-01'
  AND usage_date < DATE '2026-10-08'
GROUP BY 1, 2, 3

SELECT
  COALESCE(custom_tags['team'], 'unassigned') AS team,
  sku_name, usage_unit,
  SUM(usage_quantity) AS usage_quantity
FROM system.billing.usage
WHERE usage_date >= DATE '2026-10-01'
  AND usage_date < DATE '2026-10-08'
GROUP BY 1, 2, 3

Compare designs with equivalent data, correctness, freshness, concurrency, and cache conditions. Include startup, idle time, retries, maintenance, and operational effort. Price usage using applicable effective-dated rates and account terms, then include separately billed cloud storage, requests, and egress. DBUs alone are not the full cost. Report cost per successfully processed unit alongside latency and reliability, not a universal percentage saving.

Databricks Interview Questions and Answers for Experienced

The experienced answers focus on decisions that must remain defensible in production. They explain the evidence needed to diagnose a problem, the boundaries of a guarantee, and the recovery or rollout plan that accompanies an architectural choice.

81. How would you organize workspaces, catalogs, schemas, and service identities for several teams sharing one lakehouse?

Separate collaboration boundaries from data-security boundaries. Workspaces organize development and execution; catalogs provide broad governance boundaries, while schemas organize domain-owned assets. A practical design might use separate production and nonproduction workspaces, catalogs aligned to environment and sensitive business domains, and schemas for each team's data products. Avoid creating a workspace for every table or assuming workspace separation alone protects shared data.

Grant access to account groups, assign stable group ownership, and give each production workload an appropriate service identity. Normal readers need USE CATALOG, USE SCHEMA, and SELECT; workspace access, compute permissions, and cloud credentials are separate checks. Restrict catalog-to-workspace bindings where required.

Publish ownership, naming, retention, and cross-team interface rules. Test access using representative analyst and job identities, including denied cases. The tradeoff is isolation versus administrative overhead: central guardrails should protect shared data without making every routine team change an administrator ticket.

82. How would you choose between scheduled batch, incremental micro-batches, and low-latency streaming for a new data product?

Choose the least complex execution model that meets the product's measured freshness requirement. A daily financial summary usually favors scheduled batch; a periodically refreshed operational table can use incremental micro-batches; genuinely time-sensitive decisions may justify continuously running streaming infrastructure.

Evaluate peak arrival rate, allowable backlog, replay retention, event ordering, downstream capacity, and the business treatment of late corrections. Incremental processing avoids rereading unchanged data, but still needs checkpoints or durable progress tracking, idempotency, and reconciliation. AvailableNow processes the available backlog through bounded incremental execution rather than promising one batch.

Benchmark end-to-end freshness and cost at normal and burst traffic, including startup and recovery. Check the selected product's supported triggers: serverless notebook/job restrictions differ from Lakeflow pipeline modes. For example, an hourly report does not benefit from paying for a continuously active stream merely because its source supports streaming.

83. A file-ingestion pipeline stopped for several days. How would you resume it without losing data or reprocessing everything blindly?

Preserve the existing checkpoint and establish what stopped before restarting. Check the failing run, permissions, schema changes, source retention, and whether files were deleted or overwritten during the outage. Compare the last durable ingestion progress with a source inventory or manifest to establish the missing interval.

If the query and checkpoint remain compatible and the source files are still available, resume with that checkpoint. Apply admission limits and sufficient capacity to drain the backlog without overwhelming downstream tables. A schema-evolution failure may require accepting the intended schema change and restarting, rather than discarding progress.

If recovery requires a new checkpoint, treat it as an explicit replay: preserve the original, define the source range, and write through business-key or event-ID deduplication. Auto Loader's file tracking does not deduplicate repeated business events across different files. Reconcile expected files and events against accepted, quarantined, and missing records before declaring recovery complete.

84. How would you apply an out-of-order CDC feed that contains updates, deletes, and multiple events for the same key?

Apply changes by a deterministic source sequence, not file arrival order or processing time. Preserve each event's business key, operation, source sequence, and a tie-breaker that resolves equal timestamps. Validate conflicting events with identical ordering values rather than selecting an arbitrary winner.

For supported Lakeflow pipelines, AUTO CDC can maintain SCD Type 1 or Type 2 targets using keys, sequencing, and explicit delete handling. Configure tombstone retention to cover the expected out-of-order interval and recovery backlog. Otherwise, implement equivalent ordering and deletion state around a carefully designed MERGE.

For a Type 1 target, consolidate multiple source events per key and apply only newer events. Retain enough deletion metadata to prevent an older update from resurrecting a deleted entity. A Type 2 target instead requires correctly sequenced validity intervals; collapsing everything to the newest row would discard history. Test duplicate deliveries, late updates, deletes arriving first, null keys, and partial-update semantics.

85. Under what conditions can a streaming pipeline claim exactly-once results, and where can duplicate effects still occur?

Claim exactly-once results only for a clearly defined boundary and failure model. The source must support replay, the checkpoint must remain durable, processing must be reproducible, restarts must be compatible, and the sink must atomically commit or deduplicate retried output. Source delivery duplicates still require a business-level event identity.

A common failure occurs after an external sink accepts a write but before Spark records completion. The batch runs again. foreachBatch is at-least-once by default, so the destination needs durable idempotency, such as an atomic upsert by event ID or a transactionally recorded processing token. A batch ID alone is insufficient if its associated write and deduplication record can disagree.

Scope batch tokens to a query generation because restarting with a new checkpoint can reuse batch numbers. External emails, payments, or API calls require their own idempotency contract. Demonstrate the claim through failure injection at commit boundaries, not merely through a successful uninterrupted run.

86. How would you change a stateful streaming query when its existing checkpoint is incompatible with the new logic?

Treat the change as a controlled state rebuild or a documented, supported migration, not a checkpoint-file edit. Record the old query's final progress, output versions, state semantics, and retained replay range. Preserve its checkpoint for investigation and rollback.

Create a separate query generation with a new durable checkpoint and isolated output. Replay enough history to reconstruct the new state; starting at the old input offset alone loses the aggregation or join context accumulated before that offset. If required history is unavailable, agree on a new baseline and any resulting limitations before cutover.

Compare old and new outputs over representative windows, including late events, then switch consumers at an explicit boundary. Suppress duplicate external effects during replay and coordinate live writes so two generations do not compete unintentionally. Keep a tested rollback route until reconciliation passes. Compatibility is specific to the source, state schema, operators, sink, and runtime; changing code successfully is not evidence that old state is reusable.

87. A streaming job's state grows continuously and batches slow down. How would you diagnose and redesign it?

Determine whether the query is accumulating necessary state, failing to evict obsolete state, or simply receiving more work than it can process. Correlate batch duration and input lag with state row counts, state memory, rows removed, watermark progression, shuffle spill, and skewed keys.

Inspect unbounded aggregations, stream joins without time constraints, deduplication keys, and unusually large lateness thresholds. A watermark advances with observed event time, so an idle or delayed input can hold back cleanup; waiting longer in wall-clock time does not necessarily resolve it. Also verify that the output mode supports the intended eviction behavior.

Redesign around bounded windows or meaningful expiration rules, and route very late corrections through a separate reconciliation path when appropriate. Consider a durable current-state table instead of retaining unlimited streaming state. Additional memory or a different state-store configuration may relieve pressure, but cannot fix unlimited logical growth. Validate the redesign with long-duration and skewed-load tests, not just a short throughput benchmark.

88. How would you design a stream-stream join with bounded state and a justified late-data policy?

Define the business matching interval separately from the permitted arrival lateness. For example, an order may match a payment made within 30 minutes, while either record may arrive up to two hours late. Both streams need valid event timestamps; watermarks and a bounded time predicate allow obsolete join state to be removed.

This illustrative PySpark fragment assumes existing streaming DataFrames with nonnull order IDs and timestamp columns. It defines the join only; execution requires a supported sink, output mode, and unique durable checkpoint.

PySpark example

from pyspark.sql import functions as F

o = orders.withWatermark("order_ts", "2 hours").alias("o")
p = payments.withWatermark("payment_ts", "2 hours").alias("p")
matched = o.join(
    p,
    F.expr("""
        o.order_id = p.order_id
        AND p.payment_ts >= o.order_ts
        AND p.payment_ts <= o.order_ts + INTERVAL 30 MINUTES
    """),
    "inner",
)
from pyspark.sql import functions as F

o = orders.withWatermark("order_ts", "2 hours").alias("o")
p = payments.withWatermark("payment_ts", "2 hours").alias("p")
matched = o.join(
    p,
    F.expr("""
        o.order_id = p.order_id
        AND p.payment_ts >= o.order_ts
        AND p.payment_ts <= o.order_ts + INTERVAL 30 MINUTES
    """),
    "inner",
)
from pyspark.sql import functions as F

o = orders.withWatermark("order_ts", "2 hours").alias("o")
p = payments.withWatermark("payment_ts", "2 hours").alias("p")
matched = o.join(
    p,
    F.expr("""
        o.order_id = p.order_id
        AND p.payment_ts >= o.order_ts
        AND p.payment_ts <= o.order_ts + INTERVAL 30 MINUTES
    """),
    "inner",
)

Justify thresholds using observed delay distributions and business tolerance. Monitor stalled watermarks and late-data losses; define reconciliation outside the supported lateness guarantee. An outer join adds delayed unmatched-row decisions. Independently handle repeated payments or duplicate order events, since bounded state does not establish one-to-one business cardinality.

89. How would you backfill historical data while a live ingestion pipeline continues to run?

Separate historical replay from live ingestion, then reconcile them through an explicit overlap policy. Freeze a source boundary, record the historical range and run identity, and use independent compute, checkpoints, and staging output for the backfill. Do not reset the live query's checkpoint to make history visible.

Prefer an immutable bronze history that both paths can replay. When ranges overlap, use stable event IDs and deterministic source ordering. A historical record must not overwrite a newer live value merely because the backfill finishes later. For CDC, preserve deletes and sequence metadata rather than merging snapshots as unconditional updates.

Throttle the backfill against available capacity and avoid concurrent writers targeting the same hot keys where practical. Validate counts, key sets, totals, and selected records in staging before publishing. Finish with a reconciliation at the agreed boundary, including late arrivals and quarantined records. Separate execution simplifies recovery, but convergence still depends on shared business semantics.

90. How would you prove that an incremental pipeline has neither lost nor double-counted business events?

Prove reconciliation for a defined, closed source interval and business grain. Record source offsets or file manifests, expected event IDs, accepted records, explicit duplicates, rejected records, and unresolved gaps. Compare both directions: every expected event must have an explained outcome, and every published event must trace to an authorized input.

Row counts alone are insufficient because one missing event can cancel one duplicate. Add key-set comparisons, duplicate-key checks, business totals, and sampled field-level comparisons. Separate legitimate CDC updates and deletes from duplicate delivery; a current-state row count will not equal an event count.

Persist the reconciliation evidence with input bounds and output versions, then repeat after replay and failure tests. CDF can support incremental checks, but its retained range and automatic-versus-legacy eligibility must be verified; it is not a permanent event archive. Quality expectations detect specified violations, while independent source-to-output reconciliation tests completeness and accounting across the whole pipeline.

91. Two MERGE jobs intermittently conflict on the same Delta table. How would you reduce conflicts without weakening correctness?

Classify the conflict from the exception and overlapping operations before changing isolation or adding retries. Establish whether the jobs modify the same business rows, touch overlapping files, or collide with schema or protocol changes. Validate source-key uniqueness and deterministic event ordering first; concurrency tuning cannot repair ambiguous updates.

Reduce unnecessary overlap with precise predicates and disjoint work allocation where those boundaries match the business model. Serialize genuinely competing updates to the same entities, or consolidate them into one ordered ingestion path. Schedule metadata changes separately.

Evaluate row-level concurrency only when the table and runtime meet its requirements. It can reduce conflicts between different rows in the same file, but does not remove same-row or metadata conflicts. Retain bounded retries with backoff that reread current state and reapply an idempotent operation. Test invariant preservation, conflict rate, and throughput together; a faster pipeline that silently loses the newer update is not an improvement.

92. When would you choose Serializable rather than WriteSerializable isolation, and what tradeoff would you test?

Choose Serializable when the application requires table outcomes to agree with the actual commit order, including the effect of overlapping reads and writes. WriteSerializable is the default and allows some concurrent writes to be logically reordered while maintaining serializable write results.

For example, an update can start before an append and commit afterward without incorporating the newly appended matching rows under WriteSerializable. If the application's rule cannot accept that outcome, Serializable can force a conflict and retry instead. Neither setting makes arbitrary separate application steps or external side effects one transaction.

Test the exact concurrent operations that threaten the invariant, with controlled overlap and verified final rows. Compare conflict frequency, retry cost, throughput, and tail latency under each setting. Reads still operate on snapshots; stronger write isolation is not a promise that a long-running query always sees the latest data. Select the level from the required semantics, not from a blanket preference for the strongest-sounding option.

93. How would you evaluate a Delta table feature upgrade when several engines and older runtimes read the table?

Treat the upgrade as a compatibility migration shared by every reader and writer. Inventory scheduled jobs, streaming consumers, external engines, connectors, disaster-recovery readers, and rarely used reporting tools. Record their actual versions and supported reader and writer features, not just whether they recognize the Delta format.

Inspect the table's protocol and enabled features, then test the proposed change on an isolated representative copy. Exercise reads, writes, schema changes, deletes, and recovery with each supported client. Reader features and writer-only features have different compatibility consequences.

Do not assume that reverting a property or downgrading a runtime reverses a protocol upgrade. Some features can be dropped only through a supported procedure; others are not removable. Define the fallback before enabling the feature, potentially retaining a compatible table or delaying adoption until clients upgrade. The decision balances a measured operational benefit against the maintenance burden of supporting every required consumer.

94. How would you roll out a column rename or type change across producers, tables, streams, and downstream consumers?

Use an expand-and-contract migration when consumers cannot change together. Inventory dependencies through lineage plus code and configuration searches, including external readers that lineage might not capture. Publish the new field or compatible representation first, with explicit conversion rules, null handling, and a transition period.

Backfill and validate the new representation, then update producers and consumers in a controlled order. For a type change, test overflow, precision, timestamp interpretation, and malformed historical values rather than checking only successful casts. Monitor use of the old interface before retiring it.

Evaluate column-mapping and protocol requirements for a physical rename, plus runtime-specific restrictions on CDF and streaming across nonadditive schema changes. A state-schema change may require rebuilding a stream with a new checkpoint. Preserve the old contract or a compatibility view until cutover evidence is satisfactory. A metadata-only table change can still be a breaking application change, so rollback must cover code, data, and consumer expectations.

95. How would you select clustering keys and verify that a table-layout change actually helps the workload?

Choose keys from observed selective filters and workload importance, not merely from the columns with the highest cardinality. Examine query history, scanned bytes, file pruning, filter combinations, table growth, and write patterns. A customer identifier may help frequent customer lookups, while a date key may matter more for time-bounded reporting.

Evaluate liquid clustering where supported, recognizing that it cannot coexist with directory partitioning or Z-ordering on the same table. Changing keys does not instantly reorganize all historical data. Include the intended optimization work in the experiment, and assess automatic key selection only where its prerequisites hold.

Benchmark representative queries against equivalent data and comparable cache conditions. Measure correctness, scan volume, latency distribution, ingestion overhead, maintenance cost, and total workload spend. Retain queries unlikely to benefit as controls. A layout that speeds one dashboard but greatly increases maintenance or harms the dominant workload is not a successful optimization.

96. A join is dominated by one hot key. How would you distinguish a semantic data problem from execution skew and choose a remedy?

Check expected join cardinality before treating the hot key as a tuning problem. Count each side's rows for that key and confirm whether their product represents legitimate matches. Duplicate dimension records, missing predicates, null-safe matching of unknown keys, or an unintended many-to-many relationship can create enormous output that no partition setting fixes.

If the relationship is wrong, repair the keys or grain. Use a semi join for existence checks or business-approved aggregation when full pairwise matches are unnecessary. Do not arbitrarily deduplicate records simply to make the job finish.

For genuine execution skew, inspect task duration, shuffle size, spill, and the physical plan. Evaluate supported AQE skew handling, broadcast only a safely bounded side, or isolate heavy keys. Salting requires replicating the correct opposite-side rows and preserving exact join semantics. Validate output multiplicity and totals after each remedy; reducing the slowest task while changing the answer is a correctness failure.

97. How would your investigation differ for driver out-of-memory failures and executor out-of-memory failures?

Locate the failing process and memory category before resizing anything. Driver failures often follow collect(), toPandas(), oversized local results, excessive task metadata, or large query plans. Remove unbounded result materialization, keep processing distributed, and write results to governed storage; adding workers does not enlarge the driver.

Executor failures point toward task-sized problems such as skewed partitions, large shuffle groups, an oversized broadcast, retained caches, Python worker memory, or native-memory pressure. Compare task metrics, spill, garbage collection, partition sizes, and failure concentration. Reduce per-task data or representation size and correct the physical plan before increasing memory.

Distinguish JVM heap from memory overhead and container termination, because the remedies differ. Reproduce on representative data and measure whether the fix redistributes work rather than hiding growth temporarily. Compute size and access mode also constrain available configuration and diagnostics. A bounded output sample can aid debugging, but collecting the whole failing dataset makes the investigation itself unsafe.

98. How would you benchmark Photon and explain a workload that shows little benefit?

Benchmark the actual workload on comparable eligible compute with and without Photon where the product allows that comparison. Keep runtime, data snapshot, concurrency, hardware class, and cache conditions controlled. Repeat trials and compare result correctness, median and tail latency, throughput, and total execution cost rather than one unusually fast run.

Inspect the executed plan to establish which expensive operations used Photon and where execution fell back. Work dominated by Python UDFs, unsupported operations, external-service waits, startup, or orchestration may gain little from a faster native query engine. Very short queries can be dominated by planning and scheduling rather than data processing.

Separate a lack of eligible work from a poor data layout or skew that still needs diagnosis. SQL warehouses already use Photon, so switching a warehouse label is not a valid on/off experiment. Accept Photon based on measured service-level and cost improvement for the workload, not a universal speedup percentage.

99. A dashboard is slow only during business-hour concurrency peaks. How would you separate queueing, compute limits, and query inefficiency?

Break user-perceived latency into scheduling or queue time, query execution, and result fetching. Compare the same dashboard queries during quiet and peak periods, then align those measurements with queued queries, active queries, warehouse cluster count, scaling events, and configured capacity.

If execution time is stable but queueing grows, investigate concurrency capacity, scaling limits, competing workloads, and synchronized refresh schedules. Test workload separation or additional concurrency capacity before simply enlarging each cluster. If execution slows under load, inspect CPU pressure, spill, storage contention, and the query profile. A larger warehouse may help an individual expensive query, but cannot substitute for understanding the bottleneck.

Review repeated scans, unnecessary columns, joins, and dashboard fan-out. Benchmark with realistic simultaneous users and comparable cache conditions, measuring tail response time and cost per successful refresh. Include client fetching when server execution is already fast; otherwise a warehouse change may leave the user's experience unchanged.

100. How would you choose between serverless and classic compute for a workload with strict dependency, network, latency, and cost requirements?

Begin with a requirements matrix that separates hard constraints from preferences. Verify language and API support, native libraries, networking routes, private endpoints, data access, runtime control, diagnostics, and streaming mode for the exact cloud, region, and workload product. Serverless notebooks, jobs, SQL warehouses, and pipelines do not have identical capabilities.

Prefer serverless when its supported environment meets those requirements and reduced operational management is valuable. Choose appropriately configured classic compute when a mandatory dependency or control cannot be satisfied otherwise. For example, a workload that relies on RDD APIs or custom container behavior needs an explicit compatibility assessment rather than an assumed serverless migration.

Run representative connectivity, dependency, startup, burst-load, and recovery tests. Compare end-to-end latency and total cost, including idle capacity, retries, maintenance effort, storage, and network charges. Serverless is not automatically cheaper, and classic is not automatically more secure; security depends on the verified identity, network, and data-access design.

101. How would you migrate externally managed data into Unity Catalog managed tables while preserving consumers and rollback options?

Inventory table-name and path-based consumers, external writers, storage ownership, permissions, protocol features, and recovery requirements before moving data. Determine whether the source qualifies for supported ALTER TABLE ... SET MANAGED conversion; otherwise plan a separately validated copy and cutover. Managed-table adoption changes lifecycle responsibilities, not just a catalog label.

Capture a consistent starting snapshot and a strategy for changes arriving during migration. Compare schema, keys, counts, business totals, and required history on the destination. Test every critical engine through the supported managed-table access path rather than assuming old storage URLs remain valid.

Move consumers through a stable view or controlled configuration change, then retire external writes at an explicit boundary. Preserve the original data and migration evidence for the approved rollback window. If new writes occur after cutover, rollback requires reconciling those changes; switching a name back alone loses them. Verify grants and operating costs before removing the legacy path.

102. How would you prevent direct cloud-storage access from bypassing Unity Catalog policies?

Enforce the boundary in cloud identity and storage policy as well as in Unity Catalog. A table mask cannot protect files from an identity that independently has cloud permission to read them. Restrict managed storage to the identities required by Unity Catalog, remove broad user and workload grants, and constrain who can assume or modify those identities.

Use storage credentials and external locations for governed access, with narrowly scoped permissions. For automation, use service identities and supported OAuth or federation rather than distributing reusable bucket credentials. Keep administrative and break-glass privileges controlled and auditable.

Test both allowed table queries and denied direct-object reads using representative identities, including external tools. Review bucket policies, role trust, credential distribution, network paths, and cloud access logs alongside Databricks audit records. Network isolation adds protection but does not replace authorization. Exceptions for independently managed external data need explicit ownership and controls because Unity Catalog does not automatically govern access performed outside its supported paths.

103. What must a cross-region disaster-recovery plan preserve beyond table files, and how would you test its RPO and RTO?

Preserve the executable platform and its dependencies, not only data files. The plan needs table metadata and transaction logs, permissions, identities, jobs, code, library artifacts, configuration, connection definitions, network and encryption dependencies, and a supported streaming recovery strategy. Record which external sources and downstream services can operate from the secondary region.

Define RPO as acceptable data loss and RTO as time to restore the agreed business service. Managed disaster recovery is gated, with asset-specific coverage; external-table data and some preview resources need separate assessment. Do not infer complete protection from enabling one replication category.

Run a controlled regional-loss exercise using a known input sequence. Measure the newest recoverable business event and the time until consumers receive validated results. Test fencing the old primary, credentials, routing, duplicate suppression, backlog recovery, and failback. Replication success alone does not establish application recovery. Retain evidence of gaps and assign remediation before claiming the objectives are met.

104. How would you respond to an accidental destructive table change when time travel is available but retention is limited?

Contain further damage first: pause the responsible writer and downstream publication where appropriate, preserve evidence, and prevent scheduled cleanup from destroying the needed recovery files. Identify the destructive commit, affected keys, and last correct version from history, then verify that the older data is actually readable.

These read-only SQL examples assume an existing authorized table; version 123 is illustrative and must be replaced with a verified retained version.

SQL example

DESCRIBE HISTORY production.finance.invoice_lines;

SELECT COUNT(*) AS retained_row_count
FROM production.finance.invoice_lines VERSION AS OF 123

DESCRIBE HISTORY production.finance.invoice_lines;

SELECT COUNT(*) AS retained_row_count
FROM production.finance.invoice_lines VERSION AS OF 123

DESCRIBE HISTORY production.finance.invoice_lines;

SELECT COUNT(*) AS retained_row_count
FROM production.finance.invoice_lines VERSION AS OF 123

Compare the recovered snapshot in isolation before deciding between a targeted repair and a full restore. A full restore can discard legitimate changes made afterward unless they are explicitly reapplied. RESTORE creates a new data-changing commit, so downstream streams may process its effects again.

If retention or VACUUM has removed required files, history alone cannot recover them; use an independent backup or source replay. Validate business totals and downstream consistency before resuming normal processing.

105. How would you design and verify a sensitive-record deletion process across current tables, retained files, derived datasets, and downstream copies?

Define the record identity and all representations of it, then trace the deletion across source ingestion, current tables, derived datasets, caches, exports, shares, and downstream owners. Establish an approved retention and recovery policy with the responsible privacy and security teams; engineering implementation alone cannot establish legal compliance.

Delete or appropriately transform current records, and prevent source replay from reintroducing them. Distinguish logical deletion from physical removal: deletion vectors can leave data in existing files, and obsolete versions remain until the required rewrite and retention-aware cleanup occur. Verify the applicable purge process, followed by VACUUM when safe; do not disable retention safeguards casually.

Track replicas, backups, cached results, and recipient-held extracts separately. Revoking a share blocks future access but cannot retract copies already downloaded. Record evidence for each destination, including unresolved retention exceptions and owner acknowledgments. Verify absence from authorized query surfaces and the completion of physical-cleanup obligations without exposing the sensitive values in the verification logs.

106. Which freshness, completeness, correctness, and operational signals would you include in a production data pipeline's service objectives?

Define objectives at the data-product boundary, where a consumer can use the result. Freshness measures the delay from the relevant source event or availability time to publication; completeness measures expected inputs accounted for; correctness measures business invariants, duplicates, totals, and agreed quality rules. Each needs a denominator, measurement window, owner, and explicit treatment of late data.

Add availability of the serving interface, source backlog, watermark progress, rejected-record rate, state growth, retry frequency, failed runs, and recovery time. Track cost per useful output or refresh separately from reliability. A successful job may still produce stale or incomplete data.

For an hourly orders product, alert when the closed source interval is not reconciled by its deadline, even if the latest run succeeded. Use warning thresholds for trends and paging for user-impacting breaches. Link alerts to runbooks and source-to-output evidence so operators can distinguish a quiet source from a broken ingestion path.

107. How would you combine lineage and audit evidence to investigate an unexpected exposure of a sensitive column?

Contain the suspected exposure while preserving audit evidence, then reconstruct who could access which representation of the column during the incident window. Use column lineage to identify derived tables, views, jobs, dashboards, and exports, but treat missing lineage as an investigation gap rather than proof that no copy exists.

Correlate audit events and query history with identities, group membership changes, grants, object ownership, policy changes, and deployment times. Check the actual filter or mask logic under the affected identity. A policy on the source table does not necessarily sanitize a previously materialized downstream copy.

Investigate direct cloud access separately because it can bypass Unity Catalog controls and its visibility. Preserve cloud access logs and relevant external-system records. Distinguish demonstrated reads, possible access, and unverified downstream distribution in the incident report. After remediation, repeat negative access tests and trace derived copies; restoring the original mask alone may leave the exposure elsewhere.

108. How would you promote a bundle through development, staging, and production while keeping configuration and rollback under control?

Promote the same reviewed code and packaged artifacts through environment-specific targets, rather than rebuilding production from an untracked notebook state. Declarative Automation Bundles, formerly Databricks Asset Bundles, version resource definitions alongside code. Keep target configuration explicit for identities, catalogs, compute, schedules, and storage, while keeping credentials outside source control.

Validate bundle configuration and run unit, integration, permission, and data-quality tests in staging. Review the intended production changes, deploy with a controlled service identity, and record the release commit, artifact versions, configuration, and observed resource state. Prevent multiple deployment processes from racing over the same resources.

Define rollback separately for code, resource configuration, and data. Redeploying an earlier artifact does not undo a schema migration, table write, or external effect. Use backward-compatible changes and a tested data-repair plan where necessary. Verify production output and service objectives after deployment before retiring the previous release path.

109. How would you secure unattended deployments and job execution without tying them to one employee's credentials?

Separate the deployment identity from the job's run identity when their privileges differ. Give automation stable service principals owned by a team, with documented lifecycle and emergency access, rather than relying on one employee's account or personal token.

Use supported workload identity federation where available, or OAuth machine-to-machine authentication with securely managed credentials and automated token refresh. Restrict permissions to the necessary workspace resources, compute policies, and data objects. Reading a table normally requires USE CATALOG, USE SCHEMA, and SELECT; deployment permission does not automatically grant the job its data access.

Keep secrets out of notebooks, bundles, logs, and task parameters. Secret redaction is not a security boundary, so control who can read or execute code that accesses them. Test execution after removing the original developer's access, and test credential rotation without downtime. Monitor audit records, unexpected privilege changes, and orphaned identities so the design remains maintainable after team changes.

110. How would you build a failure-injection test that proves a pipeline can retry safely after a partial write?

Build the test around the dangerous uncertainty window: the sink has accepted an effect, but the pipeline has not recorded completion. Use isolated test tables and a fake external service, never production side effects. Provide a fixed input set containing duplicates, updates, deletes, and a known expected final result.

Inject failures before a write, between destination writes, after sink commit, and before checkpoint completion. Restart from the same checkpoint and retry the same business operation. Assert the full expected state, not just successful termination: no missing events, no repeated effects, correct ordering, and consistent processing records.

For eligible multi-table SQL transactions, verify atomic rollback. For destinations outside that boundary, verify durable idempotency or outbox recovery. Also test a new query generation so reused batch numbers cannot suppress legitimate work. Let errors propagate rather than marking incomplete work successful, and fully consume stateful batch output. Save failure positions and reconciliation results as repeatable release evidence.

111. How would you upgrade the runtime and libraries of a critical job without assuming that passing unit tests guarantees compatibility?

Create a compatibility inventory covering the runtime, language and JVM dependencies, connectors, native libraries, access mode, Spark settings, table features, and external consumers. Read the applicable release and migration notes, then pin a candidate environment instead of testing against an unspecified latest version.

Run representative end-to-end workloads against isolated outputs. Include malformed inputs, nulls, decimals, timestamps, UDFs, large shuffles, concurrency, and restart scenarios. Compare data results, schemas, physical plans, latency, and cost with the current release. Unit tests rarely exercise distributed execution or service-level permissions adequately.

For streams, verify checkpoint compatibility and rollback restrictions before the first upgraded run. Avoid enabling irreversible table features during the same rollout unless separately approved. Use a canary or shadow run, monitor a full relevant workload cycle, and retain the old artifacts and configuration. Roll back through a tested path; if state or data has changed incompatibly, rebuilding or repairing may be required instead of simply selecting the previous runtime.

112. How would you migrate legacy DBFS-root or mount-based workloads to governed storage without breaking their dependencies?

Inventory every dependency on legacy paths, including notebooks, jobs, libraries, init scripts, configuration, checkpoints, schema metadata, and external integrations. DBFS root and mounts are deprecated patterns, so map tabular data to Unity Catalog tables and governed file assets to volumes or appropriate external locations.

Create the destination objects and least-privilege access before moving consumers. Keep table storage separate from volumes, and place streaming metadata in durable locations outside table data directories. Test the supported APIs and path semantics on the intended compute; a path-string replacement does not establish compatibility.

Migrate a bounded workload first, compare content and permissions, and cut over consumers through versioned configuration. Checkpoint relocation deserves a specific supported recovery plan because changing its location can start a fresh query. Preserve legacy data for an agreed rollback interval, reconcile new writes if rollback is needed, and retire mount credentials only after all known consumers have been verified.

113. How would you decide between governed data sharing, federation, and copying extracts for an external consumer?

Start with the direction of access and the consumer's capabilities. OpenSharing is a candidate for governed cross-organization delivery of supported assets without maintaining a bespoke extract pipeline. Verify the recipient protocol, asset types, authentication, update semantics, auditing, and cross-region egress costs before choosing it.

Federation is appropriate when the querying platform can access a supported remote system and source-side load is acceptable. Databricks Lakehouse Federation primarily provides governed reads into Databricks; it is not a generic outbound-sharing replacement. Evaluate pushdown, remote availability, concurrency, and data-residency constraints for the actual direction of use.

Use extracts when the recipient requires offline data, an incompatible system, or an immutable delivery snapshot. Accept the additional responsibilities for encryption, manifests, freshness, retention, corrections, and deletion propagation. In every approach, specify who owns copies and how access is revoked. Revocation cannot erase an extract that the recipient already retained, so technical controls and delivery agreements must align.

114. What compatibility and governance questions must be answered before multiple engines access the same open table data?

Check the table protocol and every enabled feature against each engine's reader and writer capabilities. Recognizing Parquet files or the Delta name is not enough. Verify deletion vectors, column mapping, schema evolution, timestamp and decimal semantics, catalog integration, and any required compatibility metadata for the chosen access method.

Define one supported coordination model for writes. Engines must participate correctly in transaction and catalog-commit rules; independent file replacement is not a safe way to update an open table. Test concurrent changes and failure recovery with the actual connector versions, including the oldest required client.

Confirm how identities, privileges, row filters, and masks are enforced for every access path. Direct cloud credentials can bypass Unity Catalog governance, and not every external client supports every governed-table feature. Establish ownership of optimization, retention, schema changes, and incident recovery. Approve interoperability from demonstrated behavior, not from the storage format's openness alone.

115. How would you promote and roll back a registered ML model while preserving evidence about its training run and approvals?

Promote an immutable model version only after its evaluation and approval evidence meets the release criteria. Link the version to its MLflow run, code commit, training-data snapshot, dependency environment, parameters, metrics, and artifacts. Preserve these independently when table retention is shorter than the required reproducibility period.

Use controlled aliases or deployment configuration to identify approved versions, but do not treat registration or an alias assignment as proof of approval. Verify what the serving endpoint or batch job actually loads. Test signature compatibility, preprocessing, feature availability, latency, and performance on relevant subgroups before gradual rollout.

Retain the previously approved version and its runnable environment. A rollback must switch the actual consumer or serving configuration, verify readiness, and check observed predictions. If a bad model already produced business effects, reverting the endpoint does not undo them; define correction or replay separately. Record who approved promotion and rollback, the evidence used, and the resulting deployed version.

116. How would you prevent future information from leaking into historical training features or model evaluation?

Build features as they were knowable at each prediction time, then evaluate on information that was genuinely unseen. Use entity keys and point-in-time joins to select eligible feature values; aggregate only observations available before the prediction cutoff. A current customer balance joined to a historical label can leak later activity even when the table join is technically correct.

Track event time separately from arrival or availability time where late corrections matter. An event dated before the prediction might still have arrived afterward, so an event-time condition alone can create hindsight leakage. Preserve historical revisions or an appropriate bitemporal representation when needed.

Split evaluation data by time and, where appropriate, by entity. Fit preprocessing, imputation, and feature selection only on training data, and account for label maturation. Point-in-time feature lookup is distinct from Delta table time travel. Log dataset snapshots, split rules, and transformation versions, then add tests that deliberately introduce future records and confirm they cannot affect earlier features.

117. Databricks usage doubled while row volume barely changed. How would you isolate the cost driver before changing compute size?

Attribute the change before resizing compute. Compare equal business periods by SKU, usage unit, product, workspace, job, warehouse, and available tags. This read-only SQL example requires access to the billing system table and uses illustrative comparison dates; it measures usage, not the final invoice.

SQL example

SELECT
  usage_date,
  sku_name,
  usage_unit,
  SUM(usage_quantity) AS quantity
FROM system.billing.usage
WHERE usage_date >= DATE '2026-10-01'
  AND usage_date < DATE '2026-10-15'
GROUP BY usage_date, sku_name, usage_unit
ORDER BY usage_date, sku_name,

SELECT
  usage_date,
  sku_name,
  usage_unit,
  SUM(usage_quantity) AS quantity
FROM system.billing.usage
WHERE usage_date >= DATE '2026-10-01'
  AND usage_date < DATE '2026-10-15'
GROUP BY usage_date, sku_name, usage_unit
ORDER BY usage_date, sku_name,

SELECT
  usage_date,
  sku_name,
  usage_unit,
  SUM(usage_quantity) AS quantity
FROM system.billing.usage
WHERE usage_date >= DATE '2026-10-01'
  AND usage_date < DATE '2026-10-15'
GROUP BY usage_date, sku_name, usage_unit
ORDER BY usage_date, sku_name,

Correlate the increase with runtime and configuration changes, retries, longer schedules, idle time, concurrency, maintenance, and new products. Similar row counts can hide wider records, more scanned bytes, lost pruning, skew, or repeated full refreshes.

Inspect execution metrics for the responsible workload and normalize cost against useful output and service objectives. Include cloud compute, storage, requests, and network charges where billed separately. Test one targeted remedy at a time; a smaller cluster that runs much longer may increase total cost.

118. How would you coordinate writes to two tables and an external API when not every destination can participate in one transaction?

Use the strongest available atomic boundary, then make the remaining effects recoverable. Databricks supports multi-statement and multi-table SQL transactions for eligible Unity Catalog managed tables with catalog commits on supported compute. Two ordinary notebook writes are not automatically such a transaction, and an external API does not join it.

Where eligible, commit both business-table changes and an outbox record together. A separate dispatcher sends the outbox event with a stable operation ID that the API durably deduplicates, then records delivery. If the response is lost after the API succeeds, retry the same ID rather than creating a new operation.

If the tables cannot share a transaction, use durable per-step status, idempotent writes, reconciliation, and explicit compensation where the business permits it. Without API idempotency or a reliable lookup, exactly-once external effects cannot be guaranteed after an ambiguous timeout. Monitor undelivered operations and define how consumers interpret partially completed work; job repair alone does not roll back prior effects.

119. How would you make a historical business report reproducible after source corrections, code changes, and table retention expiry?

Package the report as a reproducible release with a clearly defined business cutoff. Preserve the exact input snapshots or immutable extracts, transformation code, dependencies, parameters, reference data, time-zone settings, and final published artifact. Record checksums, row counts, totals, ownership, and approval evidence in a manifest.

Distinguish reproducing the originally published report from recomputing a corrected historical view. Source corrections should create a separately identified revision rather than silently changing the meaning of the old release. Capture both event-time and known-at-time rules where late information changes eligibility.

Table version numbers help identify inputs but do not preserve their underlying files after retention expiry. Keep independently retained, restorable data and artifacts for the required period, with access controls and compatible readers. Periodically reconstruct the report in a clean environment and compare its agreed outputs. A backup that exists but has never been read back is weak evidence of analytical reproducibility.

120. How would you review a proposed lakehouse design that promises zero duplicates, instant recovery, and lower costs without measured evidence?

Turn each promise into a bounded claim with assumptions and a measurable acceptance test. For zero duplicates, define the business event identity, source-replay contract, checkpoint behavior, sink idempotency, and external side effects. For recovery, specify failure scenarios, acceptable data loss, restored functionality, and measured RPO and RTO. For savings, define the baseline workload and complete cost boundary.

Request evidence from realistic volume, skew, concurrency, late arrivals, dependency failures, and region-loss exercises. Verify supported runtime, cloud, table features, and consumer compatibility. Include recovery from ambiguous sink outcomes and retention expiry, not just a clean restart.

Reject absolute guarantees that depend on unstated assumptions, but retain useful architectural ideas as hypotheses. Approve through staged tests with explicit pass criteria, owners, and fallback decisions. A defensible design explains where its guarantees stop and how exceptions are reconciled; confidence comes from repeatable evidence rather than optimistic diagrams or a successful demonstration.

Databricks Documentation and Further Reading

Scope: this guide covers Databricks data engineering, SQL analytics, Apache Spark, Delta Lake, and production architecture. Feature availability and behavior can depend on the cloud platform, workspace configuration, compute type, and Databricks Runtime or SQL warehouse release. Check the applicable documentation and stated example assumptions; no single runtime version is treated as universally current.

Use these curated references to check platform behavior, API contracts, and supported configurations. Follow the documentation for the relevant cloud and release when a feature or example has version-specific requirements.

Team Sherlock.sh

Building fraud intelligence for live high-stake video interactions (financial discussions, hiring interviews, board meeting etc).

Catch candidate fraud before it costs you.

Sherlock AI helps you detect AI-assisted, proxy, and deepfake candidates, so every hiring decision is backed by evidence.

Ask AI about Sherlock.sh

Similar Posts