Sub topic 6
Schemas and Data Types
This chapter assumes you can attach a Databricks notebook to compute, know basic Python or SQL, and have seen a DataFrame (a distributed table with named, typed columns). Here you will learn what a schema is, which types Spark offers, how to declare a schema, and which errors come from getting types wrong.
What a schema is
A schema is the list of column names, their data types, and whether each column allows nulls. Spark attaches one schema to every DataFrame. It uses the schema to plan queries, to store data compactly, and to decide which operations are legal.
Spark checks column names and types when it analyzes a query, not when the data is read. Because transformations are lazy, a bad column name fails at the next line that uses it. A value that cannot be converted to its declared type usually does not fail at all. It becomes null.
You can see a schema with printSchema():
from pyspark.sql import functions as F
orders = spark.createDataFrame(
[
(1, "alice", "2024-01-05", 120.0),
(2, "bob", "2024-01-06", 75.5),
(3, "alice", "2024-02-10", 30.0),
(4, "carol", "2024-02-11", None),
],
"order_id INT, customer STRING, order_date STRING, amount DOUBLE",
)
orders = orders.withColumn("order_date", F.to_date("order_date"))
orders.printSchema()
display(orders)The output of printSchema() looks like this:
root
|-- order_id: integer (nullable = true)
|-- customer: string (nullable = true)
|-- order_date: date (nullable = true)
|-- amount: double (nullable = true)The DDL string "order_id INT, customer STRING, ..." is one way to declare a schema. The to_date call converts order_date from a string to a real date. Both steps are covered below.
Common data types
| Spark SQL type | Python-side value | Typical use |
|---|---|---|
| `STRING` | `str` | Text, identifiers |
| `INT` / `BIGINT` | `int` | 32-bit and 64-bit whole numbers |
| `SMALLINT` / `TINYINT` | `int` | Small whole numbers |
| `DOUBLE` / `FLOAT` | `float` | Approximate decimals |
| `DECIMAL(p, s)` | `decimal.Decimal` | Exact decimals such as money |
| `BOOLEAN` | `bool` | True or false flags |
| `DATE` | `datetime.date` | Calendar day |
| `TIMESTAMP` | `datetime.datetime` | A point in time |
| `ARRAY<T>` | `list` | Repeated values |
| `MAP<K,V>` | `dict` | Key-value pairs |
| `STRUCT<...>` | `Row` | Nested record |
Some choices matter more than others:
- Use
DECIMALfor money.DOUBLEis binary floating point, so sums can differ from the exact decimal result in the last digits. - Use
BIGINTfor IDs and counters that may pass about 2.1 billion.INToverflows silently under default settings in many contexts, so choose the wider type early. - Use
DATEandTIMESTAMP, not strings, for time values. Date functions, sorting, and comparisons then behave correctly.
Three ways to get a schema
Let Spark infer it
Options such as inferSchema for CSV make Spark scan the data and guess. This is convenient for exploration. It costs an extra pass over the data, and the guess can change when the data changes. A column that held only integers yesterday can become a string today if one bad value appears.
Declare a DDL string
A DDL string is compact and readable. The next example reads a CSV file with a declared schema, so Spark skips the inference pass and the types stay the same on every run:
raw = (
spark.read
.format("csv")
.option("header", True)
.schema("order_id INT, customer STRING, order_date DATE, amount DOUBLE")
.load("/Volumes/main/default/raw/orders.csv") # replace with a path you can read
)Build a StructType
StructType expresses the same schema as Python objects. Use it when you build schemas programmatically or need per-field control, such as setting nullable to False:
from pyspark.sql.types import (
StructType, StructField,
IntegerType, StringType, DateType, DoubleType,
)
order_schema = StructType([
StructField("order_id", IntegerType(), nullable=False),
StructField("customer", StringType(), nullable=True),
StructField("order_date", DateType(), nullable=True),
StructField("amount", DoubleType(), nullable=True),
])
print(order_schema.simpleString())Running this prints struct<order_id:int,customer:string,order_date:date,amount:double>. You can pass order_schema to .schema(...) in place of the DDL string.
Changing types with cast
To change a column's type after loading, use cast. Cast works on a column expression, so you can combine it with withColumn:
cleaned = (
orders
.withColumn("order_id", F.col("order_id").cast("bigint"))
.withColumn("amount", F.col("amount").cast("decimal(10,2)"))
)
cleaned.printSchema()For dates, prefer to_date and to_timestamp. They accept a format string, so you control how text is read:
dates = spark.createDataFrame([("05/01/2024",)], "d STRING")
dates.select(F.to_date("d", "dd/MM/yyyy").alias("parsed")).show()Edge cases and common errors
Failed casts become null
A cast that cannot succeed returns null instead of raising an error in the default configuration. This is the most common silent data-quality bug:
bad = spark.createDataFrame([("10",), ("abc",)], "x STRING")
bad.select(F.col("x").cast("int").alias("x_int")).show()The row with abc shows null. To catch these rows, compare the original column with the cast result:
checked = bad.withColumn("x_int", F.col("x").cast("int"))
checked.filter(F.col("x").isNotNull() & F.col("x_int").isNull()).show()Databricks runtimes can also enable ANSI mode, where an invalid cast raises an error. Check your compute's setting before relying on either behavior. If you want null on failure no matter the mode, use try_cast in SQL or F.expr("try_cast(x AS int)").
Nullable is a hint, not a guarantee
nullable = False tells Spark it may skip null checks. Spark does not always verify the claim when you read files, and many file sources force columns to nullable anyway. Do not use it as data validation. Enforce rules with Delta table constraints or explicit filters.
Malformed rows in CSV and JSON
When a value does not fit the declared type, the reader's mode decides what happens:
| Mode | Behavior |
|---|---|
| `PERMISSIVE` (default) | Bad fields become null, and the row is kept |
| `DROPMALFORMED` | Rows that fail to parse are dropped |
| `FAILFAST` | The read raises an error on the first bad row |
Set it with .option("mode", "FAILFAST") when you prefer a loud failure to silent nulls.
Type mismatches in joins and comparisons
Comparing an INT column with a STRING column makes Spark insert an implicit cast. The result can be a null comparison or a slower plan. Cast both sides to the same type before joining.
Nested types
A STRUCT column holds named fields, and you reach inside with dot notation:
nested = spark.createDataFrame(
[(1, ("alice", "US"))],
"id INT, person STRUCT<name: STRING, country: STRING>",
)
nested.select("id", "person.name", F.col("person.country")).show()Arrays are usually flattened with F.explode, which turns each element into its own row.
Choosing an approach
- For exploration on small data, inference is acceptable.
- For production reads, declare the schema. It is faster and it makes type changes in upstream data visible as nulls or errors rather than silent shifts.
- For Delta tables, the schema is stored with the table, so you rarely declare it on read.
- After any cast, check for new nulls.
Exercise
A CSV file has an amount column. You read it with the schema amount INT, and the file contains the value 12.50 in one row. What do you expect to see in that row, and how would you find such rows?
Show answer
In the default PERMISSIVE mode, the value cannot be parsed as an integer, so the field becomes null and the read does not fail. To find these rows, read the column as a STRING, cast it to the target type in a new column, and filter for rows where the original is not null but the cast result is null. Alternatively, set the read mode to FAILFAST so the first bad row raises an error. A better type choice here is DECIMAL(10,2).
Exercise
Why is DECIMAL(10,2) usually a better type than DOUBLE for prices, and what does the (10,2) mean?
Show answer
DOUBLE stores approximate binary values, so sums of prices can show tiny rounding errors. DECIMAL stores exact decimal values. In DECIMAL(10,2), 10 is the total number of digits (precision) and 2 is the number of digits after the decimal point (scale), so the largest value is 99,999,999.99.