BigQuery · DDL statement
BigQuery CREATE FUNCTION
CREATE FUNCTION defines a user-defined function (UDF) in SQL or JavaScript. CREATE TEMP FUNCTION lives for one query or script; CREATE FUNCTION dataset.name is persistent and shared. Prefer SQL UDFs: they are inlined, while JavaScript UDFs use more slots and lack 64-bit integers.
A SQL UDF wraps an expression: CREATE TEMP FUNCTION net(price NUMERIC, vat NUMERIC) AS (price / (1 + vat)). The RETURNS type is optional for SQL UDFs (BigQuery infers it) and parameters can be ANY TYPE to make the function work on several types. The body can be any expression, including a scalar subquery over a table. SQL UDFs are inlined into the query, so they cost no more than writing the expression out.
A JavaScript UDF runs code in a sandbox: RETURNS is required, the body is a string (use a raw triple-quoted string r"""...""" to avoid escaping), and OPTIONS (library = ['gs://...']) loads extra code from Cloud Storage. JavaScript has no 64-bit integer, so the docs list INT64 as unsupported for arguments: pass FLOAT64 (exact up to 2^53) or STRING. INT64 is supported as the return type. BYTES arrive base64-encoded, TIMESTAMP as a JavaScript Date. JavaScript UDFs consume more slots than SQL, can time out after as little as 5 minutes of CPU time, and can return about 5 MB per row; use them only for logic SQL can't express. Python UDFs (Preview) and remote functions use the same statement with LANGUAGE python or REMOTE WITH CONNECTION.
TEMP (or TEMPORARY) functions take a bare name and exist only in the current query, script, session or procedure. A request that consists only of CREATE TEMP FUNCTION statements followed by one SELECT is still treated as a single query. Persistent functions need a dataset (CREATE FUNCTION project.dataset.name), can be shared and authorized like views, and must be referenced with the dataset from views and other UDFs. Inside a persistent UDF body, unqualified tables resolve to the function's own project. Use CREATE OR REPLACE FUNCTION to change a persistent function and DROP FUNCTION to delete it.
Syntax
CREATE [OR REPLACE] [TEMP | TEMPORARY] FUNCTION [IF NOT EXISTS]
[[project.]dataset.]function_name ([param_name param_type[, ...]])
[RETURNS data_type]
AS (sql_expression)
[OPTIONS (description = '...')]
CREATE [OR REPLACE] [TEMP | TEMPORARY] FUNCTION [IF NOT EXISTS]
[[project.]dataset.]function_name ([param_name param_type[, ...]])
RETURNS data_type
[DETERMINISTIC | NOT DETERMINISTIC]
LANGUAGE js
[OPTIONS (library = ['gs://bucket/lib.js', ...])]
AS javascript_codeArguments and return value
| Argument | Description |
|---|---|
TEMP | TEMPORARY | Function exists only for the current query, script, session or procedure. Name without project or dataset; no description option. |
param_type | Any BigQuery type; ANY TYPE in SQL UDFs. For JavaScript UDFs the docs list INT64 as unsupported; use FLOAT64 or STRING. |
RETURNS data_type | Optional for SQL UDFs (inferred), required for JavaScript UDFs. Cannot be ANY TYPE. |
DETERMINISTIC / NOT DETERMINISTIC | JavaScript only: tells BigQuery whether results that use the function may be cached. |
OPTIONS | description for persistent functions; library (Cloud Storage paths) for JavaScript and Python UDFs. |
Returns: A temporary or persistent function that can be called in queries like a built-in function.
Examples
A temporary SQL UDF
CREATE TEMP FUNCTION net_price(gross NUMERIC, vat_rate NUMERIC)
RETURNS NUMERIC
AS (ROUND(gross / (1 + vat_rate), 2));
SELECT
order_id,
net_price(gross, 0.19) AS net
FROM UNNEST([
STRUCT('o1' AS order_id, NUMERIC '119.00' AS gross),
STRUCT('o2', NUMERIC '59.50')
])
ORDER BY order_id;| order_id | net |
|---|---|
| o1 | 100 |
| o2 | 50 |
ANY TYPE makes one UDF work for several types
CREATE TEMP FUNCTION last_element(arr ANY TYPE)
AS (arr[SAFE_ORDINAL(ARRAY_LENGTH(arr))]);
SELECT
last_element(['view', 'cart', 'purchase']) AS last_step,
last_element([3, 8, 13]) AS last_number,
last_element(ARRAY<INT64>[]) AS from_empty;| last_step | last_number | from_empty |
|---|---|---|
| purchase | 13 | NULL |
A JavaScript UDF for logic SQL can't express easily
The argument is a STRING because card numbers can exceed what a JavaScript number holds exactly. The raw string avoids escaping the regex.
CREATE TEMP FUNCTION luhn_valid(card_number STRING)
RETURNS BOOL
LANGUAGE js
AS r"""
if (card_number === null) return null;
const digits = card_number.replace(/\D/g, '');
let sum = 0;
for (let i = 0; i < digits.length; i++) {
let d = Number(digits[digits.length - 1 - i]);
if (i % 2 === 1) { d *= 2; if (d > 9) d -= 9; }
sum += d;
}
return digits.length > 0 && sum % 10 === 0;
""";
SELECT luhn_valid('4539 1488 0343 6467') AS valid, luhn_valid('4539 1488 0343 6468') AS invalid;| valid | invalid |
|---|---|
| true | false |
A persistent, documented function shared by a team
The fiscal year starts on February 1 and is named after the calendar year in which it ends, so 2026-11-23 is in FY2027-Q4.
CREATE OR REPLACE FUNCTION `project.udfs.fiscal_quarter`(d DATE)
RETURNS STRING
OPTIONS (description = 'Fiscal year starts on February 1')
AS (
FORMAT('FY%d-Q%d',
EXTRACT(YEAR FROM DATE_ADD(d, INTERVAL 11 MONTH)),
DIV(EXTRACT(MONTH FROM DATE_ADD(d, INTERVAL 11 MONTH)) - 1, 3) + 1)
);Common mistakes
- Passing large INT64 values to a JavaScript UDF. JavaScript numbers are 64-bit floats, exact only up to 2^53, and the docs list INT64 as an unsupported argument type; pass IDs as STRING and other integers as FLOAT64.
- Qualifying a temporary function or leaving the dataset off a persistent one.
CREATE TEMP FUNCTION ds.fis invalid, andCREATE FUNCTION fwithout a dataset needs a default dataset. - Calling a temporary UDF from a view or a persistent UDF. They can only reference persistent functions, qualified with the dataset.
- Writing JavaScript for something SQL can do, such as string cleanup or JSON extraction. The JS sandbox costs more slots and has timeouts and memory limits that SQL functions don't.
Cost and performance
- SQL UDFs are expanded inline and cost the same as the expression they contain. JavaScript UDFs run row by row in a sandbox, use noticeably more slot time, and can fail on large inputs; filter rows before calling them.
- A UDF whose body contains a subquery over a table reads that table for the query that calls it, billed like any other scan.
FAQ
What is the difference between TEMP FUNCTION and a persistent function in BigQuery?
A TEMP function exists only during one query, script or session and has no dataset. A persistent function lives in a dataset, can be shared and used from views, and stays until you drop it.
Can I use INT64 in a JavaScript UDF?
As a return type, yes. As an argument the docs list it as unsupported, because JavaScript numbers are 64-bit floats and lose precision above 2^53. Pass FLOAT64 or STRING.
Can a BigQuery UDF query a table?
Yes, a SQL UDF can return a scalar subquery such as (SELECT COUNT(*) FROM dataset.t WHERE ...). For functions that return rows, use a table function (CREATE TABLE FUNCTION).
Related
Errors you may hit
More DDL statements
All BigQuery DDL statements · All statements and clauses · BigQuery error messages
