Delta lake
Explain schema evolution using MergeSchema
To perform schema evolution:
- To evolve schema, set
.option('mergeSchema', 'true')while writing the dataframe - To enable type widening, enable it at the delta table's level
ALTER TABLE catalog.schema.my_table
SET TBLPROPERTIES (
'delta.enableTypeWidening' = 'true'
);
Schema evolution will either add a new column, or optionally widen the type of an existing column.
There can be 3 scenarios:
- A new column is added
- The new column is added for the incoming rows. The older rows get
Nullvalue in the newly added column.
- The new column is added for the incoming rows. The older rows get
- Existing Column modified (datatype is changed)
- If type widening is not enabled, write will fail with schema mismatch
- If type widening is enabled, will alter existing column and set its datatype to a wider type
- Existing column deleted
- Doesn't delete the col in existing table. Just puts value NULL for the deleted column.
Type widening datatypes: link
| Source type | Supported wider types |
|---|---|
BYTE |
SHORT, INT, BIGINT, DECIMAL, DOUBLE |
SHORT |
INT, BIGINT, DECIMAL, DOUBLE |
INT |
BIGINT, DECIMAL, DOUBLE |
BIGINT |
DECIMAL |
FLOAT |
DOUBLE |
DECIMAL |
DECIMAL with greater precision and scale |
DATE |
TIMESTAMP_NTZ |
VOID |
Any type |
Explain delta lake's history table
It contains the table level commit log of a delta table. One row per version (transaction).
Every write (insert, update, delete, merge, optimize, schema change, and so on) creates a new numbered version.
Delta records each one as a JSON commit file in the table’s _delta_log/ folder, and DESCRIBE HISTORY reads that log and shows it as a table.
-- SQL
DESCRIBE HISTORY sales; -- all versions, newest first
DESCRIBE HISTORY sales LIMIT 5; -- last 5 commits
DESCRIBE HISTORY delta.`/mnt/data/sales`; -- by path
| Column | What it tells you |
|---|---|
version |
Commit number, starting at 0 and increasing by one per commit |
timestamp |
When the commit happened |
userId / userName |
Who made the change |
operation |
What happened: WRITE, MERGE, UPDATE, DELETE, OPTIMIZE, RESTORE, STREAMING UPDATE, ADD COLUMNS, … |
operationParameters |
Details of that operation, such as write mode, the predicate of a delete or merge, or partitionBy |
operationMetrics |
Numbers about the change: numOutputRows, numFiles, numTargetRowsUpdated, numTargetRowsDeleted, and so on |
readVersion |
The version the transaction read before writing |
isolationLevel |
Serializable or WriteSerializable |
isBlindAppend |
True if the write only appended without reading existing data |
job, notebook, clusterId |
Where the write came from (on Databricks) |
userMetadata |
A custom note you attached to the commit |
engineInfo |
The Spark/Delta version that wrote the commit |
When is liquid clustering triggered?
3 triggers
- Trigger on write
- Manual trigger
- Automated trigger (databricks only feature)
TRIGGER ON WRITE
Liquid clustering happens at write-time. Every time delta writes writes to a table, liquid clustering is performed on it (INSERT, MERGE, COPY INTO etc). So, all liquid clustering work happens inside the spark jobs that are touching the table. There is no separate background service that continuously optimizes the tables.
MANUAL/EXPLICIT TRIGGER
Liquid clustering can be manually triggered via the optimize command
from delta.tables import *
deltaTable = DeltaTable.forPath(spark, "path/to/table")
deltaTable.optimize().executeCompaction()
OPTIMIZE table_name;
AUTOMATED TRIGGER (databricks only)
When predictive optimization is enabled (requires databricks premium plan), databricks will automatically run ANALYZE, OPTIMIZE, VACUUM operations - by queueing them as job to be run on serverless compute instances.
Since OPTIMIZE is being run, it will also end up triggering liquid clustering.
What happens during liquid-clustering?
- Delta reads clustering metadata - looks at existing files, their min/max ranges on clustering keys, clustering quality scores
- Incoming rows are sorted and grouped by the clustering keys.
- Delta will append rows into files whose key ranges are a good match for that particular row. If there is no existing file with a good match, it will create new file with tight range.
The computational cost is proportional only to the new data. There is no global-sort. No full table scan (only file statistics are read).
If liquid clustering finds that the existing data is horribly clustered, it won't re-organize and re-write the whole table. Instead, it will only rewrite a few of the worst files. If it sees diminishing returns, it will stop early.
Why? because it doesn't want to break streaming SLAs. Re-organizing the entire table may take a long time, breaking the SLA. So instead, it will fix only a few existing files on every run. Over time, as more and more writes trigger liquid clustering, the table will eventually become well-clustered.
So, in short, liquid clustering will touch a few files on every run, keeping the rewrite size small.
What is automated liquid clustering?
(Databricks only feature)
When automated liquid clustering is enabled, the runtime will analyze the historical query workload, and automatically identify the best columns for clustering. It will figure out the keys which will lead to cost savings from data skipping.
In this case, the liquid clustering columns won't need to be manually declared.
-- Enable automatic liquid clustering on an existing table,
-- including tables that previously had manually specified keys.
ALTER TABLE table1 CLUSTER BY AUTO;
-- Disable automatic liquid clustering on an existing table.
ALTER TABLE table1 CLUSTER BY NONE;
-- Disable automatic liquid clustering by setting the clustering keys
-- to chosen clustering columns or new columns.
ALTER TABLE table1 CLUSTER BY (column01, column02);
Source: Databricks: Delta Clustering: Enable/disable automatic liquid clustering
What triggers reclustering?
A re-clustering is triggered when:
- Files overlap on clustering keys
- There is fragmentation
- Query
What is auto compaction? How does it work?
Auto compaction kicks in when the number of file sizes is above a threshold (the spark configuration variable is spark.databricks.delta.autoCompact.minNumFiles). The output file size is controlled using spark.databricks.delta.autoCompact.maxFileSize.
Like liquid clustering, auto compaction comes in 2 flavours:
- Automated auto-compaction (Databricks only feature, part of Predictive Optimization) - the runtime will run OPTIMIZE, which will end up performing auto-compaction
- Non-automated auto-compaction - auto compaction will have to be performed by manually running
OPTIMIZEvia a spark job, or a user.
Auto compaction executes an OPTIMIZE command at the end of a transaction. Keep in mind that since OPTIMIZE is being run - if liquid clustering was enabled, then liquid clustering will also be performed on the table.
To enable auto compaction, following variables can be set:
- Table properties:
delta.autoOptimize.autoCompact - Spark Session setting:
spark.databricks.delta.autoCompact.enabled
The values these 2 settings take are:
| Options | Behavior |
|---|---|
auto (recommended) |
Tunes target file size while respecting other autotuning functionality. Requires Databricks Runtime 10.4 LTS or above. |
legacy |
Alias for true. Requires Databricks Runtime 10.4 LTS or above. |
true |
Use 128 MB as the target file size. No dynamic sizing. |
false |
Turns off auto compaction. Can be set at the session level to override auto compaction for all Delta tables modified in the workload. |
Source: Databricks: Auto compaction for Delta Lake on Databricks
What file sizes does auto compaction target?
Databricks aims for smaller file sizes for smaller tables, and larger file sizes for larger tables. The aim it to make sure that the number of files doesn't increase too much.
However, it won't set the file size dynamically if you've explicitly set target file size (set via delta table property delta.targetFileSize. Its default value is None).
| Table size | Target file size | Approximate number of files in table |
|---|---|---|
| 10 GB | 256 MB | 40 |
| 1 TB | 256 MB | 4096 |
| 2.56 TB | 256 MB | 10240 |
| 3 TB | 307 MB | 12108 |
| 5 TB | 512 MB | 17339 |
| 7 TB | 716 MB | 20784 |
| 10 TB | 1 GB | 24437 |
| 20 TB | 1 GB | 34437 |
| 50 TB | 1 GB | 64437 |
| 100 TB | 1 GB | 114437 |
What is predictive optimization?
This is a feature available for Unity Catalog managed tables. It requires databricks premium plan.
When predictive optimization is enabled, databricks will automatically run ANALYZE, OPTIMIZE, VACUUM operations - by queueing them as job to be run on serverless compute (you will be billed for this compute).
Since OPTMIZE is being run, it will end up triggering both liquid clustering and auto-compaction on tables.
Observability statistics for predictive optimization executions are stored in the table
system.storage.predictive_optimization_operations_history.
To explicitly enable/disable predictive optimization on a table:
ALTER CATALOG [catalog_name] { ENABLE | DISABLE | INHERIT } PREDICTIVE OPTIMIZATION;
ALTER { SCHEMA | DATABASE } schema_name { ENABLE | DISABLE | INHERIT } PREDICTIVE OPTIMIZATION;
How does z-order work?
NOTE: As of now (2025), liquid clustering is recommended over Z-ORDERING.
WARNING:
Very costly operation to perform. Z-order will lead to re-write amplification. Every
OPTIMIZE ZORDERwill rewrite large chunks of data.
- Writes rows with similar values close together, and stores min/max stats per file
- Improves file-level data skipping when queries are filtering on multiple columns
Now, spark can skip entire files by looking at the min/max stats. Very effective for range and equality filters
Z-ORDER has to be triggered manually (in pipelines or scheduled jobs).
So, use Z-ORDER only for legacy tables, and one-off historical backfills.
By default, simply prefer liquid clustering.
To run z-order:
OPTIMIZE orders
ZORDER BY (customer_id, order_date)
Explain z-order vs bucketing
Bucketing is not supported for delta tables.
Similar to partitioning+bucketing for normalparquet tables, partitioning+z-ordering is the way to go for delta tables.
However, it is still recommended to simply use liquid clustering instead of partitioning+z-ordering.
Zorder and bucketing solve completely different problems.
Zorder will help speed up writes through data-skipping. Bucketing will help speed up execution by preventing shuffles during joins and aggregations.
Z-order doesn't prevent the data-shuffle problem that bucketing does.
What is VACUUM?
Removing stale files by trimming history
VACUUM will:
- Trim data history by deleting snapshot files that are older than the specified time travel retention period.
- Physically delete dropped rows (that were soft-deleted via deletion vectors)
It is never run automatically. It will always have to be manually executed by a job or a user.
Delete old data files (loses history)
VACUUM events RETAIN 168 HOURS
Spark theory
Explain spark architecture
Apache Spark follows a distributed master-worker architecture with three main components:
Cluster Manager
- Manages cluster resources such as CPU and memory.
- Allocates resources to Spark applications.
- Launches executors on worker nodes.
- Examples: YARN, Kubernetes, and Spark Standalone.
Driver
- The brain of the Spark application.
- Creates the SparkSession and builds the execution plan.
- Converts operations into jobs, stages, and tasks.
- Schedules tasks across executors and coordinates execution.
Executors
- Worker processes responsible for actual data processing.
- Execute tasks on data partitions in parallel.
- Manage memory, caching, and shuffle data.
- Report execution status back to the Driver.
In short: The Driver coordinates, the Cluster Manager allocates resources, and Executors perform the computation.
Explain transformations vs actions
In Spark, operations are classified into Transformations and Actions.
Transformations
- Operations that create a new DataFrame or RDD from an existing one.
- They are evaluated lazily, meaning Spark doesn't execute them immediately.
- They build the execution plan (DAG).
- Examples: filter(), select(), groupBy(), join(), withColumn().
Actions
- Operations that trigger actual execution of the Spark job.
- They force Spark to execute the transformations defined earlier.
- Examples: show(), count(), collect(), write(), first().
Explain lazy evaluation in spark
In Spark, lazy evaluation means transformations are not executed immediately. Instead, Spark builds an execution plan (DAG) and executes it only when an action is triggered.
It allows Spark to optimize the entire computation pipeline before executing it.
Why is lazy evaluation useful?
- Allows Spark to optimize multiple transformations together.
- Avoids unnecessary computations.
- Enables techniques like predicate pushdown and column pruning.
How does spark do fault tolerance?
Spark provides fault tolerance primarily through RDD lineage, task retries, and data replication.
Spark achieves fault tolerance through recomputation rather than relying entirely on replication of intermediate data.
- RDD Lineage: Spark maintains the sequence of transformations used to create an RDD. If a partition is lost, Spark can recompute it from the original data using its lineage.
- Task Retry: If an executor fails while processing a task, Spark can reschedule that task on another executor.
- Data Replication: Cached data can be replicated across executors using persistence options such as MEMORYONLY2.
- Checkpointing: Spark can save intermediate data to reliable storage like ADLS or HDFS, reducing the need to recompute long transformation chains.
Example: If an executor crashes while processing a partition, Spark identifies the lost partition and recomputes it on another executor using lineage.
how to resolve data skewness?
Data skewness occurs when data is unevenly distributed across partitions, causing some Spark tasks to process significantly more data than others. This leads to stragglers and poor job performance.
I handle data skew using these techniques:
- Salting: Add a random key to skewed records to distribute them across multiple partitions, then aggregate again.
- Broadcast Join: If one table is small, broadcast it instead of performing a shuffle join.
- AQE (Adaptive Query Execution): Enable Spark's AQE to detect and optimize skewed joins automatically.
- Repartitioning: Redistribute data using appropriate partitioning keys.
- Skew-aware joins: Split heavily skewed keys and process them separately.
How to optimize data shuffling?
Data shuffling happens when Spark redistributes data across partitions, typically during joins, groupBy, distinct, and repartition operations. It involves network I/O and disk I/O, making it expensive.
I optimize shuffling using these techniques:
- Broadcast Joins: Broadcast smaller tables to avoid shuffling both datasets.
- Reduce Data Early: Apply filters and column pruning before joins and aggregations.
- Avoid Unnecessary Shuffles: Minimize repartition, distinct, and groupBy operations.
- Use AQE: Enable Adaptive Query Execution to optimize partition sizes and skewed joins.
- Optimize Partitioning: Choose appropriate partition counts and partitioning keys.
- Use Efficient Formats: Prefer Parquet or Delta to reduce data scanned and transferred.
Interview takeaway: I use Spark UI to identify shuffle read/write volume, spill to disk, and task duration, then optimize the operations responsible for excessive shuffling.
Explain MergeSchema vs OverwriteSchema
Overwriteschema - will delete existing schema, and use the new incoming schema only. May corrupt existing table. Older data remains recoverable through time travel.
MergeSchema - leads to schema evolution. Used when appending data to an existing location. Combines existing data with new data.
- Column added
- A new column is added to destination schema. Older rows get
Nullvalue in the newly added column.
- A new column is added to destination schema. Older rows get
- Column modified (datatype is changed)
- Will fail with schema mismatch
- Will apply type widening (existing datatype is changed to wider datatype)
- Column deleted
- Doesn't delete col in existing table. Just puts value NULL for the deleted column.
Type widening formats: link
| Source type | Supported wider types |
|---|---|
BYTE |
SHORT, INT, BIGINT, DECIMAL, DOUBLE |
SHORT |
INT, BIGINT, DECIMAL, DOUBLE |
INT |
BIGINT, DECIMAL, DOUBLE |
BIGINT |
DECIMAL |
FLOAT |
DOUBLE |
DECIMAL |
DECIMAL with greater precision and scale |
DATE |
TIMESTAMP_NTZ |
VOID |
Any type |
Explain checkpointing - what does it do?
Checkpoint materializes the data and cuts off the lineage.
Persist caches the computed data but keeps the lineage.
Checkpoint is primarily about lineage truncation.
- Marking - Marks df as "to be checkpointed"
- Materialization trigger - When action is triggered on this df, spark executes plan upto that point
- Write to storage - Once df is computed, it is written to physical files on disk
- Lineage truncation - delete logical plan that led upto that dataframe
- Reference update - future operation on df will point directly to files on disk, ignoring original files and transformations
Explain Jobs, Stages, Tasks
Spark breaks your work into a three-level hierarchy: job → stages → tasks. Each level is defined by a different trigger.
Interview one-liner:
- an action triggers a job
- shuffles split it into stages
- partitions decide the number of tasks
Job — created every time you call an action (count(), collect(), show(), write). Transformations like filter or select are lazy and create nothing until an action fires. One action usually means one job, though some actions spawn extra ones (e.g. schema inference on read.csv, or the sampling job behind sortBy).
Stage — Spark's DAG scheduler cuts each job into stages at shuffle boundaries. Narrow transformations (map, filter, withColumn) need no data movement, so they're pipelined together in one stage. Wide transformations (groupBy, join, repartition, distinct) need data redistributed across executors, which forces a new stage. So: number of stages ≈ number of shuffles + 1. Intermediate stages are ShuffleMapStages; the last one is the ResultStage.
Task — the actual unit of work sent to an executor core. Each stage runs one task per partition, all executing the same code on different slices of data. Stage 0's task count comes from your input partitions (e.g. file splits); after a shuffle it's spark.sql.shuffle.partitions (default 200, often coalesced by AQE).
Tasks in a stage run in parallel, but a stage after a shuffle waits for the previous stage to finish — which is why too few partitions underuse your cluster and skewed partitions create straggler tasks.
Explain parallelism when reading Parquet files
Read granularity is at row group level.
- The file has physical boundaries via row groups.
- While reading, spark makes virtual partitions based on
spark.sql.files.maxPartitionBytes. - Spark cannot break row groups. So it decides which partition a row group belongs to, based on the partition where the row group's middle byte falls.
- 1 partition is read by 1 task
Consequences:
- When row group size is small and partition size is large, multiple row groups will be read as part of a single partition
- When row group size is large, and partition size is small, splitting a file into more partitions than row groups will result in many empty partitions, with no row group to process within them

Why are UDFs slow?
Because of the serialization bottleneck
Moving data between jvm (spark) and python is very expensive
To run python code on data:
- Serialize: Convert JVM rows into Python-readable bytes (Pickling).
- Transfer: Send those bytes across a socket to a Python worker process.
- Deserialize: The Python worker un-pickles the bytes back into Python objects.
- Process & Repeat: After your logic runs, the whole process happens in reverse to get the result back to the JVM.
SOLUTION
Use arrow. Arrow memory format is readable by both jvm and python. So no serde is required.
Arrow is faster because arrow is column based, while pickling is row based. So arrow takes advantage of SIMD etc and gives a tremendous performance improvement.
spark.conf.set("spark.sql.execution.arrow.pyspark.enabled", "true")
Explain read modes in spark
There are 3 read modes
| Mode | Behavior |
|---|---|
PERMISSIVE |
Reads valid records and handles malformed records by setting corrupt fields to null. Default mode. |
DROPMALFORMED |
Drops malformed records entirely. |
FAILFAST |
Throws an exception immediately when malformed data is encountered. |
Explain write modes in spark
There are 4 write modes
| Mode | Behavior |
|---|---|
error / errorifexists |
Default mode. Throws an exception if the destination already exists. |
append |
Adds new records without modifying existing data. |
overwrite |
Replaces existing data with new data. |
ignore |
Skips writing if the destination already exists. |
Explain reduceByKey vs groupByKey
groupByKey shuffles all values belonging to a key, whereas reduceByKey performs local aggregation before the shuffle, reducing network traffic and memory usage. Therefore, use reduceByKey when you can express the operation as an associative and commutative reduction.
reduceByKey performs a Map-side Combine.
- How it works: It merges data locally on each executor before sending anything across the network. If an executor has ten "Apple" records, it reduces them to one "Apple" record with a sum and then shuffles that single record.
- Benefit: Massive reduction in network traffic and memory usage.
groupByKey is a "brute force" operation.
- How it works: It shuffles every single record across the network to the reducing executor. All values for a key are collected into a single list in memory.
- Risk: If you have a skewed key (e.g., millions of records for one "ID"), the executor will run out of memory (
OutOfMemoryError) because it tries to hold that entire list in RAM.
| - | reduceByKey |
groupByKey |
|---|---|---|
| Shuffle data | Less | More |
| Map-side combine | ✅ | ❌ |
| Memory usage | Lower | Higher |
| Requires aggregation function | ✅ | ❌ |
| Typical use | Aggregations | Need all values |
Pro Tip: In the DataFrame API, when you use df.groupBy("key").sum(), Spark is smart enough to use the reduceByKey logic under the hood. You don't have to worry about this choice unless you are working with the low-level RDD API.
Explain map vs flatmap
In PySpark, both map() and flatMap() are transformations used to process RDD elements.
Map
- Applies a function to each input element.
- Produces exactly one output element per input element.
- Preserves the one-to-one relationship.
FlatMap
- Applies a function to each input element.
- Each input can produce zero, one, or multiple output elements.
- Flattens the resulting collections into a single RDD.
Spark optimization
How do you do performance optimization?
Overall strategy is:
- Enable AQE
- Optimize joins
- Reduce the amount of data being processed
- Use caching and buffering to re-use lineages
- Use better data serialization formats
Key optimization techniques:
- Reduce the amount of data being processed
- Predicate Pushdown: Filter data as early as possible to reduce the amount of data scanned.
- Column Pruning: Select only required columns instead of reading entire datasets.
- Optimize joins
- Broadcast Join: Broadcast smaller datasets to avoid expensive shuffle joins.
- Data Skew Handling: Use salting, AQE, or skew join optimization to distribute data evenly.
- Partitioning: Choose appropriate partition sizes and avoid excessive small partitions.
- Caching: Cache frequently reused DataFrames to avoid recomputation.
- AQE (Adaptive Query Execution): Dynamically optimize query execution based on runtime statistics.
- File Compaction: Use Delta OPTIMIZE to combine small files and reduce file-reading overhead.
- Avoid UDFs: Prefer built-in Spark SQL functions because they benefit from Catalyst optimization.
- Join Optimization: Filter datasets before joining and select appropriate join strategies.
Explain projection pruning, predicate pushdown
Cut down the data as much as possible before processing it.
The words come from relational algebra
- Project = select column
- Predicate = filter condition
Projection pruning
Reduce the number of columns read.
Spark does this automatically via catalyst optimizer. If a column isn't used in any calculation, then it is simply not even read.
Predicate pushdown
Reduce the number of rows read, by pushing filters as close to data source as possible. Also done automatically by catalyst.
Shows up in df.explain(True) as:
PushedFilters: [GreaterThan(salary,100000)]
Pushdown depends on the data source. It won't work when filters use:
- UDFs
- complex expressions
- filtering after aggregation (eg -
HAVING COUNT(*) > 100;) - derives values
WHERE amount * 12 > 1000000;
- filtering after aggregation (eg -
How will you do join optimization
USE BUCKETING
Bucketing improves joins by pre-organizing data into buckets based on a join key, reducing or eliminating the need for a full shuffle during the join.
If the bucketed column is also the basis of the join, then the related rows are already within the same executor. This eliminates the need of a data shuffle.
FORCE BROADCAST JOIN
Using hint when the df is larger than autobroadcast threshold, but will still fit in memory.
from pyspark.sql.functions import broadcast
result = large_df.join(
broadcast(small_df),
"customer_id"
)
Cache and persist
Caching will cause AQE to fail.
Use it anyways when
- Recomputation is expensive
- The same df is used for many different downstream tasks, so repeating the lineage is necessary
AQE looks at statistics of data as it is written to shuffle files.
So it doesn't work well if data is cached, because the current state of the df is frozen. So AQE cannot optimize it.
Once data is cached, its execution plan in considered to be fixed. So AQE cannot modify it further.
AQE's effectiveness changes based on where data is stored. The shuffle data write has varying levels of AQE awareness:
- DISK_ONLY - full awareness. AQE handles everything perfectly. Can coalesce and change join type.
- MEMORYANDDISK - partial awareness. Cannot coalesce, can change join type
- Persisted delta tables - unaware during write
WHAT TO DO?
- Let AQE optimize before cache. Force a wide transformation before caching using an explicit repartition() etc.
.unpersist()dataframes as soon as their use is over
Explain AQE - what does it do?
Is a runtime optmizer for batch optimization tool where data is large. Won't work for streaming pipelines.
Does 3 things:
- Coalesce shuffle partitions
- Change join strategy
- Handle skewed joins
AQE looks at statistics of data as it is written to shuffle files. It is a runtime shuffle-stage-boundary optimizer.
What it does
COALESCE SHUFFLE PARTITIONS
After a shuffle stage is completed, AQE looks at the partition sizes, and coalesces the partitions smaller than minPartitionNum to achieve target size specified in advisoryPartitionSizeInBytes
Variables are set in:
spark.sql.adaptive.minPartitionSizespark.sql.adaptive.advisoryPartitionSizeInBytes
CHANGE JOIN STRATEGY
Looks at the sizes of data.
Uses variables in the scope spark.sql.adaptive
- Convert Shuffle sort merge join to Broadcast hash join
- When any join side is smaller than
autoBroadcastJoinThreshold
- When any join side is smaller than
- Convert Shuffle sort merge join to Shuffle hash join
- Partitions are smaller than
maxShuffledHashJoinLocalMapThreshold
- Partitions are smaller than
Note: AQE will ignore the preferSortMergeJoin setting, and go ahead with shuffle hash join when:
advisoryPartitionSizeInBytesis less thanmaxShuffledHashJoinLocalMapThreshold- All partitions are smaller than
advisoryPartitionSizeInBytes
HANDLE SKEWED JOINS
AQE detects oversized shuffle partitions, splits them into smaller pieces, and replicates the matching data from the other side so the join work can run in parallel.
It doesn't use salting. It simply breaks down dataframes using split points directly on the dataframes.
Detects skew using variables in scope spark.sql.adaptive.skewJoin
A partition considered to be skewed when:
partition_size > median_partition_size × skewedPartitionFactor
AND
partition_size > skewedPartitionThresholdInBytes
Why is AQE better than static optimization?
AQE does runtime level-optimization. So it can deal with performance issues DURING the execution itself. So it handles problems as they occur, and we don't have to know them beforehand.
- Handling stale or missing statistics
- Static optimization relies on cost based optimization, that needs up to date table statistics (row counts, histograms etc)
- If stats are outdates, the optimization chosen won't be optimal
- AQE will wait for the first stage of query to finish, and then look at the actual size of data written to shuffle files. Then it will re-plan next stage using 100% accurate runtime data
- Dynamic join selection
- Static - A table might be 10GB on disk (too big to broadcast), but after you apply a strict
WHEREfilter, it shrinks to 2MB. A static optimizer often won't realize this and will stick to a heavy, shuffle-intensive join. - AQE - AQE will see that post-filter table that came into this stage is tiny, and will optmize the join to a Broadcast Hash Join
- Static - A table might be 10GB on disk (too big to broadcast), but after you apply a strict
- Solving smille file overhead
- Static - Devs will have to manually tune spark.sql.shuffle.partitions. If set to 200 but result set is only 1mb, spark will launch 200 micro tasks, causing too much overhead
- AQE - it will coalesce partitions, and will detect the tiny slices of data and merge them into few appropriately sized tasks
- Skew management
- Static - will treat every partition as equal. In case of skew, the executor will OOM, or make the stage choke up waiting for the skewed partition to be processed
- AQE - will detect the skewed partition, and will automatically split it into smaller chunks
When does AQE not work?
- Before first shuffle - aqe is runtime stage optimizer. Needs the first stage to be done so that it has the statistics to begin optimization
- Non shuffle operations (narrow transformations)
- Streaming data
- In-memory data (cached dataframes). Cache truncates logical lineage, so AQE can't look at how the data was distributed/skewed
- non-equi joins
- join optimizations from AQE are built for equi joins.
- python UDFs (non-vectorized operations)
- The output of a UDF is not predictable, so AQE has no idea how to optimize for it
So it doesn't work well if data is cached, because the current state of the df is frozen. So AQE cannot optimize it.
Once data is cached, its execution plan in considered to be fixed. So AQE cannot modify it further.
AQE's effectiveness changes based on where data is stored. The shuffle data write has varying levels of AQE awareness:
- DISK_ONLY - full awareness. AQE handles everything perfectly. Can coalesce and change join type.
- MEMORYANDDISK - partial awareness. Cannot coalesce, can change join type
- Persisted delta tables - unaware during write
Doesn't work for:
- before first shuffle (as it is a runtime optimizer)
- in-memory cached data
- non equi joins
- threshold mismatches (config issues - workload didn't meet thresholds of skew or small)
- UDFs (non vectorized) are used
How to find driver oom vs executor oom
Driver OOM symptoms:
- Error messages -
java.lang.OutOfMemoryError: Java heap spaceorGC overhead limit exceeded - collect() shows failure
- broadcasting causes failure (crashes the driver)
- sparkui disappears/crashes (driver is responsible of it)
Executor OOM:
- Error messages -
ExecutorLostFailure,Exit status 137(means os killed process),Container killed by YARN for exceeding memory limits - Skew
- Spark job continues running - gets re-run on another executor and fails repeatedly
- Memory spill - seen in sparkui statistics
How to do optimization in databricks?
- Use photon engine
- Optimize data layout (data skipping)
- Liquid clustering
- File sizing (run optimize to merge small files into larger efficient files)
- Leverage predictive I/O
- Use delta lake. Predictive I/O will handle indexing and caching of data at storage levels, increasing access speed
- Use serverless and auto-scaling
- Avoids fixed rigid cluster sizes
- Serverless SQL warehouses for BI and SQL tasks. It will scale automatically, and shut down during inactivity
- Auto scaling - set a range (eg - 2 to 5)
- Select compute well
- Memory optimized - use for pipelines heavy in shuffles, joins and caching
- Compute optimized - for ML tasks, complex UDFs
- Storage optmized - use for very large scale delta lake oeprations, because they have fast local NVME SSDs for caching (spill to disk)
How to detect data skews, and how to handle them
To detect skew
- Check spark ui's summary metrics
- Duration - look at max vs median. If max is vastly larger than median, there is skew
- Shuffle read size/records - if 75th percentile is 10mb, but max is 100mb, there is skew
- Event timeline - healthy execution has dense block of short bars. Skew will show a few very long bars.
- Disk spills - the large partitions will spill to disk. In tasks, look at "Peak execution memory" and "disk spill"
Solutions
- Enable AQE
- Manually handle the skew - salting (when AQE isn't available, or isn't working well)
- Repartition df to get more even dataframes
Spark code
Implement SCD2 using merge
- If a customer is new, insert a new record.
- If an existing customer's attributes change, expire the old record.
- Insert the updated customer as a new current record.
- If nothing changes, do nothing.
from delta.tables import DeltaTable
from pyspark.sql.functions import current_timestamp, lit
target = DeltaTable.forName(spark, "gold.dim_customer")
source = source_df.withColumn(
"effective_start_date", current_timestamp()
).withColumn(
"effective_end_date", lit(None).cast("timestamp")
).withColumn(
"is_current", lit(True)
)
# Step 1: Expire existing records when attributes change
target.alias("t").merge(
source.alias("s"),
"t.customer_id = s.customer_id AND t.is_current = true"
).whenMatchedUpdate(
condition="t.customer_name <> s.customer_name OR t.city <> s.city",
set={
"is_current": "false",
"effective_end_date": "s.effective_start_date"
}
).execute()
# Step 2: Insert new records
target.alias("t").merge(
source.alias("s"),
"t.customer_id = s.customer_id AND t.is_current = true"
).whenNotMatchedInsert(
values={
"customer_id": "s.customer_id",
"customer_name": "s.customer_name",
"city": "s.city",
"effective_start_date": "s.effective_start_date",
"effective_end_date": "s.effective_end_date",
"is_current": "s.is_current"
}
).execute()
Read json with schema, flatten, explode, write to delta
{
"customer_id": 101,
"name": "John",
"address": {
"city": "Pune",
"country": "India"
},
"orders": [
{"order_id": 1, "amount": 500},
{"order_id": 2, "amount": 1000}
]
}
from pyspark.sql.types import *
from pyspark.sql.functions import col, explode
# 1. Define schema
schema = StructType([
StructField("customer_id", IntegerType()),
StructField("name", StringType()),
StructField("address", StructType([
StructField("city", StringType()),
StructField("country", StringType())
])),
StructField("orders", ArrayType(
StructType([
StructField("order_id", IntegerType()),
StructField("amount", DoubleType())
])
))
])
# 2. Read JSON
df = (
spark.read
.schema(schema)
.json("/data/customers/")
)
# 3. Flatten nested structures and explode array
result_df = df.select(
col("customer_id"),
col("name"),
col("address.city").alias("city"),
col("address.country").alias("country"),
explode(col("orders")).alias("order")
).select(
"customer_id",
"name",
"city",
"country",
col("order.order_id").alias("order_id"),
col("order.amount").alias("amount")
)
# 4. Write to Delta table
(
result_df.write
.format("delta")
.mode("overwrite")
.saveAsTable("gold.customer_orders")
)
How will you deduplicate rows?
# all cols
fully_unique_rows_df = df.distinct()
# specific cols
unique_names_df = df.dropDuplicates(subset=["name", "surname"])
How will you handle nulls?
. Check for nulls
df.filter(col("age").isNull())df.filter(col("age").isNotNull())
2. Replace nulls
df.fillna({"age": 0, "name": "Unknown"})
3. Drop null records
df.dropna(subset=["customer_id"])
4. Use the first non-null value
df.withColumn( "phone", coalesce(col("mobile"), col("home_phone")))
5. Conditional handling
df.withColumn( "status", when(col("status").isNull(), "UNKNOWN") .otherwise(col("status")))
6. Null-safe joins
df1.join(df2, df1.id.eqNullSafe(df2.id))
Data engineering - general
How'll you do incremental load?
I implement incremental loading by processing only new or modified records instead of reprocessing the entire dataset.
My approach:
- Identify changes: Use a watermark column such as updated_at, CDC, or Delta Change Data Feed.
- Store the watermark: Maintain the last successful processing timestamp in a control table.
- Extract incrementally: Read records where updated_at is greater than the previous watermark.
- Process changes: Apply transformations, deduplication, and data quality checks.
- Upsert: Use Delta Lake MERGE to insert new records and update existing ones.
- Update watermark: Advance it only after successful processing.
Then use Delta MERGE to upsert the records.
Production considerations: Handle late-arriving data using a lookback window, make processing idempotent, and update watermarks only after successful commits.
last_watermark = get_watermark("customers")
incremental_df = (
spark.read.format("jdbc")
.option("query", f"""
SELECT * FROM customers
WHERE updated_at > '{last_watermark}'
""")
.load()
)
How to debug long running spark jobs?
I debug long-running Spark jobs primarily using Spark UI and execution metrics.
I first identify the slowest stage, investigate task-level metrics, determine the bottleneck, and then optimize the underlying operation rather than blindly increasing cluster resources.
My approach:
- Spark UI – Jobs & Stages: Identify which stage is taking the most time and whether tasks are stuck.
- Task Analysis: Compare task execution times, input sizes, and shuffle read/write to identify data skew.
- Shuffle & Spill: Check whether excessive shuffling or memory spills are causing performance issues.
- Executor Metrics: Monitor CPU utilization, memory usage, GC time, and executor failures.
- Query Plan: Use explain("formatted") to inspect the physical execution plan.
- Data Skew: Look for a few tasks taking significantly longer than others.
- Optimization: Apply broadcast joins, repartitioning, AQE, predicate pushdown, and caching where appropriate.
Explain SCD 1 2 3 4 6
SCD (Slowly Changing Dimensions) techniques are used in data warehousing to manage changes in dimension attributes over time.
| Type | Description | Historical data |
|---|---|---|
| SCD 1 | Overwrite existing record with new values. | Not maintained |
| SCD 2 | Insert a new row for every change, maintaining effective dates and current flag. | Full history |
| SCD 3 | Maintain current and previous values in separate columns. | Limited history |
| SCD 4 | Keep current data in one table and historical records in a separate history table. | Full history |
| SCD 6 | Hybrid of SCD 1, 2, and 3. Maintains full history plus current and previous values. | Full history |
Example: Customer changes city from Pune to Mumbai
SCD 1 – Overwrite
| Customer | City |
|---|---|
| 101 | Mumbai |
SCD 2 – New row
| Customer | City | Start Date | End Date | Current |
|---|---|---|---|---|
| 101 | Pune | Jan 2024 | Mar 2025 | No |
| 101 | Mumbai | Mar 2025 | NULL | Yes |
SCD 3 – Previous value column
| Customer | Current City | Previous City |
|---|---|---|
| 101 | Mumbai | Pune |
SCD 4 – Separate history table
- Current table: Contains only Mumbai.
- History table: Contains the previous Pune record and its validity period.
SCD 6 – Hybrid
Combines:
- Type 1: Current value is overwritten in a current-value column.
- Type 2: New historical records are inserted.
- Type 3: Previous value is maintained in a separate column.
When would I use each?
- SCD 1: When historical changes are irrelevant.
- SCD 2: When auditability and historical reporting are required.
- SCD 3: When only the previous value matters.
- SCD 4: When current and historical data need separate storage.
- SCD 6: When both historical analysis and easy access to current/previous values are required.
Interview takeaway: SCD Type 2 is the most commonly used approach in enterprise data warehouses because it preserves complete historical changes and supports point-in-time reporting.
Explain file formats and their advantages - parquet, orc, avro
- Parquet is columnar - When building analytical data pipelines in Spark or Databricks.
- ORC is columnar - use when working with Hive-heavy environments and analytical workloads.
- Avro is row based. Use when exchanging records between services or processing streaming events through Kafka.
Parquet
Parquet is a columnar storage format, optimized for analytical workloads (OLAP).
Advantages:
- Reads only required columns (column pruning).
- Efficient compression and encoding.
- Supports predicate pushdown.
- Handles nested data structures.
- Excellent integration with Spark, Databricks, and Hive.
Use case: Data warehouses, analytical queries, and large-scale ETL pipelines.
ORC (Optimized Row Columnar)
ORC is also a columnar storage format, designed primarily for efficient analytical processing in the Hadoop ecosystem.
Advantages:
- High compression efficiency.
- Built-in indexes and statistics.
- Supports predicate pushdown and column pruning.
- Efficient for large analytical scans.
- Strong integration with Hive.
Use case: Hive-based data warehouses and large-scale analytical workloads.
Avro
Avro is a row-based storage format, designed for serialization and data exchange.
Advantages:
- Stores complete records together.
- Supports schema evolution.
- Supports schema resolution between writer and reader schemas.
- Efficient for streaming and message-based systems.
- Commonly used with Kafka.
Use case: Kafka messaging, event streaming, and data exchange between distributed systems.
Databricks - data quality
How will you ensure data quality in databricks?
I ensure data quality in Databricks through multiple layers of validation across the data pipeline, following a Bronze, Silver, and Gold architecture.
- Schema Validation: Define explicit schemas and enforce schema evolution rules using Delta Lake.
- Data Completeness: Check for null values, missing records, and mandatory columns.
- Uniqueness: Identify duplicate records using business keys.
- Referential Integrity: Validate foreign keys against dimension or master tables.
- Business Rules: Implement domain-specific validations using PySpark or SQL.
- Delta Live Tables Expectations: Define constraints to retain, drop, or fail on invalid records.
- Data Reconciliation: Compare source and target record counts and aggregate values.
- Monitoring: Track quality metrics, failed records, and anomalies using Databricks Workflows and alerts.
from pyspark.sql.functions import col
valid_df = df.filter(
col("customer_id").isNotNull() &
col("amount").isNotNull() &
(col("amount") >= 0)
)
invalid_df = df.subtract(valid_df)
Bronze layer – Validate ingestion
At this stage, I focus on ensuring that the data has been ingested correctly.
- Schema validation and schema evolution.
- Mandatory field checks.
- Malformed or corrupt record detection.
- Source-to-Bronze record count reconciliation.
- Tracking ingestion timestamps and source metadata.
Silver layer – Enforce data quality rules
This is where I implement most of my data quality checks.
I validate different dimensions of data quality:
| Dimension | Example |
|---|---|
| Completeness | Customer ID should not be NULL |
| Uniqueness | Transaction ID should be unique |
| Validity | Transaction amount must be positive |
| Consistency | Start date must be before end date |
| Referential integrity | Every transaction must reference an existing customer |
| Accuracy | Reconcile totals against the source system |
| Timeliness | Data should arrive within the expected SLA |
Implemented using:
- Delta Lake
NOT NULLandCHECKconstraints. - Lakeflow expectations for pipeline-level validation.
- PySpark for complex business rules and cross-table validations.
Gold layer – Validate business-level correctness
At this stage, I focus on ensuring that the data is correct from a business perspective.
For example:
- Reconcile aggregated transaction amounts against Silver.
- Validate business KPIs.
- Check consistency between fact and dimension tables.
- Ensure expected reporting periods are complete.
- Validate that transformations haven't introduced unexpected changes.
How would you monitor data quality in production?
I would establish a centralized data quality monitoring mechanism.
For every validation rule, I would capture:
- Pipeline and table name.
- Validation rule.
- Number of records checked.
- Number of records passed and failed.
- Failure percentage.
- Execution timestamp.
- Severity and validation status.
I would store these metrics in a Delta table and expose them through Databricks SQL dashboards.
| Requirement | Databricks solution |
|---|---|
| Schema enforcement | Delta Lake |
| Table-level constraints | Delta constraints |
| Pipeline validation | Lakeflow expectations |
| Complex business rules | PySpark |
| Invalid record handling | Quarantine Delta tables |
| Data profiling | Unity Catalog Data Quality Monitoring |
| Freshness/completeness anomalies | Unity Catalog monitoring |
| Lineage and traceability | Unity Catalog |
| Reporting and alerting | Databricks SQL dashboards and alerts |
I would also consider DQX or Great Expectations if the organization needs a reusable data quality framework across multiple pipelines.
How would you implement referential integrity checks efficiently on large Delta tables?
I would implement referential integrity checks using anti-joins, but I would pay particular attention to the volume of data being scanned, join strategy, and whether the validation is incremental or full-table.
For optimization, validate only incremental records. If 100k records were inserted today, will check up those records only.
How would you implement a reusable data quality framework across 100 Databricks tables?
I would build a metadata-driven framework with a registry of reusable validators, centralized rule configuration, standardized validation results, and Databricks Workflows for orchestration.
This would allow us to manage data quality across hundreds of tables without duplicating validation logic in individual pipelines.
I'll define a metadata driven rule configuration
I would maintain a configuration table containing the rules for each dataset.
This allows us to add or modify validation rules without changing the execution engine.
Eg - main.metadata.data_quality_rules
| table_name | rule_name | rule_type | column_name | severity |
|---|---|---|---|---|
| customers | customeridnot_null | NOT_NULL | customer_id | CRITICAL |
| customers | emailnotnull | NOT_NULL | HIGH | |
| customers | valid_age | RANGE | age | MEDIUM |
| transactions | amount_positive | EXPRESSION | amount | CRITICAL |
| transactions | transaction_unique | UNIQUE | transaction_id | CRITICAL |
I would implement individual validators and register them with a common execution engine.
from pyspark.sql import functions as F
class DataQualityValidator:
@staticmethod
def not_null(df, column):
return F.col(column).isNotNull()
@staticmethod
def positive(df, column):
return F.col(column) > 0
@staticmethod
def valid_range(df, column, minimum, maximum):
return F.col(column).between(
minimum, maximum
)
VALIDATORS = {
"NOT_NULL": DataQualityValidator.not_null,
"POSITIVE": DataQualityValidator.positive,
}
def execute_rule(df, rule):
validator = VALIDATORS[rule["rule_type"]]
condition = validator(
df,
rule["column_name"]
)
return df.filter(~condition)
I would standardize the output of every validator.
main.monitoring.data_quality_results
Eg:
| Field | Description |
|---|---|
| run_id | Unique execution identifier |
| table_name | Validated table |
| rule_id | Validation rule |
| total_records | Records evaluated |
| failed_records | Records violating the rule |
| passed_records | Records passing |
| failure_percentage | Percentage failed |
| executiontimems | Execution duration |
| status | PASS / FAIL |
| executed_at | Execution timestamp |
For production, I would not necessarily execute all 100 tables sequentially in one Spark driver process.
I would use Databricks Workflows to orchestrate independent table validations, with controlled concurrency and separate tasks for high-volume datasets.
I would also group rules that can be evaluated in the same Spark aggregation to avoid repeatedly scanning the same table.
Why this architecture?
It provides several advantages:
- Reusability: Common validation logic is implemented once.
- Consistency: All tables follow the same validation conventions.
- Extensibility: New rules can be added through configuration.
- Observability: All validation results are stored centrally.
- Maintainability: Business logic and validation infrastructure remain separate.
- Scalability: Different tables can be validated independently.
How would you ensure data quality checks don't significantly increase Spark job execution time?
My approach would be to treat data quality validation as part of the performance engineering of the pipeline.
I would focus on minimizing additional data scans and making validation incremental wherever possible.
Separate lightweight and expensive checks
| Check | Frequency |
|---|---|
| NOT NULL | Every batch |
| Data type / schema | Every batch |
| Basic range validation | Every batch |
| Duplicate detection | Every batch or incremental state-aware check |
| Referential integrity | Every batch against an appropriate reference snapshot |
| Statistical profiling | Periodically |
| Full historical reconciliation | Daily / weekly |
| Deep distribution drift analysis | Periodically or on anomaly |
What interviewers are really evaluating
Across these three questions, I would make sure to communicate these engineering principles:
| Area | Senior-level consideration |
|---|---|
| Referential integrity | Incremental validation, anti-joins, late-arriving dimensions |
| Reusable framework | Metadata-driven rules, extensibility, centralized metrics |
| Performance | Minimize scans, shuffles, and repeated Spark actions |
| Reliability | Idempotency, quarantine, retries, auditability |
| Operations | Monitoring, alerting, ownership, SLAs |
Databricks - cicd
Explain how to package and deploy pipelines
Use declarative automation bundles. Deployed via ci-cd
(Previously was called databricks asset bundles)
File organization looks like:
my-databricks-project/
│
├── databricks.yml # Main bundle configuration
├── pyproject.toml # Python dependencies and packaging
├── README.md
├── .gitignore
│
├── resources/ # Databricks resource definitions
│ ├── jobs/
│ │ ├── ingestion.job.yml
│ │ ├── transformation.job.yml
│ │ └── data_quality.job.yml
│ │
│ ├── pipelines/
│ │ ├── bronze.pipeline.yml
│ │ └── silver.pipeline.yml
│ │
│ └── permissions.yml # Optional shared configuration
│
├── src/ # Actual application code
│ ├── ingestion/
│ │ ├── __init__.py
│ │ └── main.py
│ │
│ ├── transformations/
│ │ ├── __init__.py
│ │ ├── customers.py
│ │ └── orders.py
│ │
│ ├── data_quality/
│ │ ├── __init__.py
│ │ ├── expectations.py
│ │ └── validators.py
│ │
│ └── common/
│ ├── __init__.py
│ ├── config.py
│ └── logging.py
│
├── tests/
│ ├── unit/
│ │ ├── test_customers.py
│ │ └── test_validators.py
│ │
│ └── integration/
│ └── test_pipeline.py
│
└── notebooks/ # Optional development notebooks
└── exploration.ipynb
Sql theory
What are the key types
- Primary key - 1 column. Only 1 primary key per table.
- Super key
- any combinations of columns to pinpoint a row
- may contain unnecessary columns
- Candidate key - minimal superkey
- Composite key - key of more than 1 columns

What is SQL's clause execution order
FROM,JOIN,ON- Take in all source tables. Join them to create a single large table.WHERE- Filter the large combined table to remove unnecessary rows.GROUP BYHAVING- Window functions,
SELECT,distinct()- Select required columns from the table. Apply window functions if required. ORDER BYLIMIT- Return the data as result.
Explain the various null interactions with joins, sort, group by, aggregates
- joins - will ignore null values
- sort - will put null at beginning or end depending on dbms
- group by - all nulls become a single category
- aggregates - will ignore null values (exception -
count(*)will count null valued rows too)
Explain normal vs materialized views
- Normal views are used for abstraction and reusable logic
- Materialized views are used when expensive aggregations are queried frequently and precomputation improves performance
Normal View (Virtual View)
- Stores only the SQL query definition, not the actual result data.
- Every time you query the view, the underlying query is executed against the source tables.
- Always reflects the latest underlying data.
- Doesn't require additional storage for results.
Materialized View
- Stores the result of the query physically.
- Querying it is generally faster because results are precomputed.
- Needs to be refreshed when underlying data changes (refresh may be automatic depending on the platform).
- Requires additional storage.
Data Modelling
How to approach?
List:
- Entities (dims)
- Relationships (facts)
- Measurements (facts)
- Metrics to track
Then model using snowflake to star
Python
Explain lists vs sets vs tuple
- List: Ordered and mutable. Used when you need an ordered, modifiable collection.
- Tuple: Ordered and immutable. Used for fixed collections that should not be modified.
- Set: Unique elements with average O(1) membership lookup. Used when you need unique elements and fast membership checks.
Explain deep vs shallow copy
In Python, shallow copy and deep copy differ in how they handle nested objects.
Shallow vs deep copy matters primarily for mutable objects containing other objects, such as lists, dictionaries, and sets containing mutable elements.
Shallow Copy
- Creates a new outer object.
- Nested objects are still shared between the original and copied object.
- Changes to nested objects affect both copies.
Deep Copy
- Creates a new outer object and recursively copies nested objects.
- Changes to nested objects don't affect the original.
Explain decorators in python
A decorator in Python is a function that modifies or extends the behavior of another function without changing its original implementation.
The decorator wraps the original function and adds additional behavior.
Common use cases:
- Logging and monitoring.
- Authentication and authorization.
- Execution time measurement.
- Caching using @lru_cache.
- Retry mechanisms.
Decorators use Python's first-class functions and closures.
def my_decorator(func):
def wrapper():
print("Before function execution")
func()
print("After function execution")
return wrapper
@my_decorator
def hello():
print("Hello!")
hello()
# Before function execution
# Hello!
# After function execution
Decorator is a syntatic sugar for:
hello = my_decorator(hello)
Explain iterators in python
Iterators enable lazy, sequential data processing without loading the entire collection into memory.
An iterator implements two methods:
- iter() – Returns the iterator object itself.
- next() – Returns the next element. Raises StopIteration when exhausted.
Iterator vs Iterable:
- Iterable: An object that can return an iterator, e.g., list, tuple, string.
- Iterator: An object that produces elements one at a time.
Why are iterators useful?
- Memory efficient.
- Support lazy evaluation.
- Useful for processing large datasets and streams.
Explain return vs yeild
In Python, return and yield both produce values from a function, but they behave differently.
Return
- Terminates function execution.
- Returns a single result to the caller.
- The function cannot resume from where it stopped.
def get_numbers():
return [1, 2, 3]
result = get_numbers()
Yield
- Turns a function into a generator.
- Produces values one at a time.
- Suspends execution and resumes from where it stopped when the next value is requested.
- Memory efficient for large datasets.
def get_numbers():
yield 1
yield 2
yield 3
for num in get_numbers():
print(num)