Type Conversion

CAST

CAST(value AS typename)

Description

Convert the value to the other data type. CAST() may fail if some value cannot be converted to the specified type.

The type name can be STRING, BOOL, FLOAT64, INT64, NUMERIC, DATE, DATETIME, TIME, TIMESTAMP.

Example

CAST(123 AS STRING)

Result: "123"

CAST("apple" AS INT64)

Result: raising an error

SAFE_CAST

SAFE_CAST(expression AS typename)

Description

Convert the value to the other data type. SAFE_CAST() is identical to CAST(), but it never fails. It returns NULL when facing an error.

The type name can be STRING, BOOL, FLOAT64, INT64, NUMERIC, DATE, DATETIME, TIME, TIMESTAMP.

Example

SAFE_CAST(123 AS STRING)

Result: "123"

SAFE_CAST("apple" AS INT64)

Result: null

DATE

Date(date_expression)

Description

Convert a string, timestamp, or datetime expression to a date variable in a "yyyy-mm-dd" format. For the timestamp inputs, you can optionally specify a time zone.

Example

DATE("2016-12-25")

Result: 2016-12-25

DATE(DATETIME("2016-12-25 23:59:59"))

Result: 2016-12-25

DATE(TIMESTAMP("2016-12-25 05:30:00+07"), "America/Los_Angeles")

Result: 2016-12-24

DATETIME

DATETIME(datetime_expression)

Description

Convert a string, timestamp, or date expression to a datetime variable in a "yyyy-mm-dd hh-mm-ss" format. For the timestamp inputs, you can optionally specify a time zone.

Example

DATETIME("2020-12-01 14:20:32")

Result: 2020-12-01T14:20:32

DATETIME(TIMESTAMP("2020-12-01 14:20:32+07"), "America/Los_Angeles")

Result: 2020-11-30T23:20:32

TIMESTAMP

TIMESTAMP(timestamp_expression)

Description

Convert a string, date, or datetime expression to a timestamp variable.

Example

TIMESTAMP("2020-12-25 15:30:00 UTC")

Result: 2020-12-25 15:30:00 UTC

TIME

TIME(time_expression)

Description

Convert a string, timestamp, or datetime expression to a time variable in a "hh-mm-ss" format. For the timestamp inputs, you can optionally specify a time zone.

Example

TIME(TIMESTAMP("2020-12-25 15:30:00+08"), "America/Los_Angeles")

Result: 23:30:00

Last updated