CertSafari
    Databricks Certified Associate Developer for Apache Spark· Lessons

    Domain 2 · Lesson 8/32

    Reading and writing Spark DataFrames: files, JDBC and partitioned overwrite

    Utilize common data sources such as JDBC, files, etc., to efficiently read from and write to Spark DataFrames using Spark SQL, including overwriting and partitioning by column.

    20 min read
    5% of exam
    12 sources
    Published 21 Oct 2026
    Docs as of 17 Oct 2026

    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.

    A CSV read written as the full chain: format, options, an explicit DDL schema, then loadpython
    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.

    The writer side of the same pattern: format, mode, option, partitionBy, savepython
    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:

    Built-in formats and what their options are mostly about
    Format stringKindTypical options
    parquetColumnar, Spark's defaultcompression
    orcColumnar with lightweight indexescompression, mergeSchema
    jsonText records, flexible schemamultiline records, schema inference
    csvDelimited textheader, delimiter, malformed records
    textOne line (or one file) per rowlineSep, wholetext
    deltaACID table format, Databricks defaultreplaceWhere, 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")

    Sources123

    2.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.

    The four save modes when the target already holds data
    Mode stringBehaviour when data exists
    error / errorifexists (default)Throws an exception; nothing is written
    appendAdds this DataFrame's rows to the existing data
    overwriteReplaces the existing data
    ignoreSilently skips the write; existing data is untouched
    Each save mode applied to a path-based writepython
    # 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?

    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?

    Sources42

    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.

    JDBC read options and what each one controls
    OptionRequired?What it does
    dbtableYes, or queryNames the table to read; cannot be combined with query
    queryYes, or dbtableA SQL statement run on the remote database; cannot be combined with dbtable
    fetchsizeNoRows fetched per round trip; larger values trade memory for speed
    partitionColumnNoColumn with evenly spread values used to split the read
    lowerBound / upperBoundNoMinimum and maximum of partitionColumn used to compute the splits
    numPartitionsNoNumber 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.

    A JDBC read through a named connection, with the filter pushed into the query optionpython
    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?

    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?

    Sources5678

    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.

    Reading a table in ten parallel slices of the id rangepython
    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"}
    )

    Sources56

    5.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.

    Replacing a PostgreSQL table's contents with a DataFramepython
    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"}
    )

    Sources897

    6.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.

    Writing partitioned Parquet, reading the root (column recovered), then reading one partition directory (column absent)python
        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.

    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|
        # +---+-------------+

    Checkpoint 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?

    Sources10211

    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.

    Dynamic partition overwrite in SQL via the session config, then per-write via the DataFrameWriter optionpython
    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?

    Sources1112

    Sources

    (12)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 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
    2. 3.
      “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
    3. 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
    4. 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
    5. 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
    6. 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
    7. 9.
      “If true, truncates the target table in overwrite mode instead of dropping and recreating it.”
      ↩︎ Writing a DataFrame to a database
    8. 10.
      “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
    9. 11.
      “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
    10. 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

    Spotted a mistake, or was something unclear? Tell us.