CertSafari
    Databricks Certified Associate Developer for Apache Spark· Lessons

    Domain 3 · Lesson 17/32

    Reading and writing Spark DataFrames with explicit schemas

    Manage input and output operations by writing, overwriting, and reading DataFrames with schemas.

    17 min read
    3% of exam
    9 sources
    Published 21 Oct 2026
    Docs as of 30 Sep 2026

    What you will be able to do

    • Read CSV and JSON files with an explicit schema passed as a StructType or a DDL string, and explain why this skips schema inference
    • Choose column types deliberately, such as LongType instead of IntegerType, when declaring a schema
    • Predict what happens when file contents do not match a declared schema, and capture malformed rows with _corrupt_record
    • Write and overwrite DataFrames with DataFrameWriter, and choose between insertInto and saveAsTable when the target table already exists

    Key concept

    Explicit read schema — A StructType or DDL string passed to spark.read through schema(). Spark parses the data directly into those column names and types and never runs its own schema-inference pass, so loading is faster and the column types are the ones you chose.

    1.What schema inference costs and how schema() avoids it

    Every DataFrame has a schema: column names plus a type for each column. Formats that store types, such as Parquet, carry that schema with them. CSV and JSON files are text, so Spark has to get the types from somewhere. It can work them out from the data, which is schema inference, or you can declare them. The reader is reached through spark.read, which returns a DataFrameReader. On that reader, schema() declares the types and option("inferSchema", "true") asks Spark to work them out.

    On a large file, inference costs a full extra read. When inferSchema is enabled, the CSV reader reads the input once just to decide the column types, then reads it again to load the rows. With a multi-gigabyte daily extract, that is a complete scan you pay for before any real work begins. The CSV reference gives two ways to avoid it: turn inferSchema off, or pass a schema explicitly with schema.

    An explicit schema does more than save time. It is a contract. Spark does not run inference alongside your schema, does not sample a partition to check it, and does not widen your types to fit what it sees. Each row is parsed into exactly the fields you declared. This matters when the inferred type would be wrong for your downstream logic. An order_id column whose values fit in 32 bits today would be inferred as an integer, and a pipeline that needs it as a long to avoid overflow later has to say so. Only schema() can do that. option("inferSchema", "true") brings the scan back, and the header option only controls whether the first line is a header row, not which types the columns get.

    Checkpoint 1 of 9· Check yourself

    A daily job loads a 6 GB CSV extract. Its values fit in 32 bits today, but downstream logic needs order_id as a long. The team also wants to stop paying for an extra pass over the file before loading. Which change to the reader meets both goals?

    Checkpoint 2 of 9· Exam question

    A data engineer reads a daily CSV extract with no header row. The order_id column must be read as a long (not the int Spark would infer) to avoid downstream overflow, and schema inference is too slow on the multi-gigabyte file. Which line fills the blank so the file is read with the required types without triggering an inference scan? from pyspark.sql.types import StructType, StructField, LongType, StringType order_schema = StructType([ StructField("order_id", LongType(), True), StructField("customer", StringType(), True) ]) df = spark.read.____.csv("/mnt/raw/orders/")

    Checkpoint 3 of 9· Exam question

    A developer calls .schema(customSchema) on a DataFrameReader before loading a CSV file. What effect does this have on how Spark processes the file?

    Sources12

    2.Two ways to write a schema: StructType or a DDL string

    schema() accepts either a StructType object or a DDL-formatted string. Both produce the same result. They differ only in how you write the schema. A StructType is a list of StructField entries. Each entry holds a name, a data type object such as StringType() or IntegerType(), and a nullable flag. A DDL string writes the same thing inline as comma-separated name TYPE pairs, for example 'col0 INT, col1 DOUBLE'.

    The same two-column schema declared as a StructType and as a DDL stringpython
    from pyspark.sql.types import StructType, StructField, StringType, IntegerType
    
    # Define schema
    schema = StructType([
        StructField("name", StringType(), True),
        StructField("age", IntegerType(), True)
    ])
    
    # Read CSV with schema
    df = spark.read.schema(schema).csv("path/to/file.csv")
    
    # Read CSV with DDL-formatted string schema
    df = spark.read.schema("name STRING, age INT").csv("path/to/file.csv")

    The DDL string is the compact choice for short, flat schemas typed inline, such as a JSON feed that needs a string event_id and a timestamp event_ts. A StructType is better when the schema is built in code, reused across jobs, or taken from another DataFrame's .schema attribute. The schema always goes through the schema() method, or the schema parameter of format methods such as csv(path, schema=...) and json(path, schema, ...). Passing it as a generic option("schema", ...) is not how a reader receives its schema.

    A DDL string schema applied to a CSV read; printSchema confirms the declared typespython
    import tempfile
    with tempfile.TemporaryDirectory(prefix="schema") as d:
        spark.read.schema("col0 INT, col1 DOUBLE").format("csv").load(d).printSchema()
        # root
        #  |-- col0: integer (nullable = true)
        #  |-- col1: double (nullable = true)

    Choosing the type object is where an explicit schema earns its keep. The integer types differ in width, and picking the wider one is the usual reason to declare a schema instead of inferring one.

    Common PySpark type objects used in StructField declarations
    Type objectWhat it holds
    IntegerType()Signed 32-bit integers
    LongType()Signed 64-bit integers
    DoubleType()Double precision floats
    StringType()String data
    DateType()Dates (datetime.date)
    TimestampType()Timestamps (datetime.datetime)

    Checkpoint 4 of 9· Fill the gap

    The second read below declares its schema as a DDL string. Which DataFrameReader method goes in the blank so that Spark gets name as a string and age as an integer, without running inference?

    from pyspark.sql.types import StructType, StructField, StringType, IntegerType
    
    # Define schema
    schema = StructType([
        StructField("name", StringType(), True),
        StructField("age", IntegerType(), True)
    ])
    
    # Read CSV with schema
    df = spark.read.schema(schema).csv("path/to/file.csv")
    
    # Read CSV with DDL-formatted string schema
    df = spark.read. ? ("name STRING, age INT").csv("path/to/file.csv")

    Checkpoint 5 of 9· Exam question

    A dataset arrives as newline-delimited JSON where every record must expose event_id as a string and event_ts as a timestamp. The team wants to define this schema inline as a compact string rather than build a StructType object. Which line reads the files with that requirement? df = spark.read.____.json("/mnt/raw/events/")

    Sources34

    3.When the data does not match the declared schema

    For CSV, a declared schema is matched to columns by position, not by name. CSV carries no column-name metadata, so the first field of the schema reads the first column, the second field reads the second, and so on. If the schema lists columns in a different order from the file, values land in the wrong fields with no error. A rating field may then hold comment text. Declare CSV schemas in the file's column order.

    Values that cannot be parsed into the declared type are handled by the reader's parse mode. A city name in an integer column is the typical case. The mode is set with option("mode", ...):

    CSV parser modes for rows that do not fit the declared schema
    ModeWhat happens to a row with an unparseable field
    PERMISSIVE (default)Row is kept; nulls are inserted for the fields that could not be parsed
    DROPMALFORMEDRow is dropped from the result
    FAILFASTThe whole read aborts

    Because PERMISSIVE turns bad values into nulls without warning, add a _corrupt_record string column to the schema so you can see those rows. Spark puts each malformed row in that column, and a filter on non-null values isolates them for review. If the badRecordsPath option is also set, it takes precedence: the malformed rows are written to that path and do not appear in the DataFrame.

    Adding _corrupt_record to an explicit schema to inspect rows that failed to parsepython
    schema = StructType([
      StructField("review_id", StringType(), True),
      StructField("rating", IntegerType(), True),
      StructField("comment", StringType(), True),
      StructField("_corrupt_record", StringType(), True)
    ])
    
    df = (spark.read
      .format("csv")
      .option("header", "true")
      .option("mode", "PERMISSIVE")
      .schema(schema)
      .load("/Volumes/<catalog>/<schema>/<volume>/reviews_csv")
    )
    display(df.filter(df["_corrupt_record"].isNotNull()))

    Checkpoint 6 of 9· Check yourself

    The CSV file's header is review_id,rating,comment. A developer reads it with header set to true and schema("rating INT, review_id STRING, comment STRING"). What ends up in the DataFrame's review_id field?

    Checkpoint 7 of 9· Match them up

    A CSV row has a city name in a column declared as INT. Match each setting to what it does with that row.

    Tap a term, then the definition that fits it.

    Sources5

    4.Writing and overwriting DataFrames with DataFrameWriter

    Output goes through df.write, which returns a DataFrameWriter for non-streaming DataFrames. Its format methods mirror the reader's: parquet, json, csv, orc, text, plus the generic format(...).save(path). What happens when the target already holds data depends on the save mode. Save modes (append, overwrite, ignore, errorifexists) are covered in their own lesson. The detail that matters here is that the default is errorifexists. A plain df.write.parquet(path) against an existing path fails, and replacing the data requires mode("overwrite").

    Overwriting and appending to a Parquet pathpython
    # 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")

    A schema completes the round trip. When you write CSV, the output files keep no types. Reading them back with the writing DataFrame's own df.schema as the read schema restores the original types without an inference scan. The example below writes a DataFrame to CSV with mode("overwrite") and reads it back with schema=df.schema. It also uses the CSV nullValue option, which is why Alice comes back as NULL.

    Overwrite to CSV, then read back using the original DataFrame's schemapython
        df = spark.createDataFrame([{"age": 100, "name": "Alice"}])
        df.write.mode("overwrite").format("csv").save(d)
    
        spark.read.csv(d, schema=df.schema, nullValue="Alice").show()

    Checkpoint 8 of 9· Fill the gap

    This job reruns every night, and the directory d still holds the CSV files from the previous run. Each run must replace those files and then read them back with the original types. Which save mode goes in the blank?

        df = spark.createDataFrame([{"age": 100, "name": "Alice"}])
        df.write.mode(" ? ").format("csv").save(d)
    
        spark.read.csv(d, schema=df.schema, nullValue="Alice").show()

    Sources67

    5.Overwriting a table: insertInto versus saveAsTable

    When the target is a table instead of a path, there are two writer methods, and they match columns differently. saveAsTable creates or writes a named table, covered in Persistent tables with saveAsTable. insertInto(tableName, overwrite) writes into a table that already exists. The difference that catches people out is how each one lines up your DataFrame's columns with the table's columns.

    insertInto with renamed columns still lands data by positionpython
    df.write.saveAsTable("tblA")
    
    df.selectExpr("age AS col1", "name AS col2").write.insertInto("tblA")

    Position matching is harmless while the column order matches the table and dangerous when it does not. If a DataFrame has the right columns in a different order, insertInto writes each one into whichever table column sits at the same position. saveAsTable in append mode uses column names to find the correct positions, so the same reordered DataFrame lands correctly. When a table already exists, append mode also keeps that table's existing format and options.

    The two methods also handle schema change differently when overwriting. insertInto requires the DataFrame's schema to be the same as the table's. Its overwrite=True flag replaces the data, not the table definition. saveAsTable with mode("overwrite") does not require the DataFrame's schema to match the existing table, so it can replace a table whose columns have changed.

    Writing to an existing table: insertInto compared with saveAsTable
    BehaviourinsertIntosaveAsTable
    Column matchingBy position; column names are ignoredBy column name
    How to overwriteinsertInto(name, overwrite=True)mode("overwrite").saveAsTable(name)
    Schema on overwriteMust be the same as the table's schemaNeed not match the existing table schema
    Default when table existsInserts (overwrite disabled by default)Throws an exception (errorifexists)

    Checkpoint 9 of 9· Check yourself

    Table sales_daily already exists and its definition never changes. Each night a DataFrame arrives with its columns in the table's order, and the job has to replace the rows already in the table. Which writer call does that?

    Sources89

    Sources

    (9)

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

    1. 1.
      “To avoid this, either disable inferSchema or specify the schema explicitly using schema.”
      ↩︎ What schema inference costs and how schema() avoids it
      “If inferSchema is enabled, this function reads the input once to determine the schema.”
      ↩︎ Exam trap 1
    2. 3.
      “A StructType object or a DDL-formatted string (for example, 'col0 INT, col1 DOUBLE').”
      ↩︎ Two ways to write a schema: StructType or a DDL string
      “By specifying the schema here, the underlying data source can skip the schema inference step, which speeds up data loading.”
      ↩︎ Key concept
      “By specifying the schema here, the underlying data source can skip the schema inference step, which speeds up data loading.”
      ↩︎ Prediction
    3. 5.
      “You can add the column _corrupt_record to the schema provided to the DataFrameReader to review corrupt records in the resultant DataFrame.”
      ↩︎ When the data does not match the declared schema
      “FAILFAST: aborts the reading if any malformed data is found”
      ↩︎ When the data does not match the declared schema
      “CSV has no column-name metadata, so Spark maps schema fields to columns by position — a mismatched schema shifts values into the wrong fields.”
      ↩︎ Exam trap 2
      “PERMISSIVE (default): nulls are inserted for fields that could not be parsed correctly”
      ↩︎ Exam trap 3
      “CSV has no column-name metadata, so Spark maps schema fields to columns by position — a mismatched schema shifts values into the wrong fields.”
      ↩︎ Checkpoint
      “PERMISSIVE (default): nulls are inserted for fields that could not be parsed correctly”
      ↩︎ Checkpoint
    4. 6.
      “error or errorifexists: Throw an exception if data already exists (default).”
      ↩︎ Writing and overwriting DataFrames with DataFrameWriter
      “df.write.insertInto("existing_table", overwrite=True)”
      ↩︎ Checkpoint
    5. 7.
      “Interface for saving the content of the non-streaming DataFrame out into external storage.”
      ↩︎ Writing and overwriting DataFrames with DataFrameWriter
    6. 8.
      “Requires that the schema of the DataFrame is the same as the schema of the table.”
      ↩︎ Overwriting a table: insertInto versus saveAsTable
      “Unlike DataFrameWriter.saveAsTable, DataFrameWriter.insertInto ignores column names and uses position-based resolution.”
      ↩︎ Prediction
    7. 9.
      “When mode is 'overwrite', the schema of the DataFrame does not need to match the existing table schema.”
      ↩︎ Overwriting a table: insertInto versus saveAsTable
      “When mode is 'append', if a table already exists, its format and options are used.”
      ↩︎ Overwriting a table: insertInto versus saveAsTable
      “Unlike DataFrameWriter.insertInto, DataFrameWriter.saveAsTable uses column names to find the correct column positions.”
      ↩︎ Exam trap 4

    Ready to test yourself?

    Practise Databricks Certified Associate Developer for Apache Spark in quiz mode.

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