Thursday, 5 June 2025

Understanding Column Mode in BigQuery and How to Modify It?

In BigQuery, each column in a table has a mode that defines how values are stored and whether they can be null. The three modes available are:

 

·      NULLABLE: The column can contain NULL values.

·      REQUIRED: The column cannot have NULL values (must always contain a value).

·      REPEATED: The column can store an array of values.

 

Changing column modes is sometimes necessary when modifying schemas to allow or restrict NULL values. However, in BigQuery, mode changes have limitations.

 

Changing Column Mode in BigQuery

You can change a column mode from REQUIRED to NULLABLE, but you cannot change a column from NULLABLE to REQUIRED directly.

 

To change a column from REQUIRED to NULLABLE, use the following SQL command:

ALTER TABLE project.dataset.table_name 
ALTER COLUMN column_name DROP NOT NULL;

This command allows NULL values in a column that was previously REQUIRED.

 

For example, I have employees table, where it has four fields (id, name, age and mail) and all are mandatory.

 


You can change the mode from REQUIRED to NULLABLE in two ways

 

Approach 1: Using Alter statement 

ALTER TABLE myProject.myDataset.employees 
ALTER COLUMN age DROP NOT NULL;

 Upon successful execution of the statement, you can the mode for the column age is set to NULLABLE. 


 

Approach 2: Using User interface.

 

Click on “Edit schema” button on employees schema section.

 


Click on the options next to the Mode section for the field you want to modify, then select the desired mode. For example, I changed the mode of the mail field to NULLABLE and saved the changes.

 

Now you can observe that the mode for mail field is set to NULLABLE. 


 

However, if you need to change from NULLABLE to REQUIRED, BigQuery does not support this operation directly. A workaround is to:

 

·      Create a new table with the desired schema (where the column is REQUIRED).

·      Copy data from the existing table to the new table, ensuring there are no NULL values.

 

Previous                                                    Next                                                    Home

Wednesday, 4 June 2025

SAFE_CAST in BigQuery to perform Error-Free Data Conversion

When working with BigQuery, data often comes in different formats, and converting data types is a common task. However, using CAST directly can lead to errors if the data is not in the expected format. This guide introduces SAFE_CAST, a safer alternative that prevents query failures by replacing conversion errors with NULL. 

This tutorial walks you through:

·      Creating a table in BigQuery

·      Inserting sample data (including incorrect values)

·      Using SAFE_CAST to handle invalid conversions safely

·      Understanding when to use SAFE_CAST vs. CAST

 

By the end of this guide, you’ll know how to perform type conversions in BigQuery without worrying about query failures.

 

Using SAFE_CAST in BigQuery

The SAFE_CAST function in BigQuery is used to convert one data type to another without causing errors. If the conversion fails, instead of throwing an error, SAFE_CAST replace the value with NULL. This is useful when working with datasets that may have inconsistent or incorrect data formats.

 

Syntax

SAFE_CAST(expression AS target_data_type)

Here,

·      expression: The value to be converted.

·      target_data_type: The data type to which the value should be converted.

 

Step-by-Step Guide

Step 1: Create a Table

Let's create a table named employee_data with columns of different data types.

CREATE TABLE my_project.my_dataset.employee_data (
    emp_id STRING,
    age STRING,  -- Storing age as a string (to demonstrate SAFE_CAST)
    salary STRING  -- Storing salary as a string (to demonstrate SAFE_CAST)
);

Note: We are using STRING type for age and salary to simulate real-world scenarios where data may be stored incorrectly.

 

Step 2: Insert Sample Records

We will insert some records, including some invalid values that cannot be converted to integers or floats.

INSERT INTO my_project.my_dataset.employee_data (emp_id, age, salary)
VALUES
    ('E101', '30', '50000.75'),    -- Valid age and salary
    ('E102', 'Twenty-five', '60000'), -- Invalid age (non-numeric string)
    ('E103', '40', 'Invalid'),      -- Invalid salary (non-numeric string)
    ('E104', '35', '70000.50');     -- Valid age and salary

 

Let’s print employee_data content by executing below command.

 

SELECT * FROM my_project.my_dataset.employee_data;

 


Step 3: Using SAFE_CAST to Convert Data Types

Now, we will use SAFE_CAST to safely convert age and salary to INT64 and FLOAT64, respectively.

 

SELECT 
    emp_id,
    SAFE_CAST(age AS INT64) AS age_converted,
    SAFE_CAST(salary AS FLOAT64) AS salary_converted
FROM my_project.my_dataset.employee_data;

 

You can observe following output.

 


 

As you see above result,

·      The valid values are converted correctly.

·      The invalid values are replaced with NULL instead of throwing errors.

 

When to Use SAFE_CAST?

·      Handling Invalid Data: Prevents errors when encountering incorrect data formats.

·      Data Cleaning: Helps in processing raw data without stopping execution.

·      Working with External Data Sources: Useful when data comes from external sources with unknown formats.

 

Comparison: CAST vs. SAFE_CAST

Function

Behavior

CAST(value AS INT64)   

Throws an error if conversion fails.

SAFE_CAST(value AS INT64)  

Returns NULL if conversion fails.

 

In summary,

·      SAFE_CAST is a safer alternative to CAST.

·      It avoids query failures by replacing conversion errors with NULL.

·      It is useful for cleaning and transforming data in BigQuery.

 


  

Previous                                                    Next                                                    Home

Changing Column Data Types in BigQuery: A Step-by-Step Guide

Modifying the data type of a column in BigQuery requires understanding the concepts of coercible and castable data types.

 

·      A coercible data type can be automatically converted into another type without loss of information, such as converting an INT64 to a NUMERIC.

 

·      A castable data type requires explicit conversion and may involve potential data loss, like converting a STRING to a DATE.

 

1. Changing to a Coercible Data Type

For coercible data types, you can use the ALTER TABLE statement

ALTER TABLE `project.dataset.table`
ALTER COLUMN column_name
SET DATA TYPE new_data_type;


 

 For instance, in the employee table, the employee_id column is of type INTEGER. It can be converted to BIGNUMERIC using the following statement: 

ALTER TABLE `project.dataset.employee`
ALTER COLUMN employee_id
SET DATA TYPE BIGNUMERIC;

After executing the statement, refresh the schema, you can observe that the type of column employee_id is converted to BIGNUMERIC.  

 


2. Changing to a Castable Data Type

For castable data types, you need to create a new table with the desired schema and cast the column accordingly:

 

Syntax

 

CREATE TABLE `project.dataset.new_table` AS
SELECT
  column1,
  column2,
  CAST(column_to_change AS new_data_type) AS column_to_change,
  column4
FROM
  `project.dataset.old_table`;

The following SQL snippet creates the employee_new table in project.dataset by selecting specific columns from employee, while converting the employee_id column to an INTEGER type.  

 

CREATE TABLE `project.dataset.employee_new` AS
SELECT
  first_name,
  last_name,
  CAST(employee_id AS INTEGER) AS employee_id,
  email
FROM
  `project.dataset.employee`;

This operation ensures that the employee_new table retains the selected columns while transforming employee_id into an integer data type.

 

2.1 How to change the column type in existing table only?

Write the SELECT Query:

SELECT  
    CAST(employee_id AS INTEGER) AS employee_id,  
    first_name,  
    last_name,  
    email,  
    hire_date,  
    department,  
    salary,  
    my_age  
FROM `project.dataset.employee`  
WHERE true;

 

Configure Query Settings:

Click on More → Query Settings

 


In the Query Settings form:

·      Set Destination to "Set a destination table for query results"

·      Choose Destination table write preference as "Overwrite table"

·      Choose the same dataset and table as destination table.

 

Click the Save button to apply settings.

 


Run the query to store the results in the specified destination table.

 

Now go back to the schema tab, you can observe that the employee_id column data type is changed to INTEGER.

 


 

Previous                                                    Next                                                    Home