What you will be able to do
- Read and write Parquet, CSV, JSON, ORC and Delta data with the shared format/option/load/save pattern of DataFrameReader and DataFrameWriter
- Pick the right save mode, and predict what a write with no mode does when the target already holds data
- Read a database table over JDBC, push a query down to the source, and parallelise the read with partitionColumn, lowerBound, upperBound and numPartitions
- Write partitioned output to a path, read it back with the partition column recovered, and choose static or dynamic partition overwrite
Key concept
DataFrameReader / DataFrameWriter format interface — Every Spark source, from a Parquet directory to a PostgreSQL table, is read through spark.read and written through df.write using the same chain: name a format, add options, then load or save. Shortcuts such as parquet() or jdbc() are the same chain with the format already filled in.
1.One interface for every source: format, option, load, save
Spark reads data through a single entry point, spark.read, which returns a DataFrameReader. You name the source with format(...), tune it with option(key, value) or options(...), optionally fix the columns with schema(...), and finish with load(path). Writes mirror this on df.write, a DataFrameWriter: format, option, mode, optionally partitionBy, then save(path). Because the pattern does not change, moving a job from CSV to Parquet, or from files to a database, usually means changing the format string and its options and nothing else.
df = spark.read \
.format("csv") \
.option("header", "true") \
.option("inferSchema", "true") \
.option("delimiter", ",") \
.schema("name STRING, age INT") \
.load("path/to/file.csv")Each built-in format also has a shortcut method that fills in format for you: spark.read.json(path), .csv(path), .parquet(path), .orc(path), .text(path) and .jdbc(url, table, ...) on the reader, and the matching methods on the writer. spark.read.format("json").load(p) and spark.read.json(p) do the same thing. On the write side, the chain below writes Snappy-compressed Parquet split into year and month directories, replacing anything already at the path.
df.write \
.format("parquet") \
.mode("overwrite") \
.option("compression", "snappy") \
.partitionBy("year", "month") \
.save("path/to/output")If you leave out format, the default depends on the platform. Plain Apache Spark falls back to Parquet. Databricks falls back to Delta Lake, so the same df.write.save(path) writes Parquet files on one platform and a Delta table on the other. Most file formats also take a compression option on write. The formats differ in what their options control:
| Format string | Kind | Typical options |
|---|---|---|
| parquet | Columnar, Spark's default | compression |
| orc | Columnar with lightweight indexes | compression, mergeSchema |
| json | Text records, flexible schema | multiline records, schema inference |
| csv | Delimited text | header, delimiter, malformed records |
| text | One line (or one file) per row | lineSep, wholetext |
| delta | ACID table format, Databricks default | replaceWhere, partitionOverwriteMode |
Checkpoint 1 of 10· Fill the gap
This write should produce Snappy-compressed Parquet laid out in year and month directories under the output path. Which DataFrameWriter method fills the blank?
df.write \
.format("parquet") \
.mode("overwrite") \
.option("compression", "snappy") \
. ? ("year", "month") \
.save("path/to/output")partitionBy is the DataFrameWriter step that splits the output into one directory per column value, here year and then month. repartition only changes the DataFrame's in-memory partitions and does not create directories. bucketBy and sortBy deal with buckets inside a table.
Source: docs.databricks.com2.Save modes: what a write does when data already exists
mode(...) controls only one thing: what happens when the target path or table already holds data. On an empty target, all four modes write the same output. They differ the moment there is something there, and the default is the safe one. With no mode set, a rerun fails and nothing gets clobbered. That is why a scheduled job that writes to a fixed path works the first night and fails the second, unless someone sets a mode on purpose.
| Mode string | Behaviour when data exists |
|---|---|
| error / errorifexists (default) | Throws an exception; nothing is written |
| append | Adds this DataFrame's rows to the existing data |
| overwrite | Replaces the existing data |
| ignore | Silently skips the write; existing data is untouched |
# Overwrite existing data
df.write.mode("overwrite").parquet("path/to/output.parquet")
# Append to existing data
df.write.mode("append").parquet("path/to/output.parquet")
# Ignore if data exists
df.write.mode("ignore").json("path/to/output.json")
# Error if data exists (default)
df.write.mode("error").csv("path/to/output.csv")Choose ignore when you only want the output created once, for example seeding a reference dataset. It does not warn you that it skipped anything. Choose append for incremental loads where each run adds new rows, and remember that rerunning the same batch will duplicate them. There is no merge mode and no key-based upsert among the save modes. overwrite is the mode that interacts with partitioning, covered in the last section.
Checkpoint 2 of 10· Check yourself
A scheduled job seeds a reference lookup dataset at a fixed path. The first run should create it. Later runs must not fail, and must leave the existing files exactly as they are. Which write setting fits?
ignore writes on an empty target and quietly skips the write when data already exists, so the files stay as they are and the job does not fail. append has no key-based de-duplication, so it would duplicate rows. overwrite replaces the data. The default mode, error, throws an exception on the second run.
“ignore: Silently ignore this operation if data already exists.”Source: docs.databricks.com
Checkpoint 3 of 10· Exam question
A developer writes df.write.format("parquet").save("/tmp/output") and reruns the exact same job a second time against a path that already contains data from the first run. No .mode(...) was specified. What happens on the second run?
Correct answer: A — Spark raises an AnalysisException, because the default save mode is errorifexists, which refuses to write whenever the target path already contains data.
- A. Correct — when no mode is given,
DataFrameWriterdefaults toerrorifexists(also callederror), so writing to a non-empty target path throws an exception instead of silently changing the data. - B. Incorrect —
ignoreis an explicit mode a developer must set; it is not the implicit default, so an unspecified mode does not behave this way. - C. Incorrect —
appendmust be chosen explicitly with.mode("append"); Spark never appends automatically just because no mode was passed. - D. Incorrect —
overwritealso requires an explicit.mode("overwrite")call; Spark does not overwrite existing output by default for any file-based format. - E. Incorrect — there is no default
mergesave mode in Spark'sDataFrameWriter; merge-style upserts require a separate API such as Delta Lake'sMERGE INTO.
3.Reading a database table over JDBC
JDBC uses the same reader chain: spark.read.format("jdbc"), connection options, then load() with no path. The connection options are url (a string of the form jdbc:subprotocol:subname, such as jdbc:postgresql://dbhost:5432/hr), driver (the driver class), and user and password. These options say how to connect but not what to read. You must also give either dbtable, which names a table, or query, which is a SQL statement. Leave both out and the load fails, however complete the connection details are. You cannot set both.
| Option | Required? | What it does |
|---|---|---|
| dbtable | Yes, or query | Names the table to read; cannot be combined with query |
| query | Yes, or dbtable | A SQL statement run on the remote database; cannot be combined with dbtable |
| fetchsize | No | Rows fetched per round trip; larger values trade memory for speed |
| partitionColumn | No | Column with evenly spread values used to split the read |
| lowerBound / upperBound | No | Minimum and maximum of partitionColumn used to compute the splits |
| numPartitions | No | Number of parallel connections used to fetch the data |
The query option is how you push work down to the database. The whole SQL string runs on the external system, and Spark receives only the result. A WHERE active = 1 filter or a join inside query therefore never ships the discarded rows over the network. Spark does not rewrite or optimise that string. JDBC sources also give the Spark optimizer no statistics about the remote table, so a selective filter is worth writing into query yourself rather than hoping Spark pushes it down.
df = (spark.read
.format("jdbc")
.option("databricks.connection", "<connection-name>")
.option("query", "SELECT * FROM external_table")
.load())Spark reads the remote table's schema itself and maps its types to Spark SQL types, so a JDBC read needs no schema(...) call. fetchsize affects speed and driver memory only. It controls how many rows come back per round trip and has nothing to do with whether the read can find its data. Keep the credentials in their own options rather than in the URL, because errors and logs can expose a URL.
Checkpoint 4 of 10· Check yourself
Only about 2% of the rows in a remote orders table have status = 'OPEN', and the job needs only those rows. Which JDBC read keeps the unwanted rows from being sent over the network to Spark?
The SQL in the query option runs entirely on the external database, so Spark only receives the rows that pass the WHERE clause. JDBC sources don't give the optimizer any statistics. fetchsize only changes how many rows come back per round trip. dbtable and query can't be set together.
“Using the query option ensures that filter and join logic executes on the source database before data reaches Spark.”Source: docs.databricks.com
Checkpoint 5 of 10· Exam question
A data engineer is reading a table from a PostgreSQL database using Spark's JDBC data source:
df = spark.read.format("jdbc") \
.option("url", "jdbc:postgresql://dbhost:5432/hr") \
.option("driver", "org.postgresql.Driver") \
.option("user", "svc_reader") \
.option("password", "s3cr3t") \
.load()
Running this code raises an AnalysisException because a required option is missing. Which option must be added to identify what to read?
Correct answer: A — .option("dbtable", "employees"), which names the source table (or a parenthesized subquery) that Spark reads through the JDBC connection.
- A. Correct —
dbtable(orquery) is the required option that tells the JDBC reader which table or subquery to pull rows from; without it Spark has a connection but nothing to select. - B. Incorrect —
fetchsizeis a performance tuning knob for the JDBC driver's row batch size and does not name a source table, so it cannot fix a missing-table error. - C. Incorrect —
numPartitionscontrols read parallelism once a table is already identified; it plays no role in specifying which table to read. - D. Incorrect —
partitionColumnonly has an effect alongsidenumPartitions,lowerBound, andupperBoundfor parallel scans, and still requires a table to already be specified. - E. Incorrect —
isolationLevelgoverns transaction isolation on the JDBC connection and is unrelated to naming the table or subquery being read.
4.Parallel JDBC reads with partitionColumn and bounds
A plain JDBC read uses one connection, so one task pulls the entire table while the rest of the cluster waits. To split the read, give Spark a numeric column and its range: partitionColumn (column in the jdbc() shortcut), lowerBound, upperBound and numPartitions. Spark divides the range into numPartitions slices and opens one connection per slice. These four go together. Setting numPartitions alone does not give Spark a column to split on. A split column also requires dbtable, not query.
df = spark.read.jdbc(
url="jdbc:postgresql://localhost:5432/mydb",
table="users",
column="id",
lowerBound=1,
upperBound=1000,
numPartitions=10,
properties={"user": "myuser", "password": "mypassword"}
)Pick a column whose values are spread evenly, such as a sequential id. A skewed column produces one huge slice and several empty ones. You can also split the read with predicates, a list of WHERE clauses that each define one partition. If you pass both column and predicates, column wins. Set numPartitions with the database in mind as well as the cluster: every slice is a live connection, and hundreds of them at once can bring down the source system.
Checkpoint 6 of 10· Fill the gap
You want the jdbc() shortcut to read the users table in ten parallel slices of the id range. Which keyword argument names the column that Spark splits the read on?
df = spark.read.jdbc(
url="jdbc:postgresql://localhost:5432/mydb",
table="users",
? ="id",
lowerBound=1,
upperBound=1000,
numPartitions=10,
properties={"user": "myuser", "password": "mypassword"}
)In the jdbc() shortcut, the split column is passed as column. It works together with lowerBound, upperBound and numPartitions to divide the id range into ten slices. partitionColumn is the name of the same setting when you use format("jdbc") options. predicates expects a list of WHERE clauses rather than a column name. fetchsize only sets how many rows come back per round trip.
Source: docs.databricks.com5.Writing a DataFrame to a database
Writing over JDBC uses the writer chain with the same connection options, a target table, and a save mode. The df.write.jdbc(url, table, mode, properties) shortcut does it in one call. append adds rows to the existing table and overwrite replaces its contents. The default is still error, so writing to a table that already exists fails unless you choose a mode.
df.write.jdbc(
url="jdbc:postgresql://localhost:5432/mydb",
table="users",
mode="overwrite",
properties={"user": "myuser", "password": "mypassword"}
)A JDBC write works on whole tables, never on individual rows. Spark can append rows or overwrite the table, but it cannot run an UPDATE or DELETE against the database, so an upsert has to happen in the database itself. Write-side options tune the transfer. The bundled connectors document batchsize (rows per insert batch, default 1000), numPartitions (parallel write connections), isolationLevel (the transaction isolation level, default READ_UNCOMMITTED) and truncate. With truncate, an overwrite empties the existing table instead of dropping and recreating it, so the table's definition survives the write. None of these options says what data to read or write. They only tune how the transfer runs.
Checkpoint 7 of 10· Fill the gap
A nightly job reloads the PostgreSQL users table from a DataFrame. The table already exists from the night before. Each run must replace the table's contents. It must not fail, and it must not pile up duplicate rows. Which save mode value fills the blank?
df.write.jdbc(
url="jdbc:postgresql://localhost:5432/mydb",
table="users",
mode=" ? ",
properties={"user": "myuser", "password": "mypassword"}
)overwrite replaces the contents of the existing table, so every run leaves exactly one copy of the data. append would add the rows again on each run and create duplicates. errorifexists is the default and fails because the table already exists. ignore would skip the write, so the table would keep last night's data.
Source: docs.databricks.com6.Partitioned output on a path and reading it back
DataFrameWriter.partitionBy splits output by column value. On a path-based write, that means one subdirectory per value, in the Hive style column=value. Writing with partitionBy("event_date") to /data/events produces folders like /data/events/event_date=2026-09-01/, each holding only that date's rows. The partition column's values live in the directory names, not inside the data files. A query that filters on event_date therefore only needs the matching folder. Options that control file counts or sizes, such as maxRecordsPerFile, repartition or coalesce, still leave every date mixed through the same files. bucketBy hashes rows into a fixed number of buckets, works only with saveAsTable, and creates no per-value folders.
spark.createDataFrame(
[{"age": 100, "name": "Alice"}, {"age": 120, "name": "Ruifeng Zheng"}]
).write.partitionBy("name").mode("overwrite").format("parquet").save(d)
spark.read.parquet(d).sort("age").show()
# +---+-------------+
# |age| name|
# +---+-------------+
# |100| Alice|
# |120|Ruifeng Zheng|
# +---+-------------+
# Read one partition as a DataFrame.
spark.read.parquet(f"{d}{os.path.sep}name=Alice").show()
# +---+
# |age|
# +---+
# |100|
# +---+Reading the root directory brings the partition column back. Spark finds the name=... folders and rebuilds name as a column from the directory names, so the DataFrame has the same columns as before the write. Reading one partition directory directly returns only that partition's rows, and the name column is gone, because inside name=Alice nothing records the value. To read one partition and keep the column, read the root and filter on it.
Reading a partition directory directly drops the partition column, so neither DataFrame contains event_date. Reading /data/events and filtering on event_date for both days keeps the column.
Checkpoint 8 of 10· Fill the gap
After the partitioned write below, the read has to return both rows with the name column rebuilt, as the output shows. Which argument to spark.read.parquet fills the blank?
spark.createDataFrame(
[{"age": 100, "name": "Alice"}, {"age": 120, "name": "Ruifeng Zheng"}]
).write.partitionBy("name").mode("overwrite").format("parquet").save(d)
spark.read.parquet( ? ).sort("age").show()
# +---+-------------+
# |age| name|
# +---+-------------+
# |100| Alice|
# |120|Ruifeng Zheng|
# +---+-------------+When you read the root path d, Spark finds the name=... folders and rebuilds name as a column from the directory names. When you read a single name=... partition directory, you get only that partition's rows, and the name column is missing because nothing inside the folder stores its value.
Source: docs.databricks.comCheckpoint 9 of 10· Exam question
A team stores five years of clickstream events as Parquet files. Analysts almost always filter queries by event_date, and the dataset is read far more often than it is written. Which write pattern lets a query such as WHERE event_date = '2026-09-01' skip scanning irrelevant files entirely?
Correct answer: A — df.write.format("parquet").partitionBy("event_date").save("/data/events"), which writes a separate subdirectory per date so a date filter can prune whole directories before opening any files.
- A. Correct —
partitionBycreates Hive-style directories such asevent_date=2026-09-01/, and a matching filter lets Spark prune directories at planning time instead of scanning every file. - B. Incorrect — bucketing distributes rows across a fixed number of hash buckets to speed up joins and aggregations, but it produces no per-date directory structure for a query planner to prune on.
- C. Incorrect —
repartitionchanges the number and distribution of output files in memory before writing but has no relationship to the values stored in theevent_datecolumn. - D. Incorrect —
maxRecordsPerFileonly bounds how many rows land in each output file; it does nothing to group rows by date, so pruning still cannot happen. - E. Incorrect — forcing output into one file is the opposite of what pruning needs, since every query would have to open that single file no matter which date it targets.
7.Overwriting partitioned output: static vs dynamic
With partitioned output, mode("overwrite") can do two different things, and partitionOverwriteMode picks which. In static mode, the default, the overwrite replaces all the existing data at the target. A daily job that writes one new day with overwrite will wipe out every earlier day. In dynamic mode, Spark replaces only the partitions the incoming DataFrame has rows for. Every other partition stays as it was. Dynamic mode is the right choice for reprocessing a late or corrected slice, such as rewriting yesterday's partition without touching the rest of the year.
You can turn on dynamic mode in two places. Setting the session configuration spark.sql.sources.partitionOverwriteMode to dynamic covers every overwrite in the session, including SQL INSERT OVERWRITE. Setting the writer option partitionOverwriteMode to dynamic covers a single write, and when both are set the writer option wins. The setting only matters in overwrite mode. Append never removes partitions.
SET spark.sql.sources.partitionOverwriteMode=dynamic;
INSERT OVERWRITE TABLE default.people10m SELECT * FROM morePeople;
(df.write
.mode("overwrite")
.option("partitionOverwriteMode", "dynamic")
.saveAsTable("default.people10m")
)Checkpoint 10 of 10· Check yourself
To reprocess a corrected slice, a job rewrites only yesterday's rows (event_date = 2026-10-20) into /data/events. That path is partitioned by event_date and holds a year of history. Which write replaces that day and keeps every other date as it is?
In dynamic mode, overwrite replaces only the partitions that df has rows for, so the rest of the year stays as it was. Static is the default, and both the default and an explicit static setting replace all the existing data at the target. Append never removes data, so the old rows for that day would stay next to the corrected ones.
“Dynamic partition overwrites replace all the existing data in each partition for which the write will commit new data and leaves all other partitions unchanged.”Source: docs.databricks.com
Sources
(12)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“Specifies the input data source format.”
↩︎ One interface for every source: format, option, load, save“Specifies the input data source format.”
↩︎ Key concept - 2.
“Specifies the underlying output data source.”
↩︎ One interface for every source: format, option, load, save“ignore: Silently ignore this operation if data already exists.”
↩︎ Save modes: what a write does when data already exists“Buckets the output by the given columns.”
↩︎ Partitioned output on a path and reading it back“error or errorifexists: Throw an exception if data already exists (default).”
↩︎ Exam trap 1“error or errorifexists: Throw an exception if data already exists (default).”
↩︎ Prediction - 3.https://docs.databricks.com/aws/en/query/formatsOfficial docs
“Databricks uses Delta Lake as the default protocol for reading and writing data and tables, whereas Apache Spark uses Parquet.”
↩︎ One interface for every source: format, option, load, save - 4.
“Specifies the behavior when data or table already exists.”
↩︎ Save modes: what a write does when data already exists - 5.
“The JDBC URL of the form jdbc:subprotocol:subname.”
↩︎ Reading a database table over JDBC“Partitions of the table are retrieved in parallel if either column or predicates is specified.”
↩︎ Parallel JDBC reads with partitionColumn and bounds“Avoid creating too many partitions in parallel on a large cluster, as this can crash external database systems.”
↩︎ Parallel JDBC reads with partitionColumn and bounds - 6.
“The number of rows to fetch per round trip.”
↩︎ Reading a database table over JDBC“A column with uniformly distributed values to use for parallel data fetching.”
↩︎ Parallel JDBC reads with partitionColumn and bounds“The table name to query. Cannot be used with query.”
↩︎ Exam trap 2“all four parameters (partitionColumn, lowerBound, upperBound, numPartitions) must be specified together”
↩︎ Exam trap 3 - 7.
“When using the query option, the specified SQL statement runs entirely on the external data source.”
↩︎ Reading a database table over JDBC“Using the query option ensures that filter and join logic executes on the source database before data reaches Spark.”
↩︎ Reading a database table over JDBC“Spark automatically reads the schema from the external database table and maps its types to Spark SQL types.”
↩︎ Reading a database table over JDBC“Use append to add rows to an existing table or overwrite to replace its contents.”
↩︎ Writing a DataFrame to a database - 8.
“Neither JDBC nor PySpark data sources expose statistics to the query optimizer to help select the order of operations.”
↩︎ Reading a database table over JDBC“Don't embed credentials in the URL, because logs or errors can expose them.”
↩︎ Reading a database table over JDBC“It supports reading data and appending or overwriting entire tables, not row-level modifications.”
↩︎ Writing a DataFrame to a database - 9.
“If true, truncates the target table in overwrite mode instead of dropping and recreating it.”
↩︎ Writing a DataFrame to a database - 10.https://docs.databricks.com/aws/en/pyspark/reference/classes/dataframewriter/partitionByOfficial docs
“If specified, the output is laid out on the file system similar to Hive's partitioning scheme.”
↩︎ Partitioned output on a path and reading it back - 11.https://docs.delta.io/delta-batchSecondary source
“You can use the SQL session configuration spark.sql.files.maxRecordsPerFile to specify the maximum number of records to write to a single file”
↩︎ Partitioned output on a path and reading it back“Any existing logical partitions for which the write does not contain data will remain unchanged.”
↩︎ Overwriting partitioned output: static vs dynamic“If present, the query-specific option overrides the mode defined in the session configuration.”
↩︎ Overwriting partitioned output: static vs dynamic“The default for partitionOverwriteMode is static.”
↩︎ Exam trap 4“The default for partitionOverwriteMode is static.”
↩︎ Prediction - 12.
“replace all the existing data in each partition for which the write will commit new data”
↩︎ Overwriting partitioned output: static vs dynamic“Not recommended for new workloads.”
↩︎ Overwriting partitioned output: static vs dynamic“Dynamic partition overwrites replace all the existing data in each partition for which the write will commit new data and leaves all other partitions unchanged.”
↩︎ Checkpoint