BigQuery reference
BigQuery SQL functions
The GoogleSQL functions data engineers use every day, with examples you can paste into the BigQuery console and run for free, the mistakes people make with them, and what they mean for cost. 143 functions in 12 categories.
No function matches. Try the statements and clauses or the error messages.
Date functions
- CURRENT_DATECURRENT_DATE() returns today's date as a DATE, in UTC unless you pass a time zone: CURRENT_DATE('America/New_York').
- DATEDATE builds a DATE from year, month and day numbers, or converts a TIMESTAMP or DATETIME to its calendar date.
- DATE_ADDDATE_ADD(date, INTERVAL n part) adds days, weeks, months, quarters or years to a DATE and returns a DATE.
- DATE_BUCKETDATE_BUCKET(date, INTERVAL n DAY) returns the first day of the fixed-width bucket that contains a date, counted from an origin (1950-01-01 by default).
- DATE_DIFFDATE_DIFF(end_date, start_date, DAY) returns the number of days between two dates as INT64.
- DATE_FROM_UNIX_DATEDATE_FROM_UNIX_DATE(n) converts a count of days since 1970-01-01 into a DATE: DATE_FROM_UNIX_DATE(20780) is 2026-11-23.
- DATE_SUBDATE_SUB(date, INTERVAL n part) subtracts days, weeks, months, quarters or years from a DATE.
- DATE_TRUNCDATE_TRUNC rounds a date down to the start of a period: DATE_TRUNC(order_date, MONTH) returns the first day of that month.
- EXTRACTEXTRACT(part FROM value) returns one part of a DATE, DATETIME, TIMESTAMP or TIME, such as YEAR, MONTH, DAYOFWEEK, ISOWEEK or HOUR, usually as INT64.
- FORMAT_DATEFORMAT_DATE(format_string, date) turns a DATE into a STRING using % elements: FORMAT_DATE('%d/%m/%Y', d) gives 23/11/2026 and FORMAT_DATE('%B %Y', d) gives November 2026.
- GENERATE_DATE_ARRAYGENERATE_DATE_ARRAY(start, end[, INTERVAL n part]) returns an ARRAY of dates from start to end, both included.
- LAST_DAYLAST_DAY(date) returns the last day of the month that contains a date, such as 2026-11-30 for 2026-11-23.
- PARSE_DATEPARSE_DATE(format_string, string) converts a STRING to a DATE using % elements, such as PARSE_DATE('%d/%m/%Y', '23/11/2026').
- UNIX_DATEUNIX_DATE(date) returns the number of days since 1970-01-01 as INT64: UNIX_DATE(DATE '2026-11-23') is 20780.
Datetime functions
- CURRENT_DATETIMECURRENT_DATETIME() returns the current date and time as a DATETIME, the wall-clock time in UTC or in the time zone you pass: CURRENT_DATETIME('Europe/Berlin').
- DATETIMEDATETIME builds a DATETIME from numbers, from a DATE and TIME, or converts a TIMESTAMP to local wall-clock time: DATETIME(ts, 'Europe/Berlin').
- DATETIME_ADDDATETIME_ADD(datetime, INTERVAL n part) adds microseconds up to years to a DATETIME and returns a DATETIME.
- DATETIME_DIFFDATETIME_DIFF(end, start, part) returns the number of part boundaries between two DATETIME values as INT64.
- DATETIME_SUBDATETIME_SUB(datetime, INTERVAL n part) subtracts microseconds up to years from a DATETIME and returns a DATETIME.
- DATETIME_TRUNCDATETIME_TRUNC(datetime, part) rounds a DATETIME down to the start of a period, such as the hour, day, week or month.
- FORMAT_DATETIMEFORMAT_DATETIME(format_string, datetime) turns a DATETIME into a STRING using % elements, for example FORMAT_DATETIME('%d/%m/%Y %H:%M', dt) gives 23/11/2026 18:45.
- PARSE_DATETIMEPARSE_DATETIME(format_string, string) converts a STRING to a DATETIME using % elements, such as PARSE_DATETIME('%d/%m/%Y %H:%M', '23/11/2026 18:45').
Timestamp functions
- CURRENT_TIMESTAMPCURRENT_TIMESTAMP() returns the current instant as a TIMESTAMP with microsecond precision, shown in UTC.
- FORMAT_TIMESTAMPFORMAT_TIMESTAMP(format_string, ts[, time_zone]) converts a TIMESTAMP to a STRING with % elements, in UTC or in the zone you pass: FORMAT_TIMESTAMP('%F %H:%M', ts, 'Europe/Berlin').
- PARSE_TIMESTAMPPARSE_TIMESTAMP(format_string, string[, time_zone]) converts a STRING to a TIMESTAMP using % elements.
- TIMESTAMPTIMESTAMP converts a STRING, DATE or DATETIME to a TIMESTAMP, reading it in UTC or in the time zone you pass: TIMESTAMP('2026-11-23 09:00:00', 'Europe/Berlin') is 08:00 UTC.
- TIMESTAMP_ADDTIMESTAMP_ADD(ts, INTERVAL n part) adds an exact duration to a TIMESTAMP, in MICROSECOND, MILLISECOND, SECOND, MINUTE, HOUR or DAY (24 hours).
- TIMESTAMP_DIFFTIMESTAMP_DIFF(end_ts, start_ts, part) returns the number of whole MICROSECOND, MILLISECOND, SECOND, MINUTE, HOUR or DAY units between two TIMESTAMPs as INT64, truncated toward zero.
- TIMESTAMP_MILLISTIMESTAMP_MILLIS(n) converts milliseconds since 1970-01-01 00:00:00 UTC to a TIMESTAMP.
- TIMESTAMP_SECONDSTIMESTAMP_SECONDS(n) converts Unix epoch seconds (seconds since 1970-01-01 00:00:00 UTC) to a TIMESTAMP: TIMESTAMP_SECONDS(1795392000) is 2026-11-23 00:00:00 UTC.
- TIMESTAMP_SUBTIMESTAMP_SUB(ts, INTERVAL n part) subtracts an exact duration (MICROSECOND up to DAY) from a TIMESTAMP.
- TIMESTAMP_TRUNCTIMESTAMP_TRUNC(ts, part[, time_zone]) rounds a TIMESTAMP down to the start of a minute, hour, day, week, month or year, in UTC or in the zone you pass.
- UNIX_MILLISUNIX_MILLIS(ts) returns the number of milliseconds since 1970-01-01 00:00:00 UTC as INT64, truncating microseconds.
- UNIX_SECONDSUNIX_SECONDS(ts) returns the number of seconds since 1970-01-01 00:00:00 UTC as INT64, dropping fractions of a second.
String functions
- CONCATCONCAT joins two or more values into one STRING (or BYTES): CONCAT(first_name, ' ', last_name).
- CONTAINS_SUBSTRCONTAINS_SUBSTR(expression, 'text') returns TRUE if the text appears anywhere in the value, ignoring case and Unicode differences.
- ENDS_WITHENDS_WITH(value, suffix) returns TRUE if a string ends with suffix: ENDS_WITH(file_name, '.parquet') finds Parquet files.
- FORMATFORMAT(pattern, values...) builds a string with printf-style specifiers: FORMAT('%.2f', 3.14159) returns 3.14, FORMAT("%'d", 1234567) returns 1,234,567 and FORMAT('%s has %d orders', name, n) fills in text.
- INITCAPINITCAP(value[, delimiters]) capitalizes the first letter of each word and lowercases the rest: INITCAP('mary-jane SMITH') returns Mary-Jane Smith.
- INSTRINSTR(value, subvalue[, position[, occurrence]]) returns the 1-based position of a substring, optionally starting at a given position or finding the nth match.
- LEFTLEFT(value, length) returns the first length characters of a string (or bytes of a BYTES value): LEFT('4111111111111111', 4) returns 4111.
- LENGTHLENGTH(value) returns the number of characters in a STRING, or the number of bytes in a BYTES value.
- LOWERLOWER(value) converts a string to lowercase using Unicode case rules: LOWER('Ana@Example.COM') returns ana@example.com.
- LPADLPAD(value, length[, pattern]) pads a string on the left to a fixed length: LPAD('42', 6, '0') returns 000042.
- LTRIMLTRIM(value[, characters]) removes leading whitespace, or every leading character found in the characters set: LTRIM('000123', '0') returns 123.
- REGEXP_CONTAINSREGEXP_CONTAINS(value, regex) returns TRUE if any part of the string matches an RE2 regular expression: REGEXP_CONTAINS(email, r'@example\.(com|org)$').
- REGEXP_EXTRACTREGEXP_EXTRACT(value, regex) returns the first substring that matches an RE2 regular expression, or the capture group if the pattern has one: REGEXP_EXTRACT(note, r'\d+') pulls the first number from text.
- REGEXP_EXTRACT_ALLREGEXP_EXTRACT_ALL(value, regex) returns an ARRAY of every non-overlapping match of an RE2 regular expression: REGEXP_EXTRACT_ALL(text, r'#(\w+)') returns all hashtags.
- REGEXP_REPLACEREGEXP_REPLACE(value, regex, replacement) replaces every match of an RE2 regular expression: REGEXP_REPLACE(phone, r'[^0-9]', '') keeps only digits.
- REPLACEREPLACE(value, from, to) replaces every occurrence of a substring: REPLACE(phone, ' ', '') removes all spaces.
- REVERSEREVERSE(value) returns a STRING with its characters in reverse order, or a BYTES value with its bytes reversed: REVERSE('stressed') returns desserts.
- RIGHTRIGHT(value, length) returns the last length characters of a string (or bytes of a BYTES value): RIGHT('4111111111111111', 4) returns 1111.
- RPADRPAD(value, length[, pattern]) pads a string on the right to a fixed length: RPAD('SKU', 8, '.') returns SKU.....
- RTRIMRTRIM(value[, characters]) removes trailing whitespace, or every trailing character found in the characters set: RTRIM('12.500', '0') returns 12.5.
- SOUNDEXSOUNDEX(value) returns a four-character phonetic code (a letter and three digits) for how a word sounds in English: SOUNDEX('Smith') and SOUNDEX('Smyth') both return S530.
- SPLITSPLIT breaks a string into an ARRAY<STRING> on a delimiter: SPLIT('a,b,c', ',') returns [a, b, c].
- STARTS_WITHSTARTS_WITH(value, prefix) returns TRUE if a string begins with prefix: STARTS_WITH(table_name, 'tmp_') is TRUE for tmp_orders.
- STRPOSSTRPOS(value, subvalue) returns the 1-based position of the first occurrence of subvalue, or 0 if it isn't found: STRPOS('ana@example.com', '@') returns 4.
- SUBSTRSUBSTR(value, position[, length]) returns part of a string: SUBSTR('INV-2026-00042', 5, 4) returns 2026.
- TRANSLATETRANSLATE(value, source_chars, target_chars) replaces each character in source_chars with the character at the same position in target_chars, and deletes source characters that have no counterpart: TRANSLATE(phone, '()- ', '') strips four characters in one call.
- TRIMTRIM(value[, characters]) removes leading and trailing whitespace from a string, or every leading and trailing character found in the characters set: TRIM('xxapplexx', 'x') returns apple.
- UPPERUPPER(value) converts a string to uppercase using Unicode case rules: UPPER('de-be') returns DE-BE.
Aggregate functions
- ANY_VALUEANY_VALUE returns the value of an expression from some row of the group, skipping NULLs.
- APPROX_COUNT_DISTINCTAPPROX_COUNT_DISTINCT estimates the number of distinct non-NULL values with a HyperLogLog++ sketch.
- APPROX_QUANTILESAPPROX_QUANTILES(x, n) returns an array of n + 1 approximate quantile boundaries, from the minimum to the maximum.
- APPROX_TOP_COUNTAPPROX_TOP_COUNT(x, n) returns the n most frequent values of x with their approximate counts, as an ARRAY of STRUCT<value, count>.
- ARRAY_AGGARRAY_AGG collects the values of a group into an ARRAY.
- AVGAVG returns the mean of the non-NULL values in a group.
- COUNTCOUNT counts rows: COUNT() counts every row, COUNT(column) skips NULLs, and COUNT(DISTINCT column) counts unique non-NULL values exactly.
- COUNTIFCOUNTIF counts the rows where a BOOL condition is TRUE, for example COUNTIF(status = 'failed').
- LOGICAL_ANDLOGICAL_AND returns TRUE if a BOOL expression is TRUE for every non-NULL row of a group and FALSE if any row is FALSE.
- LOGICAL_ORLOGICAL_OR returns TRUE if a BOOL expression is TRUE for at least one row of a group and FALSE if every non-NULL row is FALSE.
- MAXMAX returns the largest non-NULL value in a group: the latest timestamp, the highest amount, the alphabetically last string.
- MAX_BYMAX_BY(x, y) returns the value of x from the row where y is largest, such as the current status of each order: MAX_BY(status, updated_at).
- MINMIN returns the smallest non-NULL value in a group: the earliest date, the lowest price, the alphabetically first string.
- MIN_BYMIN_BY(x, y) returns the value of x from the row where y is smallest, such as each user's first marketing channel: MIN_BY(channel, visited_at).
- STRING_AGGSTRING_AGG concatenates the non-NULL strings of a group into one value, separated by a delimiter (a comma by default).
- SUMSUM adds up the non-NULL values in a group and returns NULL, not 0, when there is nothing to add.
Window functions
- DENSE_RANKDENSE_RANK() ranks rows within a window partition without gaps: tied rows share a rank and the next distinct value gets the next integer (1, 1, 2).
- FIRST_VALUEFIRST_VALUE(x) returns x from the first row of the current window frame, such as each session's landing page or a series' starting value.
- LAGLAG(value, offset, default) returns a value from an earlier row of the window partition, the previous row by default.
- LAST_VALUELAST_VALUE(x) returns x from the last row of the current window frame.
- LEADLEAD(value, offset, default) returns a value from a later row of the window partition, the next row by default.
- NTILENTILE(n) splits the ordered rows of each window partition into n buckets of nearly equal size and returns the bucket number, from 1 to n.
- PERCENT_RANKPERCENT_RANK() returns each row's relative rank in its window partition as a FLOAT64 from 0 to 1, computed as (rank - 1) / (rows - 1).
- PERCENTILE_CONTPERCENTILE_CONT(x, p) OVER (...) returns the exact p-th percentile of x with linear interpolation, such as the median with p = 0.5.
- PERCENTILE_DISCPERCENTILE_DISC(x, p) OVER (...) returns the first value of x whose cumulative distribution reaches p, so the answer is always a value from the data.
- RANKRANK() assigns 1-based ranks within a window partition; tied rows share a rank and the next rank skips ahead (1, 1, 3).
- ROW_NUMBERROW_NUMBER() numbers the rows of each window partition 1, 2, 3 in ORDER BY order, with no ties and no gaps.
Array functions
- ARRAYARRAY(subquery) collects the rows a subquery returns into an array, one element per row, and returns an empty array (never NULL) when there are no rows.
- ARRAY_CONCATARRAY_CONCAT(arr1, arr2, ...) joins two or more arrays of the same element type into one, keeping order and duplicates.
- ARRAY_FIRSTARRAY_FIRST(arr) returns the first element of an array, typed as the array's elements.
- ARRAY_LASTARRAY_LAST(arr) returns the last element of an array without the ARRAY_LENGTH(arr) - 1 arithmetic.
- ARRAY_LENGTHARRAY_LENGTH(arr) returns the number of elements in an array as INT64: 0 for an empty array and NULL for a NULL array.
- ARRAY_REVERSEARRAY_REVERSE(arr) returns the same array with its elements in the opposite order.
- ARRAY_SLICEARRAY_SLICE(arr, start_offset, end_offset) returns the elements between two zero-based offsets, both ends included.
- ARRAY_TO_STRINGARRAY_TO_STRING(arr, delimiter[, null_text]) joins the elements of a STRING or BYTES array into one string.
- GENERATE_ARRAYGENERATE_ARRAY(start, end[, step]) returns an array of numbers from start to end, both inclusive, stepping by 1 or by step.
- OFFSET and SAFE_OFFSETarr[OFFSET(n)] returns the array element at zero-based position n and fails if n is out of range; arr[SAFE_OFFSET(n)] returns NULL instead.
- UNNESTUNNEST turns an array into a table with one row per element.
JSON functions
- JSON_EXTRACTJSON_EXTRACT(json, json_path) returns the JSON at a path (an object, an array or a quoted string) as JSON-formatted text, or as JSON for JSON input.
- JSON_EXTRACT_ARRAYJSON_EXTRACT_ARRAY(json[, json_path]) converts a JSON array into a SQL ARRAY with one element per item, as JSON-formatted strings (or JSON values for JSON input), ready for UNNEST.
- JSON_EXTRACT_SCALARJSON_EXTRACT_SCALAR(json, json_path) returns a scalar JSON value (string, number or boolean) as a SQL STRING without quotes, and NULL for objects, arrays and JSON null.
- JSON_KEYSJSON_KEYS(json[, max_depth][, mode => ...]) returns the unique keys of a JSON value as a sorted ARRAY<STRING>, with nested keys as dotted paths such as user.id.
- JSON_QUERYJSON_QUERY(json, json_path) returns the JSON value at a path (object, array or scalar) as JSON text for STRING input or as JSON for JSON input, keeping quotes on strings.
- JSON_QUERY_ARRAYJSON_QUERY_ARRAY(json[, json_path]) turns a JSON array into a SQL ARRAY with one element per item: ARRAY<JSON> for JSON input, JSON-formatted strings for STRING input.
- JSON_REMOVEJSON_REMOVE(json, path[, path ...]) returns a copy of a JSON value with the data at each JSONPath removed, whether an object key or an array element.
- JSON_SETJSON_SET(json, path, value[, path, value ...]) returns a copy of a JSON value with values inserted or replaced at the given JSONPaths, creating missing parents along the way.
- JSON_TYPEJSON_TYPE(json) returns the type of a JSON value as a string: object, array, string, number, boolean or null.
- JSON_VALUEJSON_VALUE(json[, json_path]) extracts a scalar (string, number or boolean) from JSON and returns it as a SQL STRING without quotes; objects, arrays and JSON null return NULL.
- JSON_VALUE_ARRAYJSON_VALUE_ARRAY(json[, json_path]) extracts a JSON array of scalars as an ARRAY<STRING> with the quotes removed.
- PARSE_JSONPARSE_JSON(json_string) converts JSON-formatted text into a value of the JSON type, validating it on the way.
- TO_JSONTO_JSON(value) converts a SQL value (scalar, struct, array or whole row) into a value of the JSON type.
- TO_JSON_STRINGTO_JSON_STRING(value[, pretty_print]) serializes any SQL value, from a scalar to a struct, an array or a whole row, into JSON text.
Conversion functions
- CASTCAST(expression AS type) converts a value to another data type, such as STRING to INT64 or TIMESTAMP to DATE, and fails the whole query if any value can't be converted.
- PARSE_NUMERICPARSE_NUMERIC(string) converts a STRING to NUMERIC and, unlike CAST, accepts thousands separators, spaces and a trailing minus sign, as in '1,234.50' or '75.10-'.
- SAFE_CASTSAFE_CAST(expression AS type) works like CAST but returns NULL instead of failing when a value can't be converted.
Conditional expressions
- CASECASE returns the result of the first WHEN branch that matches.
- COALESCECOALESCE(expr1, expr2, ...) returns the first argument that is not NULL, or NULL if every argument is NULL.
- IFIF(condition, true_result, else_result) returns true_result when the condition is TRUE and else_result when it is FALSE or NULL.
- IFNULLIFNULL(expr, null_result) returns expr, or null_result when expr is NULL.
- NULLIFNULLIF(expr, expr_to_match) returns NULL when the two values are equal and expr otherwise.
Mathematical functions
- ABSABS(x) returns the absolute value of x with the same type as the input: ABS(-42) is 42.
- CEIL / CEILINGCEIL(x) returns the smallest whole number that is not less than x: CEIL(2.1) is 3.0 and CEIL(-2.9) is -2.0.
- DIVDIV(x, y) divides two integers and drops the remainder: DIV(7, 2) is 3, while 7 / 2 is 3.5.
- FLOORFLOOR(x) returns the largest whole number that is not greater than x: FLOOR(2.9) is 2.0 and FLOOR(-2.1) is -3.0.
- GREATESTGREATEST(x1, x2, ...) returns the largest of its arguments within a single row, for example the latest of several date columns.
- LEASTLEAST(x1, x2, ...) returns the smallest of its arguments within a single row, such as the earliest of several dates or a value capped at a limit.
- LOG, LN, LOG10LOG(x) returns the natural logarithm of x (the same as LN), LOG(x, base) uses any base, and LOG10(x) uses base 10.
- MODMOD(x, y) returns the remainder of x divided by y, with the sign of x: MOD(25, 7) is 4 and MOD(-25, 7) is -4.
- POW / POWERPOW(x, y) raises x to the power y, and POWER is a synonym: POW(2, 10) returns 1024.0.
- RANDRAND() returns a pseudo-random FLOAT64 from 0 (inclusive) to 1 (exclusive), different for every row and every run.
- RANGE_BUCKETRANGE_BUCKET(point, boundaries) returns the 0-based index of the bucket a value falls into, given a sorted array of boundaries: RANGE_BUCKET(25, [10, 20, 30]) is 2.
- ROUNDROUND(x, n) rounds x to n decimal places, with halfway cases going away from zero: ROUND(19.987, 2) returns 19.99.
- SAFE_DIVIDESAFE_DIVIDE(x, y) divides x by y like the / operator but returns NULL instead of failing when y is 0 or the division overflows.
- SQRTSQRT(x) returns the square root of x: SQRT(16) is 4.0.
- TRUNCTRUNC(x, n) cuts x to n decimal places by rounding toward zero: TRUNC(2.789, 2) is 2.78 and TRUNC(-2.789, 2) is -2.78.
Hash and utility functions
- ERRORERROR(message) stops the query with your own error message.
- FARM_FINGERPRINTFARM_FINGERPRINT(value) hashes a STRING or BYTES value to a signed INT64 that never changes between runs.
- GENERATE_UUIDGENERATE_UUID() returns a random version 4 UUID as a lowercase 36-character STRING, such as 3f2b8c1e-9d4a-4e7b-8c21-5a6f0d9e7b13.
- MD5MD5(input) returns the 16-byte MD5 hash of a STRING or BYTES value as BYTES, which the console shows in base64.
- SESSION_USERSESSION_USER() returns the email address of the user or service account running the query, or a principal identifier for third-party identities.
- SHA256SHA256(input) returns the 32-byte SHA-256 hash of a STRING or BYTES value as BYTES.
