Skip to the page
Tecyfy

PySpark interview question · easy

What are some common actions in Spark, and how have you used them?

The short answerActions are the operations that make Spark execute the plan and return a result to the driver or write it out.

The full answer

Actions are the operations that make Spark execute the plan and return a result to the driver or write it out. The ones I use most are count(), show(), take() and first() for inspection, collect() and toPandas() for small results, and writes such as saveAsTable() for real output, plus foreachBatch in streaming.

ActionReturnsTypical useWatch out for
count()Number of rowsData checks, row counts before and after a stepReads all data; can be slow
show(n)Prints rowsQuick inspectionOnly a sample; truncates long values unless truncate=False
take(n), head(n), limit(n).collect()First rows as a listSpot checks, testsOrder isn't guaranteed without orderBy
first()One rowReading a computed scalar, such as a maximum date
collect()All rows to the driverSmall results: lookup lists, parametersDriver out-of-memory on large data
toPandas()pandas DataFrameSmall results for plotting or local librariesSame as collect(); enable Arrow for speed
isEmpty()BooleanSkipping work when there's no inputCheaper than count() == 0
tail(n)Last rowsInspecting the end of ordered dataBrings data to the driver
write...save(), saveAsTable(), insertInto()NothingPipeline outputChoose the mode carefully (overwrite vs append)
foreach(), foreachPartition()NothingSending rows to an external systemRuns on executors; open connections per partition, not per row
RDD reduce(), aggregate()A valueCustom aggregationsPrefer DataFrame aggregations

How I've used them

from pyspark.sql import functions as F

# Guard: skip the run when there's nothing new
new_rows = spark.read.table("bronze.events").filter(F.col("ingest_date") == run_date)
if new_rows.isEmpty():
    print("No new data")
else:
    # Data quality check before publishing
    bad = new_rows.filter(F.col("event_id").isNull()).count()
    if bad > 0:
        raise ValueError(f"{bad} events without an id")

    # Read a scalar for the next step
    max_ts = new_rows.agg(F.max("event_ts")).first()[0]

    # Publish
    new_rows.write.mode("append").saveAsTable("silver.events")

Lessons

  • Each action runs the plan from the start; when several actions reuse a DataFrame, cache it or write an intermediate table.
  • Avoid actions inside loops over rows; express the logic as one transformation.
  • In streaming, foreachBatch lets you apply batch actions, such as a Delta MERGE, to each micro-batch.
  • Keep collect() for genuinely small results; for everything else, write to storage.
  • In notebooks, every display() or show() is an action too, so a cell that looks cheap can re-read a large table; check the Jobs tab when a notebook feels slow.

Last updated 16 October 2026

Sources

Where each fact comes from

  1. 1RDD programming guide
  2. 2PySpark API reference