RDD vs DataFrame vs Dataset

Apache Spark · RDDs

Theory

Spark has three data APIs. An RDD is a distributed collection of objects with no schema; Spark treats your functions as black boxes, so it cannot optimize them. A DataFrame is a distributed table with named, typed columns (a schema); because Spark understands the columns and expressions, the Catalyst optimizer can reorder filters, prune columns and pick join strategies, and Tungsten stores rows in a compact binary format. A Dataset is a typed version of a DataFrame for Scala and Java, where each row is a class such as Order and the compiler checks field names and types.

In Scala, DataFrame is simply Dataset[Row]. Python and R have no compile-time types, so they only have DataFrames (and RDDs). For example, summing amount per region with a DataFrame groupBy runs mostly inside the JVM with generated code, while the same logic with RDD lambdas sends every row to Python worker processes and back, which is usually much slower.

Why we use it

Choosing the right API decides both speed and code clarity. DataFrames give optimization for free; RDDs give full control at the cost of performance. This comparison is one of the most common Spark interview questions.

When to use it

Use DataFrames (or Spark SQL) by default in PySpark. Use RDDs for unstructured data or low-level partition control. In Scala or Java, use Datasets when you want compile-time type safety on domain objects and can accept some overhead from lambdas.

How it works

  1. Choose a Spark API
  2. Is the data structured (rows and columns)? Yes: Use DataFrames or Spark SQL. No: Consider RDDs for raw objects or text.
  3. Using Scala/Java and need compile-time types? Yes: Use Datasets of case classes. No: Stay with DataFrames.
  4. Convert between APIs only at the edges

Syntax

rdd = df.rdd                          # DataFrame -> RDD[Row]
df = rdd.toDF(["col1", "col2"])      # RDD -> DataFrame
df = spark.createDataFrame(rdd, schema)
// Scala: val ds = df.as[Order]       // Dataset[Order]

Example

from pyspark.sql import SparkSession, functions as F

spark = (SparkSession.builder.master("local[1]")
         .config("spark.ui.enabled", "false")
         .getOrCreate())

orders = spark.createDataFrame([
    (101, 1, "North", "Laptop", 1, 55000.0, "2026-01-05"),
    (102, 2, "West",  "Phone",  2, 30000.0, "2026-01-06"),
    (103, 1, "North", "Mouse",  3,  1500.0, "2026-01-06"),
    (104, 3, "South", "Laptop", 1, 52000.0, "2026-01-07"),
    (105, 4, "West",  "Tablet", 1, 25000.0, "2026-01-08"),
    (106, 2, "East",  "Phone",  1, 15000.0, "2026-01-08"),
    (107, 5, "North", "Tablet", 2, 48000.0, "2026-01-09"),
    (108, 3, "South", "Mouse",  4,  2000.0, "2026-01-10"),
], "order_id INT, customer_id INT, region STRING, product STRING, "
   "qty INT, amount DOUBLE, order_date STRING"
).withColumn("order_date", F.to_date("order_date"))

from operator import add

# RDD version: Python lambdas, no schema, no optimizer
rdd_totals = (orders.rdd.map(lambda r: (r.region, r.amount)).reduceByKey(add))
print(sorted(rdd_totals.collect()))

# DataFrame version: named columns, optimized by Catalyst
df_totals = orders.groupBy("region").agg(F.sum("amount").alias("total"))
df_totals.orderBy("region").show()

# Converting between them
back_to_df = rdd_totals.toDF(["region", "total"])
back_to_df.printSchema()

# Output:
# [('East', 15000.0), ('North', 104500.0), ('South', 54000.0), ('West', 55000.0)]
# +------+--------+
# |region|   total|
# +------+--------+
# |  East| 15000.0|
# | North|104500.0|
# | South| 54000.0|
# |  West| 55000.0|
# +------+--------+
#
# root
#  |-- region: string (nullable = true)
#  |-- total: double (nullable = true)

Key points

Apache Spark topics

Spark Fundamentals

Spark Architecture

RDDs

DataFrames

Aggregations & Joins

Spark SQL

Window Functions

Cleaning & Complex Types

UDFs

Performance Tuning

Structured Streaming

MLlib & Ecosystem

Interview Prep

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Master Apache Spark

PySpark and Spark SQL from the ground up: DataFrames, joins, window functions, partitions and performance tuning, Structured Streaming and more. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice PySpark Write real PySpark — DataFrames, joins, window functions and Spark SQL — in a live editor with hidden tests and instant checking. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Spark  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

{{ sec.h }}

{{ sec.body }}

{{ sec.body }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
On screen — where to click

{{ rich.ui.title }}

{{ u.text }}
  1. {{ st.n }}{{ st.text }}
{{ rich.ui.title }}
{{ u.text }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
Want to run this yourself? Try the same API on Practice PySpark Online right in your browser, or run it locally after pip install pyspark (needs Java 17+), or paste it into a Databricks Free Edition notebook.
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic