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.
| Action | Returns | Typical use | Watch out for |
|---|---|---|---|
count() | Number of rows | Data checks, row counts before and after a step | Reads all data; can be slow |
show(n) | Prints rows | Quick inspection | Only a sample; truncates long values unless truncate=False |
take(n), head(n), limit(n).collect() | First rows as a list | Spot checks, tests | Order isn't guaranteed without orderBy |
first() | One row | Reading a computed scalar, such as a maximum date | |
collect() | All rows to the driver | Small results: lookup lists, parameters | Driver out-of-memory on large data |
toPandas() | pandas DataFrame | Small results for plotting or local libraries | Same as collect(); enable Arrow for speed |
isEmpty() | Boolean | Skipping work when there's no input | Cheaper than count() == 0 |
tail(n) | Last rows | Inspecting the end of ordered data | Brings data to the driver |
write...save(), saveAsTable(), insertInto() | Nothing | Pipeline output | Choose the mode carefully (overwrite vs append) |
foreach(), foreachPartition() | Nothing | Sending rows to an external system | Runs on executors; open connections per partition, not per row |
RDD reduce(), aggregate() | A value | Custom aggregations | Prefer 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,
foreachBatchlets you apply batch actions, such as a DeltaMERGE, to each micro-batch. - Keep
collect()for genuinely small results; for everything else, write to storage. - In notebooks, every
display()orshow()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