You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
-- Syntax
function() OVER (
PARTITION BY col1
ORDER BY col2
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
)
Function
Description
ROW_NUMBER()
Sequential row number
RANK()
Rank with gaps
DENSE_RANK()
Rank without gaps
NTILE(n)
Distribute into n buckets
LAG(col, n)
Previous row value
LEAD(col, n)
Next row value
FIRST_VALUE(col)
First in window
LAST_VALUE(col)
Last in window
SUM(col) OVER (...)
Running sum
-- Example: Running totalSELECTdate,
amount,
SUM(amount) OVER (ORDER BYdate) as running_total
FROM sales;
-- Example: Rank within partitionSELECT
department,
employee,
salary,
RANK() OVER (PARTITION BY department ORDER BY salary DESC) as rank
FROM employees;
Array Functions
Function
Description
Example
ARRAY(e1, e2, ...)
Create array
ARRAY(1, 2, 3)
SIZE(arr)
Array length
SIZE(ARRAY(1,2,3)) → 3
EXPLODE(arr)
Array to rows
SELECT EXPLODE(arr)
ARRAY_CONTAINS(arr, v)
Check contains
ARRAY_CONTAINS(arr, 5)
ARRAY_DISTINCT(arr)
Remove duplicates
ARRAY_DISTINCT(arr)
ARRAY_UNION(a1, a2)
Merge arrays
ARRAY_UNION(a1, a2)
ARRAY_INTERSECT(a1, a2)
Common elements
ARRAY_INTERSECT(a1, a2)
FLATTEN(arr)
Flatten nested
FLATTEN(nested_arr)
TRANSFORM(arr, x -> expr)
Transform elements
TRANSFORM(arr, x -> x * 2)
FILTER(arr, x -> cond)
Filter elements
FILTER(arr, x -> x > 0)
JSON Functions
Function
Description
Example
GET_JSON_OBJECT(json, path)
Extract by path
GET_JSON_OBJECT(j, '$.name')
JSON_TUPLE(json, k1, k2)
Multiple keys
JSON_TUPLE(j, 'a', 'b')
FROM_JSON(json, schema)
Parse to struct
FROM_JSON(j, 'a INT, b STRING')
TO_JSON(struct)
Struct to JSON
TO_JSON(named_struct(...))
SCHEMA_OF_JSON(json)
Infer schema
SCHEMA_OF_JSON('[{"a":1}]')
-- Parse JSON columnSELECT FROM_JSON(json_col, 'struct<name:string, age:int>') as parsed
FROM table;
-- Access nested JSONSELECT json_col:name, json_col:address:city
FROM table;
Conditional Functions
Function
Description
Example
CASE WHEN ... THEN ... END
Conditional
See below
IF(cond, true_val, false_val)
Inline if
IF(x > 0, 'pos', 'neg')
COALESCE(v1, v2, ...)
First non-null
COALESCE(col, 'default')
NULLIF(v1, v2)
Null if equal
NULLIF(x, 0)
NVL(v1, v2)
Replace null
NVL(col, 0)
NVL2(v, not_null, is_null)
Null branch
NVL2(col, 'yes', 'no')
-- CASE expressionSELECT
CASE
WHEN amount <100 THEN 'small'
WHEN amount <1000 THEN 'medium'
ELSE 'large'
END as size_category
FROM orders;
Type Conversion
Function
Description
CAST(v AS type)
Type conversion
v::type
Shorthand cast
TRY_CAST(v AS type)
Cast or null
CAST('123'ASINT)
CAST(date_col AS STRING)
'123'::INT
TRY_CAST('abc'ASINT) -- Returns NULL