liveBook · Manning

Try_cast

As explained in DuckDB in Action

try_cast is a DuckDB SQL function that converts a value to a target type and returns NULL instead of raising an error when conversion fails.

try_cast converts a value to a target type while returning NULL when conversion fails instead of aborting the query. This is useful when exploring nested JSON whose fields contain inconsistent values, such as a string that cannot become DOUBLE. section 5.3

Safely typing nested shot data

After unnesting the home and away shot lists, cast each row as a STRUCT with numeric X, Y, and xG fields: CREATE OR REPLACE VIEW shots AS (...) SELECT try_cast(row AS STRUCT(id BIGINT, X DOUBLE, Y DOUBLE, xG DOUBLE, ...)) AS row; Values that cannot be converted to DOUBLE become literal NULL values, allowing exploratory queries to continue. Inspect or flatten the resulting STRUCT before aggregating fields such as xG. section 5.3

Use ordinary CAST when conversion errors should expose bad data immediately; use try_cast when field-level cleanup would cost too much during exploration. section 5.3

How DuckDB in Action covers it

How deep it goes
Explains failed conversions and whole-STRUCT application, but defers field-level cleanup and date-formatting details.
Examples
Uses football-shot JSON containing malformed numeric fields such as X, Y, and xG.
What it assumes
Assumes nested JSON, STRUCT values, unnesting, and SQL casting; distinguishes strict CAST behavior from safe conversion.
What you can do after
Apply it via DuckDB SQL to preserve exploratory query results when nested-field conversion fails.
How it connects
Connects try_cast with CAST, JSON, STRUCT, unnesting, views, DOUBLE, and NULL values.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of DuckDB in Action. The section links point to the parts of the book it draws on.