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?
A schema passed through schema() lets the CSV source skip the inference read and parses rows straight into the declared types, so order_id comes back as a long. inferSchema adds a full scan and would pick integer for values that fit in 32 bits. Casting afterwards still pays for that scan. The header option only marks the first line as a header row and does not set types.
“By specifying the schema here, the underlying data source can skip the schema inference step, which speeds up data loading.”Source: docs.databricks.com
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/")
Correct answer: B — schema(order_schema)
- A. Turning on
inferSchemamakes Spark scan the file to guess column types, which is exactly the slow, unreliable path the engineer needs to avoid, and it would not guaranteeorder_idcomes back as a long. - B. Passing the
StructTypedirectly forces every row to be parsed according to the declared field names and types, soorder_idis read as aLongTypewith no inference scan required. - C. Declaring a header only tells Spark to treat the first line as column names; it says nothing about column types and does nothing to prevent inference from running.
- D. Chaining
formatandloadis just an alternate way to specify the CSV source path and does not attach a schema, so the file would still fall back to default typing behavior.
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?
Correct answer: A — Spark skips the schema-inference scan entirely and parses each row directly according to the field names and types declared in customSchema.
- A. Providing an explicit schema is precisely what lets Spark bypass the extra pass over the data that inference requires, so parsing goes straight to typed values using the declared fields.
- B. This describes wasted work Spark does not do; once a schema is supplied there is no need to also infer one, since inference exists only to produce a schema when none was given.
- C. Schema application is not partition-specific: the same declared schema is used to parse every partition of the file, so there is no partial fallback to inference on other partitions.
- D. Spark does not blend an inferred schema with a supplied one; supplying
customSchemareplaces inference outright rather than combining with it.
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'.
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.
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.
| Type object | What 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) |
It builds a StructType object, not a DDL string, and it declares only event_id, so event_ts is missing. The compact form is schema("event_id STRING, event_ts TIMESTAMP").
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")schema() accepts either a StructType or a DDL-formatted string, and both give the same result. option() and options() set generic key-value source options and are not how a reader receives its schema. format() names the data source, such as csv or json.
Source: docs.databricks.comCheckpoint 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/")
Correct answer: A — schema("event_id STRING, event_ts TIMESTAMP")
- A. The reader's
schema()method accepts a DDL-style string directly, so this line applies the compact string schema exactly as the team wants, typingevent_idandevent_tswithout building aStructTypeobject. - B. There is no generic
schemakey for the reader'soption()method; DataSource options configure things like delimiters and parsing modes, not the column schema itself, so this call has no effect on typing. - C.
StructType.add()expects an actualDataTypeinstance such asStringType(), not the bare word"STRING", so this raises an error rather than producing the required inline string schema. - D. Disabling
inferSchemaonly stops Spark from guessing types on its own; it does not supply the specificevent_id/event_tstypes the team needs, so columns would fall back to generic defaults.
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", ...):
| Mode | What happens to a row with an unparseable field |
|---|---|
| PERMISSIVE (default) | Row is kept; nulls are inserted for the fields that could not be parsed |
| DROPMALFORMED | Row is dropped from the result |
| FAILFAST | The 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.
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?
CSV has no column-name metadata, so Spark applies schema fields by position. The second declared field, review_id, reads the file's second column, which holds ratings. The values shift into the wrong fields and no error is raised.
“CSV has no column-name metadata, so Spark maps schema fields to columns by position — a mismatched schema shifts values into the wrong fields.”Source: docs.databricks.com
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.
The parse mode decides what happens to a row that does not fit the declared schema. PERMISSIVE is the default and turns bad values into nulls, DROPMALFORMED drops the row, and only FAILFAST aborts the read. Adding a _corrupt_record column makes the rows PERMISSIVE nulled out visible.
“PERMISSIVE (default): nulls are inserted for fields that could not be parsed correctly”Source: docs.databricks.com
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").
# 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.
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()Only overwrite replaces the data already at the path. errorifexists is the default and throws an exception because d already holds data. append adds new files next to the old ones, and ignore skips the write without saying so. Reading back with schema=df.schema then restores the original types without an inference scan.
Source: docs.databricks.com5.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.
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.
| Behaviour | insertInto | saveAsTable |
|---|---|---|
| Column matching | By position; column names are ignored | By column name |
| How to overwrite | insertInto(name, overwrite=True) | mode("overwrite").saveAsTable(name) |
| Schema on overwrite | Must be the same as the table's schema | Need not match the existing table schema |
| Default when table exists | Inserts (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?
insertInto writes into an existing table and only replaces its data when overwrite=True is passed. Without that flag it adds the new rows next to the old ones. A plain saveAsTable on an existing table throws an exception, because the default mode is errorifexists, and ignore skips the write without saying so.
“df.write.insertInto("existing_table", overwrite=True)”Source: docs.databricks.com
Sources
(9)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 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.
“Use SparkSession.read to access this interface.”
↩︎ What schema inference costs and how schema() avoids it - 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 - 4.
“Long data type, representing signed 64-bit integers”
↩︎ Two ways to write a schema: StructType or a DDL string - 5.https://docs.databricks.com/aws/en/query/formats/csvOfficial docs
“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 - 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 - 7.
“Interface for saving the content of the non-streaming DataFrame out into external storage.”
↩︎ Writing and overwriting DataFrames with DataFrameWriter - 8.https://docs.databricks.com/aws/en/pyspark/reference/classes/dataframewriter/insertIntoOfficial docs
“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 - 9.https://docs.databricks.com/aws/en/pyspark/reference/classes/dataframewriter/saveAsTableOfficial docs
“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