Skip to content
Bronze 5 min read · Types 2 practice problems ↓

cast and schemas

Data from CSV files, JSON and APIs often arrives as text, even when it holds numbers and dates. Until you convert it, sums fail and "10" sorts before "9". This lesson shows how to change a column's type, what happens to values that will not convert, and how to read a DataFrame's schema.

Step 1 · PySpark functions · Bronze · Clean and type, lesson 1 of 5

Read first: select (skip if you know it)

In plain words first

A form filled in by hand has "1,200" in the amount box. To a person it is a number; to a computer it is a few characters. Before you can add it up, someone has to read it and write it down as a real number. If the box says "about 1200", the conversion fails.

cast does that conversion for a whole column. Values that cannot be converted become nullnull: A missing or unknown value. Any comparison with null gives null, so filters treat it as false. Learn more →, or raise an error with ANSI mode on, as this lesson shows.

What it does

Data read from CSV, JSON or an API often arrives as strings. cast converts a column to another type so you can do maths, compare dates and sort numbers numerically ("10" sorts before "9" as a string).

Type stringSpark typeExample
"int" / "bigint"IntegerType / LongType"42" → 42
"double"DoubleType"19.99" → 19.99
"decimal(10,2)"DecimalType(10, 2)"19.99" → 19.99 exactly
"boolean"BooleanType"true" → true, "yes" → null
"date"DateType"2025-03-01" → 2025-03-01
"timestamp"TimestampType"2025-03-01 09:15:00"
"string"StringType42 → "42"

Run the example

PySparkSpark SQL

Input: raw_orders

order_idamountqtypaid
119.992true
2abc1false
3nulltwotrue
473yes
from pyspark.sql import functions as F
result = raw_orders.select(
    F.col("order_id").cast("int").alias("order_id"),
    F.col("amount").cast("double").alias("amount"),
    F.col("qty").cast("int").alias("qty"),
    F.col("paid").cast("boolean").alias("paid"),
)
SELECT CAST(order_id AS INT)   AS order_id,
       CAST(amount AS DOUBLE)  AS amount,
       CAST(qty AS INT)        AS qty,
       CAST(paid AS BOOLEAN)   AS paid
FROM raw_orders

Input

columnraw value
amount"abc"
qty"two"
paid"yes"

Output

columnafter cast
amountnull
qtynull
paidnull

What happened to each bad value

No error, no warning: three values quietly became null. In the running example this is classic Spark behaviour, which the in-browser engine follows.

Spark 4.0: ANSI mode and try_cast

Spark 4.0 turns on spark.sql.ansi.enabled by default. With it, CAST('abc' AS INT) fails the query with a CAST_INVALID_INPUT error instead of returning null. When bad values are expected, say so explicitly with try_cast, which returns null:

PySparkSpark SQL · Explicit about bad values
# Spark 4.0+
clean = raw_orders.select(F.col("amount").try_cast("double").alias("amount"))
# Spark 3.x: F.expr("try_cast(amount AS DOUBLE)")
SELECT try_cast(amount AS DOUBLE) AS amount FROM raw_orders

Counting what a cast lost

A value that was present before the cast and null after it is a conversion failure. Count those before you trust the result:

PySparkSpark SQL · Audit a cast
bad = raw_orders.filter(
    F.col("amount").isNotNull() & F.col("amount").cast("double").isNull()
)
print(bad.count())   # 1 row: "abc"
SELECT * FROM raw_orders
WHERE amount IS NOT NULL AND CAST(amount AS DOUBLE) IS NULL

Reading a schema

  • df.printSchema() prints the tree of column names, types and nullability.
  • df.dtypes returns a list such as [("order_id", "int"), ("amount", "double")].
  • df.schema returns the StructType object; df.schema["amount"].dataType gives one column's type.
  • To cast many columns at once, build one select: df.select([F.col(c).cast("double") for c in cols]).

double vs decimal for money

A double is a binary fraction: 0.1 + 0.2 is 0.30000000000000004. Summing millions of prices as doubles drifts by cents. decimal(p, s) stores exact digits: p total digits, s after the point. Use decimal(18,2) or similar for money. Values that do not fit the precision become null (or an error under ANSI mode), so leave room for totals.

Watch out: casting a double to int truncates toward zero: -2.7 becomes -2. Round first with F.round if you want rounding.

Common mistakes

  • Not checking for nulls after a cast — "1,200" and "N/A" cast to double become null, and sum skips them, so revenue is quietly low. Count values that are not null before the cast and null after it.
  • Money as double — As doubles, 0.1 + 0.2 is 0.30000000000000004; over millions of prices the total drifts by cents. Use decimal(18,2).
  • Sorting numbers stored as strings — "10" sorts before "9", so an order-by on a string amount puts 10 before 9. Cast to a number before orderBy.
  • Expecting "yes"/"no" to cast to boolean — "yes" cast to boolean is null: only true/false, t/f, y/n and 1/0 style values convert. Map the rest with when/otherwise.

Key takeaways

  • Spark 4.0 turns on ANSI mode: a bad cast fails the query with CAST_INVALID_INPUT, so use try_cast where bad values are expected.
  • CSV columns are strings unless you give the reader a schema; give one so types are set at load time.
  • To cast many columns, build one select: df.select([F.col(c).cast("double") for c in cols]).
  • A decimal that does not fit its precision becomes null (or an error under ANSI): leave room for totals.

Interview prep

THE QUESTION

"After loading a CSV, the total revenue is lower than the source system. Where would you look?"

Types first: CSV columns are strings unless a schema is given, and a cast to a number turns bad values (thousand separators like "1,200", currency symbols, "N/A") into null, which sum ignores. Compare non-null counts before and after the cast, check the corrupt-record column if the reader was PERMISSIVE, and use decimal for money. In Spark 4.0 ANSI mode, the cast would fail loudly instead, which is the reason it is the default.

Avoid: "the source must be wrong". Look at your own casts first: a failed cast becomes null silently (or errors under ANSI mode).

Follow-ups · answer out loud, then open

Follow-up"What changes for casts in Spark 4.0?"
ANSI mode is on by default, so cast("abc" as int) raises a CAST_INVALID_INPUT error instead of returning null. Use try_cast (or try_to_number) where bad values are expected and should become null.
Scenario"How would you find the rows whose amount failed to cast?"
Keep the original string and compare: df.filter(F.col("amount_raw").isNotNull() & F.col("amount").isNull()). Count them, sample them, and route them to a quarantine table instead of letting sum silently ignore them.
Trap"Casting a double 2.7 to int rounds it to 3."
Casting to an integer type truncates toward zero, so 2.7 becomes 2 and -2.7 becomes -2. Use F.round first if you need rounding.

Check yourself

3 questions

In classic (non-ANSI) Spark, what is CAST('abc' AS INT)?

Show the answer

null. Invalid input becomes null without an error.

Which function returns null for bad input even when ANSI mode is on?

Show the answer

try_cast. try_cast is the explicit "null on failure" cast.

Which type should store prices?

Show the answer

decimal(18,2). Decimals store exact digits; doubles accumulate binary rounding errors.

Practise this

Interview problems on filtering & selection, graded on hidden tests

Keep going

Up next · Clean and type · lesson 2 of 5 · 5 min read
String functions
concat vs concat_ws, substring, split, trim and padding, with the null traps in each.

Related lessons

Previous: orderBy

Primary sources: Column.cast · Data types · ANSI compliance