Databricks Interview Questions (3 Years Experience)
60 Databricks and PySpark interview questions with simple answers, scenario questions, and a one-page cheat sheet, for data engineers with up to 3 years' experience.
SS
Sukanya Saha, Technology Consultant
Β·16 min read
Beginner friendly
Your project story (asked in every interview)
βTell me about a pipeline you builtβ decides most interviews. Practise this structure with your own project, or with ShopKart from this course:
Business goal: βLeadership needed daily revenue per city by 7 AM.β
Sources and volume: βJSON order files landing hourly in cloud storage (about N GB/day), and a customer CSV.β
Architecture: βAuto Loader into bronze, silver with validation, dedupe and MERGE, SCD2 customers, gold aggregates; Unity Catalog for access.β
A hard problem you solved: duplicates and late data (updated_at condition), skew, small files, schema changes.
Operations: Lakeflow Jobs with retries and alerts, Declarative Automation Bundles and CI/CD, data quality checks.
Result: βRuntime from 3 hours to 25 minutes; cost down 40%; zero manual runs.β Use your real numbers.
π― Fundamentals and architecture
Try to answer out loud first, then tap to check.
Q1What is Databricks and what problem does it solve?Fresher+
A unified data and AI platform built around a lakehouse: data stays in open formats in your cloud storage, Spark/Photon process it, Delta Lake makes it reliable, Unity Catalog governs it. It removes the need for separate lake and warehouse systems. (lesson 1)
Q2Data lake vs data warehouse vs lakehouse?Fresher+
Warehouse: structured, reliable, fast SQL, expensive, closed. Lake: cheap object storage for any data, but no transactions or quality guarantees. Lakehouse: lake storage plus a transactional table layer (Delta) for warehouse reliability and performance.
Q3Explain control plane vs compute plane.Fresher+
Control plane (Databricks-managed): UI, notebooks, jobs, cluster manager, metadata. Compute plane: where clusters and SQL warehouses process data, in your account (classic) or Databricks' (serverless). Data lives in your storage. (lesson 2)
Q4All-purpose vs job compute vs serverless vs SQL warehouse?Fresher+
All-purpose: interactive and shared, highest rate. Job compute: per-run, cheaper, for scheduled jobs. Serverless: managed by Databricks, instant start, no tuning. SQL warehouse: SQL and BI workloads with Photon.
Q5What is a DBU and how do you control cost?1β3 yrs+
Databricks Unit: normalised processing per hour; cost = DBUs Γ SKU rate (+ VMs on classic). Control with job compute/serverless, auto-termination, autoscaling, spot workers, cluster policies, right-sizing, Photon where it shortens runtime, and fixing inefficient code.
Q6ETL vs ELT, and which does Databricks favour?1β3 yrs+
ELT: land raw data first (bronze), transform inside the platform. Cheap storage and keeping raw data for reprocessing make ELT the norm on lakehouses.
Q7What is the Databricks Runtime and why pin LTS?1β3 yrs+
A versioned bundle of Spark, Delta, libraries and optimisations. LTS versions get long-term fixes, so production behaviour doesn't change unexpectedly; upgrades are tested deliberately.
Q8How do you manage secrets?1β3 yrs+
Secret scopes (Databricks-backed or Azure Key Vault/AWS-backed) and dbutils.secrets.get. Values are redacted in output; access is controlled by ACLs. Never hard-code or commit credentials.
π― Apache Spark internals
Try to answer out loud first, then tap to check.
Q1Driver vs executor?Fresher+
Driver: runs your program, builds and optimizes the plan, schedules tasks, collects results. Executors: JVM processes on workers that run tasks on partitions and store cached data. (lesson 3)
Q2Transformation vs action? Examples?Fresher+
Transformations (select, filter, withColumn, join, groupBy) are lazy and build a plan. Actions (count, show, collect, write, saveAsTable) trigger execution.
Q3What is lazy evaluation and its benefit?Fresher+
Spark defers execution until an action so Catalyst can optimize the whole plan: predicate pushdown, column pruning, combining steps, choosing join strategies.
Q4Narrow vs wide transformations?1β3 yrs+
Narrow: each output partition depends on one input partition (filter, select). Wide: needs data from many partitions, so a shuffle (groupBy, join, distinct, orderBy, repartition). Wide operations create stage boundaries.
Q5Job vs stage vs task?1β3 yrs+
Each action creates a job. A job is split into stages at shuffle boundaries. Each stage has one task per partition, executed in parallel on executor cores.
Q6What is a shuffle and why is it expensive?1β3 yrs+
Redistributing data across executors by key. It involves serialisation, disk writes and network transfer, and is often the bottleneck. Minimise with broadcast joins, early filtering and avoiding unnecessary wide operations.
Q7What is the Catalyst optimizer?1β3 yrs+
Spark SQL's optimizer: parses code into a logical plan, applies rule-based optimizations (pushdown, pruning, constant folding), chooses a physical plan (join strategies), then Tungsten generates efficient code. df.explain() shows the result.
Q8cache() vs persist()?1β3 yrs+
cache() is persist() with the default storage level (memory and disk for DataFrames). persist() lets you choose a level (MEMORY_ONLY, DISK_ONLY...). Both are lazy; the first action materialises them. Call unpersist() when done.
Q9Why is Parquet good for analytics?3+ yrs+
Columnar storage (read only needed columns), compression and encoding per column, and min/max statistics per row group for skipping. Delta adds file-level stats in the log.
Q10What happens if an executor dies mid-job?3+ yrs+
The driver reschedules its tasks on other executors, recomputing lost partitions from lineage (or re-reading shuffle files if available). The job continues; if the same task fails too many times (default 4), the job fails.
π― PySpark coding questions
Try to answer out loud first, then tap to check.
Q1Read a CSV with a header and a schema.Fresher+
spark.read.option("header", True).schema(schema).csv(path). Avoid inferSchema in production: it costs an extra pass and can guess wrong. (lesson 4)
Q2Keep the latest row per key.Fresher+
w = Window.partitionBy("id").orderBy(F.desc("updated_at")) then df.withColumn("rn", F.row_number().over(w)).filter("rn = 1").drop("rn").
Q3Top 3 products by revenue in each city.1β3 yrs+
Aggregate revenue by city and product, then dense_rank().over(Window.partitionBy("city").orderBy(F.desc("revenue"))) and filter rank β€ 3.
Q4Running total of revenue per customer by date.1β3 yrs+
Q6Difference between orders today and yesterday per product.1β3 yrs+
Daily counts per product, then F.lag("orders").over(Window.partitionBy("product").orderBy("day")) and subtract.
Q7Count nulls in every column.1β3 yrs+
df.select([F.count(F.when(F.col(c).isNull(), c)).alias(c) for c in df.columns]).
Q8Flatten a nested JSON with an array of items.3+ yrs+
Use F.explode("items") (or explode_outer to keep empty arrays) to get one row per item, then select nested fields with col("item.sku"). For structs, select("s.*") expands fields.
π― Delta Lake
Try to answer out loud first, then tap to check.
Q1What is Delta Lake?Fresher+
An open table format: Parquet files plus a transaction log (_delta_log), giving ACID, updates/deletes/MERGE, time travel, schema enforcement/evolution and performance features. (lesson 5)
Q2How does time travel work?Fresher+
Every commit is a version in the log. Query with VERSION AS OF n or TIMESTAMP AS OF ts; RESTORE rolls the table back. Limited by VACUUM (data files, 7 days default) and log retention (30 days default).
Q3Explain the transaction log and checkpoints.1β3 yrs+
Ordered JSON commits record add/remove file actions and metadata; every 10 commits a Parquet checkpoint snapshots the state so readers don't replay thousands of JSON files.
Q4How does MERGE work, and its common error?1β3 yrs+
Joins source to target on a condition; matched rows can be updated/deleted, unmatched source rows inserted, unmatched target rows deleted (NOT MATCHED BY SOURCE). It fails if multiple source rows match one target row: dedupe the source first.
Q5Schema enforcement vs evolution?1β3 yrs+
Enforcement rejects writes whose schema doesn't match the table. Evolution (mergeSchema option, or automatic schema evolution for MERGE) allows intended changes like new columns.
Q6OPTIMIZE, ZORDER, VACUUM?1β3 yrs+
OPTIMIZE compacts small files; ZORDER BY co-locates values in files for data skipping; VACUUM deletes unreferenced files older than the retention period.
Q7What is liquid clustering?1β3 yrs+
CLUSTER BY on a table: incremental, flexible clustering that replaces partitioning and Z-ORDER for new tables. Keys can be changed without rewriting existing data; OPTIMIZE clusters new data incrementally.
Q8What is Change Data Feed?1β3 yrs+
With delta.enableChangeDataFeed = true, Delta records row-level changes (insert, update_preimage, update_postimage, delete) readable with table_changes() or readChangeFeed, so downstream jobs process only changes.
Q9How does Delta handle concurrent writes?3+ yrs+
Optimistic concurrency: writers prepare files, then attempt to commit the next version; on conflict with a concurrent commit that touched the same data, the commit fails (ConcurrentAppendException etc.) and can be retried. Appends rarely conflict.
Q10When would you still partition a Delta table?3+ yrs+
Very large tables (TB+) with a low-cardinality column that almost every query filters on (e.g. date), and enough data per partition (β₯1 GB). Otherwise prefer liquid clustering; over-partitioning causes small files.
π― Pipelines, medallion and streaming
Try to answer out loud first, then tap to check.
Q1Explain bronze, silver, gold.Fresher+
Bronze: raw, append-only with load metadata. Silver: validated, typed, de-duplicated, conformed (MERGE, SCD). Gold: business aggregates or star schemas. (lesson 6)
Q2How do you make pipelines idempotent?1β3 yrs+
MERGE on keys (with updated_at conditions), overwrite derived tables/partitions entirely, checkpoints/Auto Loader for incremental reads, deterministic run parameters.
Q3SCD Type 1 vs Type 2?1β3 yrs+
Type 1 overwrites attributes (no history). Type 2 closes the current row (valid_to, is_current=false) and inserts a new version, preserving history for point-in-time analysis.
Q4How do you handle late-arriving data?1β3 yrs+
Event/updated_at timestamps, keep-latest dedupe, conditional MERGE, recompute affected gold dates; in streaming, watermarks define how late data may be.
Q5What is Auto Loader?1β3 yrs+
cloudFiles source for incremental file ingestion with checkpointed file tracking, schema inference/evolution, rescued data, and listing or notification modes. (lesson 7)
Q6trigger(availableNow=True)?1β3 yrs+
Processes all available data in one or more micro-batches, then stops. Turns streaming code into an incremental batch job.
Q7How do you upsert from a stream?1β3 yrs+
foreachBatch: dedupe each micro-batch, then DeltaTable.merge into the target; keep it idempotent.
Q8Explain watermarks.3+ yrs+
Max seen event time minus a threshold. Later records are dropped from stateful operations, and older state is removed, bounding memory for aggregations and dedup.
Q9Streaming table vs materialized view?3+ yrs+
Streaming table: each source row processed once, for append-style ingestion. Materialized view: stored query result kept correct on refresh, for aggregates and joins. (lesson 9)
Q10What are expectations?3+ yrs+
Declarative data quality constraints in pipelines with warn/drop/fail policies and metrics in the event log.
π― Unity Catalog, jobs and CI/CD
Try to answer out loud first, then tap to check.
Q1What is the three-level namespace?Fresher+
catalog.schema.table, managed by a Unity Catalog metastore shared across workspaces. (lesson 8)
Q2Managed vs external tables?1β3 yrs+
Managed: UC controls storage and lifecycle (DROP deletes data). External: data at a path you control via an external location; DROP removes metadata only.
Q3What privileges are needed to query a table?1β3 yrs+
USE CATALOG on the catalog, USE SCHEMA on the schema, SELECT on the table (or inherited from schema/catalog).
Q4How do you restrict rows and columns?1β3 yrs+
Row filters and column masks (SQL UDFs attached to the table), or dynamic views using is_account_group_member().
Q5How do tasks share values in a job?1β3 yrs+
dbutils.jobs.taskValues.set/get, or references like {{tasks.<key>.values.<name>}}. Job parameters are read with dbutils.widgets.get. (lesson 10)
Q6How do you deploy Databricks code to production?3+ yrs+
Declarative Automation Bundles (formerly Databricks Asset Bundles) in Git; CI runs tests and bundle validate; CD deploys to staging then prod with a service principal; separate environments by workspace and/or catalog.
Q7How do you monitor pipelines?3+ yrs+
Job failure/duration alerts, pipeline event logs and expectation metrics, row-count and freshness checks on gold, and system tables (job runs, billing, audit) queried in dashboards.
π― Performance
Try to answer out loud first, then tap to check.
Q1Broadcast join: what and when?1β3 yrs+
Ship the small table to every executor to avoid shuffling the large one; automatic under the threshold (10 MB default) or via broadcast(). Avoid for large tables (OOM risk). (lesson 11)
Q2How do you detect and fix skew?1β3 yrs+
Spark UI: max task time and shuffle read far above median. Fix with AQE skew join, broadcast, isolating hot keys, or salting.
Q3What is AQE?1β3 yrs+
Adaptive Query Execution re-optimizes at runtime with real statistics: coalesces shuffle partitions, switches to broadcast joins, splits skewed partitions.
Q4What is the small files problem and the fix?1β3 yrs+
Many tiny files add listing and open overhead and slow reads. Fix with OPTIMIZE, optimized writes/auto compaction, liquid clustering, sensible partitioning, and predictive optimization.
Q5How do you choose shuffle partitions?3+ yrs+
Aim for ~100β200 MB per partition and at least the number of cores; rely on AQE coalescing (or 'auto' on Databricks) instead of a fixed 200.
Q6Driver OOM causes?3+ yrs+
collect/toPandas on big data, oversized broadcasts, huge plans from loops of withColumn, tracking too many files/partitions.
Q7Why might Photon not speed up a job?3+ yrs+
If time is spent in Python UDFs, external calls, or unsupported operations that fall back to the standard engine, or if the job is I/O or skew bound. Check the query profile to see what ran in Photon.
Scenario questions (3 years experience)
π― Real-world scenarios
Try to answer out loud first, then tap to check.
Q1The daily job usually takes 20 minutes but today took 3 hours. What do you check?3+ yrs+
Input volume change (a backfill or duplicate files), skew from a new hot key (task time distribution), a join that stopped broadcasting (table grew past the threshold), small-file explosion, spot instance loss, or cluster/runtime changes. Compare Spark UI and run metrics with a normal day.
Q2Gold revenue is double for yesterday. How do you investigate and fix it?3+ yrs+
Check bronze for files loaded twice (_source_file, _ingested_at), check silver for duplicate keys, review the job history for a re-run with append instead of MERGE. Fix the idempotency bug, RESTORE or rebuild affected silver/gold from bronze for those dates, and add a uniqueness check.
Q3The source added a new column and the pipeline broke. How do you design for this?3+ yrs+
Bronze with schema evolution (Auto Loader addNewColumns or rescue mode), job retries for the planned stop on schema change, silver with explicit column selection so new columns don't silently flow into gold, and alerts when _rescued_data is non-empty.
Q4You must load 5 years of history (50 TB) once, then daily increments.3+ yrs+
Separate backfill job processing by date ranges in parallel batches with MERGE/overwrite per range, on bigger job compute; tune file sizes and clustering; then switch to the incremental Auto Loader / availableNow job with checkpoints. Validate counts and totals per period.
Q5A team asks for real-time dashboards from Kafka.3+ yrs+
Structured Streaming from Kafka into bronze Delta with checkpoints, silver with watermark-based dedupe, gold via a streaming aggregation or materialized views refreshed frequently; define the latency requirement (seconds vs minutes) before choosing continuous vs processingTime triggers to control cost.
Q6Security asks you to ensure only HR sees salaries.3+ yrs+
Put the table in a restricted schema in Unity Catalog, grant SELECT to the HR group only, add a column mask for salary for any shared views, audit access with system tables, and never copy salaries to wider gold tables.
Q7Costs went up 50% this month. What do you do?3+ yrs+
Query system.billing.usage by job/cluster/user; look for all-purpose clusters running jobs, missing auto-termination, oversized clusters, jobs running more often or longer, unnecessary Photon or serverless usage; fix and add cluster policies and budget alerts.
One-page cheat sheet
databricks-cheat-sheet.pyPython
# READ / WRITEdf = spark.read.schema(schema).json("/Volumes/cat/sch/vol/path/")df.write.mode("append").saveAsTable("cat.sch.table") # Delta by defaultspark.table("cat.sch.table")# CLEANdf.filter(F.col("qty") > 0).withColumn("amount", F.col("qty") * F.col("price"))w = Window.partitionBy("id").orderBy(F.desc("updated_at"))latest = df.withColumn("rn", F.row_number().over(w)).filter("rn = 1").drop("rn")# UPSERTDeltaTable.forName(spark, "cat.sch.t").alias("t").merge(src.alias("s"), "t.id = s.id") \ .whenMatchedUpdateAll("s.updated_at > t.updated_at").whenNotMatchedInsertAll().execute()# INCREMENTAL (Auto Loader)spark.readStream.format("cloudFiles").option("cloudFiles.format", "json").load(path) \ .writeStream.option("checkpointLocation", ckpt).trigger(availableNow=True).toTable("cat.sch.bronze")# DELTA SQL# DESCRIBE HISTORY t Β· SELECT * FROM t VERSION AS OF 3 Β· RESTORE TABLE t TO VERSION AS OF 3# OPTIMIZE t ZORDER BY (col) Β· VACUUM t Β· CREATE TABLE t CLUSTER BY (col) AS ...# UNITY CATALOG# GRANT USE CATALOG ON CATALOG c TO `g`; GRANT USE SCHEMA, SELECT ON SCHEMA c.s TO `g`;# PERFORMANCEorders.join(F.broadcast(small), "id"); df.explain(); df.coalesce(1); df.repartition(64, "id")
Key takeaways
βInterviewers test understanding plus real trade-offs: always say why, not just what.
βPrepare one end-to-end project story with numbers.
βPractise PySpark window functions, dedupe, joins and MERGE until they're automatic.
βRevisit any lesson where an answer surprised you, then try again tomorrow.
Frequently asked questions
How should I prepare for a Databricks interview?
Be able to explain Spark internals (driver, executors, shuffle, stages), Delta Lake (log, MERGE, time travel, OPTIMIZE), the medallion architecture with SCD2, Auto Loader/streaming, Unity Catalog, and performance tuning. Practise PySpark coding (window functions, dedupe, joins) and prepare one project story you can explain end to end.
What do interviewers expect from someone with 3 years' experience?
Not just definitions: trade-offs and real situations. Why you chose MERGE over overwrite, how you handled late data, how you debugged a slow job in the Spark UI, how you deployed with CI/CD, and what you'd do differently.
Is PySpark coding asked in Databricks interviews?
Almost always. Common tasks: remove duplicates keeping the latest row, top N per group with window functions, running totals, joins with null handling, and reading/writing Delta tables. SQL equivalents are asked too.
Which Databricks certification should I take?
Databricks Certified Data Engineer Associate is the usual first step, then the Professional. This course covers most Associate topics; practise in Databricks Free Edition.
π§ Quick check: Databricks interview
1. Best way to keep only the latest record per order_id?
2. A MERGE fails with 'multiple source rows matched'. Fix?
3. Daily job reprocesses files it already loaded. What's missing?