liveBook · Manning

Cast operator

As explained in Snowflake Data Engineering

The cast operator explicitly converts an expression to a specified data type.

The Snowflake cast operator (::) explicitly converts an expression to a specified data type. When JSON keys are selected from a VARIANT column, casting makes values usable as relational columns, such as VARCHAR, DATE, or NUMBER. section 4.2

Use casts while flattening semistructured order data:

  • Cast customer names to VARCHAR and order dates to DATE while selecting top-level JSON keys. section 4.2
  • Cast nested delivery dates, baked-good types, and quantities after applying LATERAL FLATTEN. section 4.2
  • Use TRY_TO_DATE or TRY_TO_NUMBER when malformed source values should become NULL instead of causing an error. section 4.2
Listing 4.2 Selecting values from keys at the highest level of the hierarchy
select 
  customer_orders:"Customer"::varchar as customer, 
  customer_orders:"Order date"::date as order_date, 
  customer_orders:"Orders"
from ORDERS_PARK_INN_RAW_STG;

Runnable SQL casts top-level JSON values into relational columns. section 4.2

Listing 4.4 Selecting values from JSON keys at the third level of the hierarchy
select 
  customer_orders:"Customer"::varchar as customer, 
  customer_orders:"Order date"::date as order_date, 
  CO.value:"Delivery date"::date as delivery_date,
  DO.value:"Baked good type":: varchar as baked_good_type,
  DO.value:"Quantity"::number as quantity
from ORDERS_PARK_INN_RAW_STG,
lateral flatten (input => customer_orders:"Orders") CO,     #1
lateral flatten (input => CO.value:"Orders by day") DO;     #2

Runnable SQL applies casts while flattening nested order arrays. section 4.2

How Snowflake Data Engineering covers it

How deep it goes
Demonstrates executable casts at three JSON hierarchy levels and defers malformed-input handling to TRY conversion functions.
Examples
Uses customer orders, dates, delivery dates, baked-good types, and quantities extracted from nested JSON.
What it assumes
Assumes familiarity with JSON keys and VARIANT values while demonstrating explicit conversion from those values.
What you can do after
Apply it via Snowflake SQL to produce typed columns while flattening semistructured data.
How it connects
Connects JSON extraction with VARIANT, LATERAL FLATTEN, relational tables, and error-handling conversion functions.

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