1. Meet BigQuery: store big tables, ask with SQL
1.4 Data types and SAFE_CAST
Highlights & notes
Select lesson text to highlight it, or tap Add note.
Bookmarks
Bookmark a lesson to see it here.
Every column has a type. The type tells BigQuery what the values are and what you may do with them. You cannot add two names, and you cannot find the month of a number.
INT64: whole numbersNUMERIC: exact decimals. Use it for money.FLOAT64: approximate decimals. Fine for measurements, risky for money.STRING,BOOL,DATE,TIMESTAMP(an exact moment, stored in UTC)
CAST(x AS INT64) changes a type. If one value cannot be changed, the whole query fails. SAFE_CAST returns NULL for that value and carries on.
Raw files arrive as text. In the silver layer, turn each column into its real type with SAFE_CAST, then count the NULLs it produced. Those are your bad rows.
Text to numbers, safely
One raw value is not a number.
SQL
SELECT raw_amount, SAFE_CAST(raw_amount AS INT64) AS amountFROM bronze.orders_raw;
Rows at this step
raw_amount | amount -----------+------- 55000 | 55000 700 | 700 abc | NULL
Quick check
What does CAST('abc' AS INT64) do?
Why money needs NUMERIC
The same sum with two types.
SQL
SELECT 0.1 + 0.2 AS float_sum, NUMERIC '0.1' + NUMERIC '0.2' AS numeric_sum;
Result
float_sum: 0.30000000000000004 numeric_sum: 0.3
Quick check
Which type should hold prices in rupees and paise?
Try it yourself
1. Run the second walkthrough query in the BigQuery sandbox.
2. Run SELECT SAFE_CAST('12x' AS INT64) and then the same with CAST. Compare the results.
Question 1 · Easy
Which type holds true or false?
Question 2 · Medium
What does SAFE_CAST('12x' AS INT64) return?
Question 3 · Hard
A bronze amount column is text with a few bad values. What is the best way to build silver?
Key takeaways
Choose the right type: INT64 for whole numbers, NUMERIC for money, DATE and TIMESTAMP for time. SAFE_CAST returns NULL where CAST would fail.
Save your progress
Start free and your progress, code and notes stay saved. Free for 1 month, no card needed.
Start free Log in