DatumHuePlatform v0.0.24datumhue.com
Contents

SQL

SQL functions

A DatumHue app runs SQL through DataHandle:query. The query is lazy — it plans and runs on first read, then caches.

Querying

The query is rooted on the handle it's called on, bound as the table data:

lua
local top = sales:query("SELECT region, SUM(amount) AS total FROM data GROUP BY region")

Pass values for ? placeholders as a second array argument; each ? binds left to right:

lua
local big = sales:query("SELECT * FROM data WHERE amount > ?", { 1000 })

A Dir or File handle in the params binds the next ? to a location inside its grant, so a query can read a granted file directly. Only granted locations are reachable — there is no path to the wider filesystem:

lua
local rows = data_handle:query("SELECT * FROM ? WHERE ok", { my_file })

Write results into a granted location with COPY ... TO ?:

lua
data_handle:query("COPY data TO ? STORED AS PARQUET", { out_dir })

Queries never modify your source data. The only writes are into a location you've granted for writing — COPY ... TO ?, or a table you create over a granted directory. They run under a memory budget (2 GiB natively, 1 GiB in the browser) and spill to disk where one is available.

Functions 232

The functions a query can call, by group.

Analytical Functions 5

first_value

window
first_value(expression)

Returns value evaluated at the row that is the first row of the window frame.

expression

Expression to operate on

Example
-- Example usage of the first_value window function:
SELECT department,
  employee_id,
  salary,
  first_value(salary) OVER (PARTITION BY department ORDER BY salary DESC) AS top_salary
FROM employees;

+-------------+-------------+--------+------------+
| department  | employee_id | salary | top_salary |
+-------------+-------------+--------+------------+
| Sales       | 1           | 70000  | 70000      |
| Sales       | 2           | 50000  | 70000      |
| Sales       | 3           | 30000  | 70000      |
| Engineering | 4           | 90000  | 90000      |
| Engineering | 5           | 80000  | 90000      |
+-------------+-------------+--------+------------+

lag

window
lag(expression, offset, default)

Returns value evaluated at the row that is offset rows before the current row within the partition; if there is no such row, instead return default (which must be of the same type as value).

expression

Expression to operate on

offset

Integer. Specifies how many rows back the value of expression should be retrieved. Defaults to 1.

default

The default value if the offset is not within the partition. Must be of the same type as expression.

Example
-- Example usage of the lag window function:
SELECT employee_id,
    salary,
    lag(salary, 1, 0) OVER (ORDER BY employee_id) AS prev_salary
FROM employees;

+-------------+--------+-------------+
| employee_id | salary | prev_salary |
+-------------+--------+-------------+
| 1           | 30000  | 0           |
| 2           | 50000  | 30000       |
| 3           | 70000  | 50000       |
| 4           | 60000  | 70000       |
+-------------+--------+-------------+

last_value

window
last_value(expression)

Returns value evaluated at the row that is the last row of the window frame.

expression

Expression to operate on

Example
-- SQL example of last_value:
SELECT department,
       employee_id,
       salary,
       last_value(salary) OVER (PARTITION BY department ORDER BY salary) AS running_last_salary
FROM employees;

+-------------+-------------+--------+---------------------+
| department  | employee_id | salary | running_last_salary |
+-------------+-------------+--------+---------------------+
| Sales       | 1           | 30000  | 30000               |
| Sales       | 2           | 50000  | 50000               |
| Sales       | 3           | 70000  | 70000               |
| Engineering | 4           | 40000  | 40000               |
| Engineering | 5           | 60000  | 60000               |
+-------------+-------------+--------+---------------------+

lead

window
lead(expression, offset, default)

Returns value evaluated at the row that is offset rows after the current row within the partition; if there is no such row, instead return default (which must be of the same type as value).

expression

Expression to operate on

offset

Integer. Specifies how many rows forward the value of expression should be retrieved. Defaults to 1.

default

The default value if the offset is not within the partition. Must be of the same type as expression.

Example
-- Example usage of lead window function:
SELECT
    employee_id,
    department,
    salary,
    lead(salary, 1, 0) OVER (PARTITION BY department ORDER BY salary) AS next_salary
FROM employees;

+-------------+-------------+--------+--------------+
| employee_id | department  | salary | next_salary  |
+-------------+-------------+--------+--------------+
| 1           | Sales       | 30000  | 50000        |
| 2           | Sales       | 50000  | 70000        |
| 3           | Sales       | 70000  | 0            |
| 4           | Engineering | 40000  | 60000        |
| 5           | Engineering | 60000  | 0            |
+-------------+-------------+--------+--------------+

nth_value

window
nth_value(expression, n)

Returns the value evaluated at the nth row of the window frame (counting from 1). Returns NULL if no such row exists.

expression

The column from which to retrieve the nth value.

n

Integer. Specifies the row number (starting from 1) in the window frame.

Example
-- Sample employees table:
CREATE TABLE employees (id INT, salary INT);
INSERT INTO employees (id, salary) VALUES
(1, 30000),
(2, 40000),
(3, 50000),
(4, 60000),
(5, 70000);

-- Example usage of nth_value:
SELECT nth_value(salary, 2) OVER (
  ORDER BY salary
  ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS nth_value
FROM employees;

+-----------+
| nth_value |
+-----------+
| 40000     |
| 40000     |
| 40000     |
| 40000     |
| 40000     |
+-----------+

Approximate Functions 4

approx_distinct

aggregate
approx_distinct(expression)

Returns the approximate number of distinct input values calculated using the HyperLogLog algorithm.

expression

The expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT approx_distinct(column_name) FROM table_name;
+-----------------------------------+
| approx_distinct(column_name)      |
+-----------------------------------+
| 42                                |
+-----------------------------------+

approx_median

aggregate
approx_median(expression)

Returns the approximate median (50th percentile) of input values. It is an alias of approx_percentile_cont(0.5) WITHIN GROUP (ORDER BY x).

expression

The expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT approx_median(column_name) FROM table_name;
+-----------------------------------+
| approx_median(column_name)        |
+-----------------------------------+
| 23.5                              |
+-----------------------------------+

approx_percentile_cont

aggregate
approx_percentile_cont(percentile [, centroids]) WITHIN GROUP (ORDER BY expression)

Returns the approximate percentile of input values using the t-digest algorithm.

expression

The expression to operate on. Can be a constant, column, or function, and any combination of operators.

percentile

Percentile to compute. Must be a float value between 0 and 1 (inclusive).

centroids

Number of centroids to use in the t-digest algorithm. Default is 100. A higher number results in more accurate approximation but requires more memory.

Example
> SELECT approx_percentile_cont(0.75) WITHIN GROUP (ORDER BY column_name) FROM table_name;
+------------------------------------------------------------------+
| approx_percentile_cont(0.75) WITHIN GROUP (ORDER BY column_name) |
+------------------------------------------------------------------+
| 65.0                                                             |
+------------------------------------------------------------------+
> SELECT approx_percentile_cont(0.75, 100) WITHIN GROUP (ORDER BY column_name) FROM table_name;
+-----------------------------------------------------------------------+
| approx_percentile_cont(0.75, 100) WITHIN GROUP (ORDER BY column_name) |
+-----------------------------------------------------------------------+
| 65.0                                                                  |
+-----------------------------------------------------------------------+

> SELECT approx_percentile_cont(column_name, 0.75) FROM table_name;
+-----------------------------------------------+
| approx_percentile_cont(column_name, 0.75)     |
+-----------------------------------------------+
| 65.0                                          |
+-----------------------------------------------+

> SELECT approx_percentile_cont(column_name, 0.75, 100) FROM table_name;
+----------------------------------------------------------+
| approx_percentile_cont(column_name, 0.75, 100)           |
+----------------------------------------------------------+
| 65.0                                                     |
+----------------------------------------------------------+

approx_percentile_cont_with_weight

aggregate
approx_percentile_cont_with_weight(weight, percentile [, centroids]) WITHIN GROUP (ORDER BY expression)

Returns the weighted approximate percentile of input values using the t-digest algorithm.

expression

The expression to operate on. Can be a constant, column, or function, and any combination of operators.

weight

Expression to use as weight. Can be a constant, column, or function, and any combination of arithmetic operators.

percentile

Percentile to compute. Must be a float value between 0 and 1 (inclusive).

centroids

Number of centroids to use in the t-digest algorithm. Default is 100. A higher number results in more accurate approximation but requires more memory.

Example
> SELECT approx_percentile_cont_with_weight(weight_column, 0.90) WITHIN GROUP (ORDER BY column_name) FROM table_name;
+---------------------------------------------------------------------------------------------+
| approx_percentile_cont_with_weight(weight_column, 0.90) WITHIN GROUP (ORDER BY column_name) |
+---------------------------------------------------------------------------------------------+
| 78.5                                                                                        |
+---------------------------------------------------------------------------------------------+
> SELECT approx_percentile_cont_with_weight(weight_column, 0.90, 100) WITHIN GROUP (ORDER BY column_name) FROM table_name;
+--------------------------------------------------------------------------------------------------+
| approx_percentile_cont_with_weight(weight_column, 0.90, 100) WITHIN GROUP (ORDER BY column_name) |
+--------------------------------------------------------------------------------------------------+
| 78.5                                                                                             |
+--------------------------------------------------------------------------------------------------+

> SELECT approx_percentile_cont_with_weight(column_name, weight_column, 0.90) FROM table_name;
+--------------------------------------------------+
| approx_percentile_cont_with_weight(column_name, weight_column, 0.90) |
+--------------------------------------------------+
| 78.5                                             |
+--------------------------------------------------+

Array Functions 52

array_add

scalar
array_add(array1, array2)

Returns the element-wise sum of two numeric arrays of equal length, computed as array1[i] + array2[i] per position. NULL is propagated per element: if either input element at position i is NULL, the corresponding output element is NULL (positions are preserved). Returns NULL if either entire input array is NULL. Errors if the per-row lengths differ. Returns an empty array if both inputs are empty.

array1

Array expression. Can be a constant, column, or function, and any combination of array operators.

array2

Array expression. Can be a constant, column, or function, and any combination of array operators.

Example
> select array_add([1.0, 2.0, 3.0], [10.0, 20.0, 30.0]);
+---------------------------------------------------------+
| array_add(List([1.0,2.0,3.0]),List([10.0,20.0,30.0]))   |
+---------------------------------------------------------+
| [11.0, 22.0, 33.0]                                      |
+---------------------------------------------------------+

Also called list_add.

array_any_value

scalar
array_any_value(array)

Returns the first non-null element in the array. Returns NULL if the array is empty or NULL.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

Example
> select array_any_value([NULL, 1, 2, 3]);
+-------------------------------+
| array_any_value(List([NULL,1,2,3])) |
+-------------------------------------+
| 1                                   |
+-------------------------------------+

Also called list_any_value.

array_append

scalar
array_append(array, element)

Appends an element to the end of an array.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

element

Element to append to the array.

Example
> select array_append([1, 2, 3], 4);
+--------------------------------------+
| array_append(List([1,2,3]),Int64(4)) |
+--------------------------------------+
| [1, 2, 3, 4]                         |
+--------------------------------------+

Also called list_append, array_push_back, list_push_back.

array_avg

scalar
array_avg(array)

Returns the arithmetic mean (sum divided by count) of the elements of the input array. NULL elements are skipped (per SQL aggregate convention) and excluded from the count. Returns NULL if the input row is NULL, every element is NULL, or the array is empty.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

Example
> select array_avg([1.0, 2.0, 3.0]);
+----------------------------+
| array_avg(List([1.0,2.0,3.0])) |
+----------------------------+
| 2.0                        |
+----------------------------+

Also called list_avg.

array_compact

scalar
array_compact(array)

Removes null values from the array.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

Example
> select array_compact([1, NULL, 2, NULL, 3]) arr;
+-----------+
| arr       |
+-----------+
| [1, 2, 3] |
+-----------+

Also called list_compact.

array_concat

scalar
array_concat(array[, ..., array_n])

Concatenates arrays.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

array_n

Subsequent array column or literal array to concatenate.

Example
> select array_concat([1, 2], [3, 4], [5, 6]);
+---------------------------------------------------+
| array_concat(List([1,2]),List([3,4]),List([5,6])) |
+---------------------------------------------------+
| [1, 2, 3, 4, 5, 6]                                |
+---------------------------------------------------+

Also called array_cat, list_concat, list_cat.

array_dims

scalar
array_dims(array)

Returns an array of the array's dimensions.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

Example
> select array_dims([[1, 2, 3], [4, 5, 6]]);
+---------------------------------+
| array_dims(List([1,2,3,4,5,6])) |
+---------------------------------+
| [2, 3]                          |
+---------------------------------+

Also called list_dims.

array_distance

scalar
array_distance(array1, array2)

Returns the Euclidean distance between two one-dimensional input arrays of equal length.

array1

Array expression. Can be a constant, column, or function, and any combination of array operators.

array2

Array expression. Can be a constant, column, or function, and any combination of array operators.

Example
> select array_distance([1, 2], [1, 4]);
+------------------------------------+
| array_distance(List([1,2], [1,4])) |
+------------------------------------+
| 2.0                                |
+------------------------------------+

Also called list_distance.

array_distinct

scalar
array_distinct(array)

Returns distinct values from the array after removing duplicates.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

Example
> select array_distinct([1, 3, 2, 3, 1, 2, 4]);
+---------------------------------+
| array_distinct(List([1,2,3,4])) |
+---------------------------------+
| [1, 2, 3, 4]                    |
+---------------------------------+

Also called list_distinct.

array_element

scalar
array_element(array, index)

Extracts the element with the index n from the array.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

index

Index to extract the element from the array.

Example
> select array_element([1, 2, 3, 4], 3);
+-----------------------------------------+
| array_element(List([1,2,3,4]),Int64(3)) |
+-----------------------------------------+
| 3                                       |
+-----------------------------------------+

Also called array_extract, list_element, list_extract.

array_except

scalar
array_except(array1, array2)

Returns an array of the elements that appear in the first array but not in the second.

array1

Array expression. Can be a constant, column, or function, and any combination of array operators.

array2

Array expression. Can be a constant, column, or function, and any combination of array operators.

Example
> select array_except([1, 2, 3, 4], [5, 6, 3, 4]);
+----------------------------------------------------+
| array_except([1, 2, 3, 4], [5, 6, 3, 4]);           |
+----------------------------------------------------+
| [1, 2]                                              |
+----------------------------------------------------+
> select array_except([1, 2, 3, 4], [3, 4, 5, 6]);
+----------------------------------------------------+
| array_except([1, 2, 3, 4], [3, 4, 5, 6]);           |
+----------------------------------------------------+
| [1, 2]                                              |
+----------------------------------------------------+

Also called list_except.

array_has

scalar
array_has(array, element)

Returns true if the array contains the element.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

element

Scalar or Array expression. Can be a constant, column, or function, and any combination of array operators.

Example
> select array_has([1, 2, 3], 2);
+-----------------------------+
| array_has(List([1,2,3]), 2) |
+-----------------------------+
| true                        |
+-----------------------------+

Also called list_has, array_contains, list_contains.

array_has_all

scalar
array_has_all(array, sub_array)

Returns true if all elements of sub_array exist in array.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

sub_array

Array expression. Can be a constant, column, or function, and any combination of array operators.

Example
> select array_has_all([1, 2, 3, 4], [2, 3]);
+---------------------------------------------+
| array_has_all(List([1,2,3,4]), List([2,3])) |
+---------------------------------------------+
| true                                        |
+---------------------------------------------+

Also called list_has_all.

array_has_any

scalar
array_has_any(array1, array2)

Returns true if the arrays have any elements in common.

array1

Array expression. Can be a constant, column, or function, and any combination of array operators.

array2

Array expression. Can be a constant, column, or function, and any combination of array operators.

Example
> select array_has_any([1, 2, 3], [3, 4]);
+------------------------------------------+
| array_has_any(List([1,2,3]), List([3,4])) |
+------------------------------------------+
| true                                     |
+------------------------------------------+

Also called list_has_any, arrays_overlap.

array_intersect

scalar
array_intersect(array1, array2)

Returns an array of elements in the intersection of array1 and array2.

array1

Array expression. Can be a constant, column, or function, and any combination of array operators.

array2

Array expression. Can be a constant, column, or function, and any combination of array operators.

Example
> select array_intersect([1, 2, 3, 4], [5, 6, 3, 4]);
+----------------------------------------------------+
| array_intersect([1, 2, 3, 4], [5, 6, 3, 4]);       |
+----------------------------------------------------+
| [3, 4]                                             |
+----------------------------------------------------+
> select array_intersect([1, 2, 3, 4], [5, 6, 7, 8]);
+----------------------------------------------------+
| array_intersect([1, 2, 3, 4], [5, 6, 7, 8]);       |
+----------------------------------------------------+
| []                                                 |
+----------------------------------------------------+

Also called list_intersect.

array_length

scalar
array_length(array[, dimension])

Returns the length of the array dimension.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

dimension

Array dimension. Default is 1

Example
> select array_length([1, 2, 3, 4, 5], 1);
+-------------------------------------------+
| array_length(List([1,2,3,4,5]), 1)        |
+-------------------------------------------+
| 5                                         |
+-------------------------------------------+

Also called list_length.

array_max

scalar
array_max(array)

Returns the maximum value in the array.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

Example
> select array_max([3,1,4,2]);
+-----------------------------------------+
| array_max(List([3,1,4,2]))              |
+-----------------------------------------+
| 4                                       |
+-----------------------------------------+

Also called list_max.

array_min

scalar
array_min(array)

Returns the minimum value in the array.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

Example
> select array_min([3,1,4,2]);
+-----------------------------------------+
| array_min(List([3,1,4,2]))              |
+-----------------------------------------+
| 1                                       |
+-----------------------------------------+

array_ndims

scalar
array_ndims(array)

Returns the number of dimensions of the array.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

Example
> select array_ndims([[1, 2, 3], [4, 5, 6]]);
+----------------------------------+
| array_ndims(List([1,2,3,4,5,6])) |
+----------------------------------+
| 2                                |
+----------------------------------+

Also called list_ndims.

array_normalize

scalar
array_normalize(array)

Returns the L2-normalized vector for the input numeric array, computed as array[i] / sqrt(sum(array[i]^2)) per element. Returns NULL if the input is NULL, contains NULL elements, or has zero magnitude (all elements are zero). Returns an empty array for an empty input array.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

Example
> select array_normalize([3.0, 4.0]);
+-----------------------------+
| array_normalize(List([3.0,4.0])) |
+-----------------------------+
| [0.6, 0.8]                  |
+-----------------------------+

Also called list_normalize.

array_pop_back

scalar
array_pop_back(array)

Returns the array without the last element.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

Example
> select array_pop_back([1, 2, 3]);
+-------------------------------+
| array_pop_back(List([1,2,3])) |
+-------------------------------+
| [1, 2]                        |
+-------------------------------+

Also called list_pop_back.

array_pop_front

scalar
array_pop_front(array)

Returns the array without the first element.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

Example
> select array_pop_front([1, 2, 3]);
+-------------------------------+
| array_pop_front(List([1,2,3])) |
+-------------------------------+
| [2, 3]                        |
+-------------------------------+

Also called list_pop_front.

array_position

scalar
array_position(array, element[, index])

Returns the position of the first occurrence of the specified element in the array, or NULL if not found. Comparisons are done using IS DISTINCT FROM semantics, so NULL is considered to match NULL.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

element

Element to search for in the array.

index

Index at which to start searching (1-indexed). Defaults to searching from the start

Example
> select array_position([1, 2, 2, 3, 1, 4], 2);
+----------------------------------------------+
| array_position(List([1,2,2,3,1,4]),Int64(2)) |
+----------------------------------------------+
| 2                                            |
+----------------------------------------------+
> select array_position([1, 2, 2, 3, 1, 4], 2, 3);
+----------------------------------------------------+
| array_position(List([1,2,2,3,1,4]),Int64(2), Int64(3)) |
+----------------------------------------------------+
| 3                                                  |
+----------------------------------------------------+

Also called list_position, array_indexof, list_indexof.

array_positions

scalar
array_positions(array, element)

Searches for an element in the array, returns all occurrences.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

element

Element to search for in the array.

Example
> select array_positions([1, 2, 2, 3, 1, 4], 2);
+-----------------------------------------------+
| array_positions(List([1,2,2,3,1,4]),Int64(2)) |
+-----------------------------------------------+
| [2, 3]                                        |
+-----------------------------------------------+

Also called list_positions.

array_prepend

scalar
array_prepend(element, array)

Prepends an element to the beginning of an array.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

element

Element to prepend to the array.

Example
> select array_prepend(1, [2, 3, 4]);
+---------------------------------------+
| array_prepend(Int64(1),List([2,3,4])) |
+---------------------------------------+
| [1, 2, 3, 4]                          |
+---------------------------------------+

Also called list_prepend, array_push_front, list_push_front.

array_product

scalar
array_product(array)

Returns the product of the elements in the input numeric array. NULL elements inside the array are skipped (matching SQL aggregate convention). Returns NULL if the input is NULL, every element is NULL, or the array is empty. The result is always returned as Float64.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

Example
> select array_product([1.0, 2.0, 3.0]);
+------------------------------------+
| array_product(List([1.0,2.0,3.0])) |
+------------------------------------+
| 6.0                                |
+------------------------------------+

Also called list_product.

array_remove

scalar
array_remove(array, element)

Removes the first element from the array equal to the given value. NULL elements already in the array are preserved when removing a non-NULL value. If element evaluates to NULL, the result is NULL rather than removing NULL entries.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

element

Element to be removed from the array.

Example
> select array_remove([1, 2, 2, 3, 2, 1, 4], 2);
+----------------------------------------------+
| array_remove(List([1,2,2,3,2,1,4]),Int64(2)) |
+----------------------------------------------+
| [1, 2, 3, 2, 1, 4]                           |
+----------------------------------------------+

> select array_remove([1, 2, NULL, 2, 4], 2);
+---------------------------------------------------+
| array_remove(List([1,2,NULL,2,4]),Int64(2)) |
+---------------------------------------------------+
| [1, NULL, 2, 4]                              |
+---------------------------------------------------+

Also called list_remove.

array_remove_all

scalar
array_remove_all(array, element)

Removes all elements from the array equal to the given value. NULL elements already in the array are preserved when removing a non-NULL value. If element evaluates to NULL, the result is NULL rather than removing NULL entries.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

element

Element to be removed from the array.

Example
> select array_remove_all([1, 2, 2, 3, 2, 1, 4], 2);
+--------------------------------------------------+
| array_remove_all(List([1,2,2,3,2,1,4]),Int64(2)) |
+--------------------------------------------------+
| [1, 3, 1, 4]                                     |
+--------------------------------------------------+

> select array_remove_all([1, 2, NULL, 2, 4], 2);
+-----------------------------------------------------+
| array_remove_all(List([1,2,NULL,2,4]),Int64(2)) |
+-----------------------------------------------------+
| [1, NULL, 4]                                     |
+-----------------------------------------------------+

Also called list_remove_all.

array_remove_n

scalar
array_remove_n(array, element, max)

Removes the first max elements from the array equal to the given value. NULL elements already in the array are preserved when removing a non-NULL value. If element evaluates to NULL, the result is NULL rather than removing NULL entries.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

element

Element to be removed from the array.

max

Number of first occurrences to remove.

Example
> select array_remove_n([1, 2, 2, 3, 2, 1, 4], 2, 2);
+---------------------------------------------------------+
| array_remove_n(List([1,2,2,3,2,1,4]),Int64(2),Int64(2)) |
+---------------------------------------------------------+
| [1, 3, 2, 1, 4]                                         |
+---------------------------------------------------------+

> select array_remove_n([1, 2, NULL, 2, 4], 2, 2);
+----------------------------------------------------------+
| array_remove_n(List([1,2,NULL,2,4]),Int64(2),Int64(2)) |
+----------------------------------------------------------+
| [1, NULL, 4]                                            |
+----------------------------------------------------------+

Also called list_remove_n.

array_repeat

scalar
array_repeat(element, count)

Returns an array containing element count times.

element

Element expression. Can be a constant, column, or function, and any combination of array operators.

count

Value of how many times to repeat the element.

Example
> select array_repeat(1, 3);
+---------------------------------+
| array_repeat(Int64(1),Int64(3)) |
+---------------------------------+
| [1, 1, 1]                       |
+---------------------------------+
> select array_repeat([1, 2], 2);
+------------------------------------+
| array_repeat(List([1,2]),Int64(2)) |
+------------------------------------+
| [[1, 2], [1, 2]]                   |
+------------------------------------+

Also called list_repeat.

array_replace

scalar
array_replace(array, from, to)

Replaces the first occurrence of the specified element with another specified element.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

from

Initial element.

to

Final element.

Example
> select array_replace([1, 2, 2, 3, 2, 1, 4], 2, 5);
+--------------------------------------------------------+
| array_replace(List([1,2,2,3,2,1,4]),Int64(2),Int64(5)) |
+--------------------------------------------------------+
| [1, 5, 2, 3, 2, 1, 4]                                  |
+--------------------------------------------------------+

Also called list_replace.

array_replace_all

scalar
array_replace_all(array, from, to)

Replaces all occurrences of the specified element with another specified element.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

from

Initial element.

to

Final element.

Example
> select array_replace_all([1, 2, 2, 3, 2, 1, 4], 2, 5);
+------------------------------------------------------------+
| array_replace_all(List([1,2,2,3,2,1,4]),Int64(2),Int64(5)) |
+------------------------------------------------------------+
| [1, 5, 5, 3, 5, 1, 4]                                      |
+------------------------------------------------------------+

Also called list_replace_all.

array_replace_n

scalar
array_replace_n(array, from, to, max)

Replaces the first max occurrences of the specified element with another specified element.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

from

Initial element.

to

Final element.

max

Number of first occurrences to replace.

Example
> select array_replace_n([1, 2, 2, 3, 2, 1, 4], 2, 5, 2);
+-------------------------------------------------------------------+
| array_replace_n(List([1,2,2,3,2,1,4]),Int64(2),Int64(5),Int64(2)) |
+-------------------------------------------------------------------+
| [1, 5, 5, 3, 2, 1, 4]                                             |
+-------------------------------------------------------------------+

Also called list_replace_n.

array_resize

scalar
array_resize(array, size[, value])

Resizes the list to contain size elements.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

size

New size of given array.

value

If expanding the array, defines the values to fill in. Defaults to null.

Example
> select array_resize([1, 2, 3], 5, 0);
+-------------------------------------+
| array_resize(List([1,2,3],5,0))     |
+-------------------------------------+
| [1, 2, 3, 0, 0]                     |
+-------------------------------------+

Also called list_resize.

array_reverse

scalar
array_reverse(array)

Returns the array with the order of the elements reversed.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

Example
> select array_reverse([1, 2, 3, 4]);
+------------------------------------------------------------+
| array_reverse(List([1, 2, 3, 4]))                          |
+------------------------------------------------------------+
| [4, 3, 2, 1]                                               |
+------------------------------------------------------------+

Also called list_reverse.

array_scale

scalar
array_scale(array, scalar)

Returns a new array with each element of the input array multiplied by a scalar value, computed as array[i] * scalar. Returns NULL if the input row is NULL or the scalar is NULL. If a NULL element appears in the input array at position i, the result element at position i is NULL. Returns an empty array for an empty input array.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

scalar

Numeric scalar to multiply each element by. Can be a constant or column expression.

Example
> select array_scale([1.0, 2.0, 3.0], 2.0);
+----------------------------------+
| array_scale(List([1.0,2.0,3.0]),Float64(2.0)) |
+----------------------------------+
| [2.0, 4.0, 6.0]                  |
+----------------------------------+

Also called list_scale.

array_slice

scalar
array_slice(array, begin, end[, stride])

Returns a slice of the array based on 1-indexed start and end positions.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

begin

Index of the first element. If negative, it counts backward from the end of the array.

end

Index of the last element. If negative, it counts backward from the end of the array.

stride

Stride of the array slice. The default is 1.

Example
> select array_slice([1, 2, 3, 4, 5, 6, 7, 8], 3, 6);
+--------------------------------------------------------+
| array_slice(List([1,2,3,4,5,6,7,8]),Int64(3),Int64(6)) |
+--------------------------------------------------------+
| [3, 4, 5, 6]                                           |
+--------------------------------------------------------+

Also called list_slice.

array_sort

scalar
array_sort(array[, order[, nulls_order]])

Sort array.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

order

Whether to sort in ascending (ASC) or descending (DESC) order. The default is ASC.

nulls_order

Whether to sort nulls first (NULLS FIRST) or last (NULLS LAST). The default is NULLS FIRST.

Example
> select array_sort([3, 1, 2]);
+-----------------------------+
| array_sort(List([3,1,2]))   |
+-----------------------------+
| [1, 2, 3]                   |
+-----------------------------+
> select array_sort([3, 1, NULL, 2], 'desc', 'nulls last');
+--------------------------------------------------+
| array_sort(List(3,1,NULL,2),'desc','nulls last') |
+--------------------------------------------------+
| [3, 2, 1, NULL]                                  |
+--------------------------------------------------+

Also called list_sort.

array_subtract

scalar
array_subtract(array1, array2)

Returns the element-wise difference of two numeric arrays of equal length, computed as array1[i] - array2[i] per position. NULL is propagated per element: if either input element at position i is NULL, the corresponding output element is NULL (positions are preserved). Returns NULL if either entire input array is NULL. Errors if the per-row lengths differ. Returns an empty array if both inputs are empty.

array1

Array expression. Can be a constant, column, or function, and any combination of array operators.

array2

Array expression. Can be a constant, column, or function, and any combination of array operators.

Example
> select array_subtract([10.0, 20.0, 30.0], [1.0, 2.0, 3.0]);
+--------------------------------------------------------------+
| array_subtract(List([10.0,20.0,30.0]),List([1.0,2.0,3.0]))   |
+--------------------------------------------------------------+
| [9.0, 18.0, 27.0]                                            |
+--------------------------------------------------------------+

Also called list_subtract.

array_sum

scalar
array_sum(array)

Returns the sum of the elements of the input array, computed as array[0] + array[1] + .... NULL elements are skipped (per SQL aggregate convention). Returns NULL if the input row is NULL, every element is NULL, or the array is empty.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

Example
> select array_sum([1.0, 2.0, 3.0]);
+----------------------------+
| array_sum(List([1.0,2.0,3.0])) |
+----------------------------+
| 6.0                        |
+----------------------------+

Also called list_sum.

array_to_string

scalar
array_to_string(array, delimiter[, null_string])

Converts each element to its text representation.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

delimiter

Array element separator.

null_string

Optional. String to use for null values in the output. If not provided, nulls will be omitted.

Example
> select array_to_string([[1, 2, 3, 4], [5, 6, 7, 8]], ',');
+----------------------------------------------------+
| array_to_string(List([1,2,3,4,5,6,7,8]),Utf8(",")) |
+----------------------------------------------------+
| 1,2,3,4,5,6,7,8                                    |
+----------------------------------------------------+

Also called list_to_string, array_join, list_join.

array_union

scalar
array_union(array1, array2)

Returns an array of elements that are present in both arrays (all elements from both arrays) without duplicates.

array1

Array expression. Can be a constant, column, or function, and any combination of array operators.

array2

Array expression. Can be a constant, column, or function, and any combination of array operators.

Example
> select array_union([1, 2, 3, 4], [5, 6, 3, 4]);
+----------------------------------------------------+
| array_union([1, 2, 3, 4], [5, 6, 3, 4]);           |
+----------------------------------------------------+
| [1, 2, 3, 4, 5, 6]                                 |
+----------------------------------------------------+
> select array_union([1, 2, 3, 4], [5, 6, 7, 8]);
+----------------------------------------------------+
| array_union([1, 2, 3, 4], [5, 6, 7, 8]);           |
+----------------------------------------------------+
| [1, 2, 3, 4, 5, 6, 7, 8]                           |
+----------------------------------------------------+

Also called list_union.

arrays_zip

scalar
arrays_zip(array1[, ..., array_n])

Returns an array of structs created by combining the elements of each input array at the same index. If the arrays have different lengths, shorter arrays are padded with NULLs.

array1

First array expression.

array_n

Optional additional array expressions.

Example
> select arrays_zip([1, 2, 3]);
+---------------------------------------------------+
| arrays_zip([1, 2, 3])                             |
+---------------------------------------------------+
| [{1: 1}, {1: 2}, {1: 3}]                          |
+---------------------------------------------------+
> select arrays_zip([1, 2], [3, 4, 5]);
+---------------------------------------------------+
| arrays_zip([1, 2], [3, 4, 5])                     |
+---------------------------------------------------+
| [{1: 1, 2: 3}, {1: 2, 2: 4}, {1: NULL, 2: 5}]     |
+---------------------------------------------------+

Also called list_zip.

cardinality

scalar
cardinality(array)

Returns the total number of elements in the array.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

Example
> select cardinality([[1, 2, 3, 4], [5, 6, 7, 8]]);
+--------------------------------------+
| cardinality(List([1,2,3,4,5,6,7,8])) |
+--------------------------------------+
| 8                                    |
+--------------------------------------+

cosine_distance

scalar
cosine_distance(array1, array2)

Returns the cosine distance between two input arrays of equal length. The cosine distance is defined as 1 - cosine_similarity, i.e. 1 - dot(a,b) / (||a|| * ||b||). Returns NULL if either array is NULL or contains only zeros.

array1

Array expression. Can be a constant, column, or function, and any combination of array operators.

array2

Array expression. Can be a constant, column, or function, and any combination of array operators.

Example
> select cosine_distance([1.0, 0.0], [0.0, 1.0]);
+-----------------------------------------------+
| cosine_distance(List([1.0,0.0]),List([0.0,1.0])) |
+-----------------------------------------------+
| 1.0                                           |
+-----------------------------------------------+

empty

scalar
empty(array)

Returns 1 for an empty array or 0 for a non-empty array.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

Example
> select empty([1]);
+------------------+
| empty(List([1])) |
+------------------+
| 0                |
+------------------+

Also called array_empty, list_empty.

flatten

scalar
flatten(array)

Converts an array of arrays to a flat array. - Applies to any depth of nested arrays - Does not change arrays that are already flat The flattened array contains all the elements from all source arrays.

array

Array expression. Can be a constant, column, or function, and any combination of array operators.

Example
> select flatten([[1, 2], [3, 4]]);
+------------------------------+
| flatten(List([1,2], [3,4]))  |
+------------------------------+
| [1, 2, 3, 4]                 |
+------------------------------+

generate_series

scalar
generate_series(stop)
generate_series(start, stop[, step])

Similar to the range function, but it includes the upper bound.

start

Start of the series. Ints, timestamps, dates or string types that can be coerced to Date32 are supported.

end

End of the series (included). Type must be the same as start.

step

Increase by step (can not be 0). Steps less than a day are supported only for timestamp ranges.

Example
> select generate_series(1,3);
+------------------------------------+
| generate_series(Int64(1),Int64(3)) |
+------------------------------------+
| [1, 2, 3]                          |
+------------------------------------+

inner_product

scalar
inner_product(array1, array2)

Returns the inner product (dot product) of two input arrays of equal length, computed as sum(array1[i] * array2[i]). Returns NULL if either array is NULL or contains NULL elements. Returns 0.0 for two empty arrays.

array1

Array expression. Can be a constant, column, or function, and any combination of array operators.

array2

Array expression. Can be a constant, column, or function, and any combination of array operators.

Example
> select inner_product([1.0, 2.0, 3.0], [4.0, 5.0, 6.0]);
+-------------------------------------------------------+
| inner_product(List([1.0,2.0,3.0]),List([4.0,5.0,6.0])) |
+-------------------------------------------------------+
| 32.0                                                  |
+-------------------------------------------------------+

Also called dot_product.

make_array

scalar
make_array([expression1, ..., expression_n])

Returns an array using the specified input expressions.

expression_n

Expression to include in the output array. Can be a constant, column, or function, and any combination of arithmetic or string operators.

Example
> select make_array(1, 2, 3, 4, 5);
+----------------------------------------------------------+
| make_array(Int64(1),Int64(2),Int64(3),Int64(4),Int64(5)) |
+----------------------------------------------------------+
| [1, 2, 3, 4, 5]                                          |
+----------------------------------------------------------+

Also called make_list.

range

scalar
range(stop)
range(start, stop[, step])

Returns an array between start and stop with step. The range start..end contains all values with start <= x < end. It is empty if start >= end. Step cannot be 0.

start

Start of the range. Ints, timestamps, dates or string types that can be coerced to Date32 are supported.

end

End of the range (not included). Type must be the same as start.

step

Increase by step (cannot be 0). Steps less than a day are supported only for timestamp ranges.

Example
> select range(2, 10, 3);
+-----------------------------------+
| range(Int64(2),Int64(10),Int64(3))|
+-----------------------------------+
| [2, 5, 8]                         |
+-----------------------------------+

> select range(DATE '1992-09-01', DATE '1993-03-01', INTERVAL '1' MONTH);
+--------------------------------------------------------------------------+
| range(DATE '1992-09-01', DATE '1993-03-01', INTERVAL '1' MONTH)          |
+--------------------------------------------------------------------------+
| [1992-09-01, 1992-10-01, 1992-11-01, 1992-12-01, 1993-01-01, 1993-02-01] |
+--------------------------------------------------------------------------+

string_to_array

scalar
string_to_array(str, delimiter[, null_str])

Splits a string into an array of substrings based on a delimiter. Any substrings matching the optional null_str argument are replaced with NULL.

str

String expression to split.

delimiter

Delimiter string to split on.

null_str

Substring values to be replaced with NULL.

Example
> select string_to_array('abc##def', '##');
+-----------------------------------+
| string_to_array(Utf8('abc##def'))  |
+-----------------------------------+
| ['abc', 'def']                    |
+-----------------------------------+
> select string_to_array('abc def', ' ', 'def');
+---------------------------------------------+
| string_to_array(Utf8('abc def'), Utf8(' '), Utf8('def')) |
+---------------------------------------------+
| ['abc', NULL]                               |
+---------------------------------------------+

Also called string_to_list.

Binary String Functions 2

decode

scalar
decode(expression, format)

Decode binary data from textual representation in string.

expression

Expression containing encoded string data

format

Same arguments as encode

Related: encode.

encode

scalar
encode(expression, format)

Encode binary data into a textual representation.

expression

Expression containing string or binary data

format

Supported formats are: base64, base64pad, hex

Related: decode.

Conditional Functions 6

coalesce

scalar
coalesce(expression1[, ..., expression_n])

Returns the first of its arguments that is not null. Returns null if all arguments are null. This function is often used to substitute a default value for null values.

expression1, expression_n

Expression to use if previous expressions are null. Can be a constant, column, or function, and any combination of arithmetic operators. Pass as many expression arguments as necessary.

greatest

scalar
greatest(expression1[, ..., expression_n])

Returns the greatest value in a list of expressions. Returns null if all expressions are null.

expression1, expression_n

Expressions to compare and return the greatest value.. Can be a constant, column, or function, and any combination of arithmetic operators. Pass as many expression arguments as necessary.

Example
> select greatest(4, 7, 5);
+---------------------------+
| greatest(4,7,5)           |
+---------------------------+
| 7                         |
+---------------------------+

least

scalar
least(expression1[, ..., expression_n])

Returns the smallest value in a list of expressions. Returns null if all expressions are null.

expression1, expression_n

Expressions to compare and return the smallest value. Can be a constant, column, or function, and any combination of arithmetic operators. Pass as many expression arguments as necessary.

Example
> select least(4, 7, 5);
+---------------------------+
| least(4,7,5)              |
+---------------------------+
| 4                         |
+---------------------------+

nullif

scalar
nullif(expression1, expression2)

Returns null if expression1 equals expression2; otherwise it returns expression1. This can be used to perform the inverse operation of coalesce.

expression1

Expression to compare and return if equal to expression2. Can be a constant, column, or function, and any combination of operators.

expression2

Expression to compare to expression1. Can be a constant, column, or function, and any combination of operators.

nvl

scalar
nvl(expression1, expression2)

Returns expression2 if expression1 is NULL otherwise it returns expression1 and expression2 is not evaluated. This function can be used to substitute a default value for NULL values.

expression1

Expression to return if not null. Can be a constant, column, or function, and any combination of operators.

expression2

Expression to return if expr1 is null. Can be a constant, column, or function, and any combination of operators.

Example
> select nvl(null, 'a');
+---------------------+
| nvl(NULL,Utf8("a")) |
+---------------------+
| a                   |
+---------------------+\
> select nvl('b', 'a');
+--------------------------+
| nvl(Utf8("b"),Utf8("a")) |
+--------------------------+
| b                        |
+--------------------------+

Also called ifnull.

nvl2

scalar
nvl2(expression1, expression2, expression3)

Returns expression2 if expression1 is not NULL; otherwise it returns expression3.

expression1

Expression to test for null. Can be a constant, column, or function, and any combination of operators.

expression2

Expression to return if expr1 is not null. Can be a constant, column, or function, and any combination of operators.

expression3

Expression to return if expr1 is null. Can be a constant, column, or function, and any combination of operators.

Example
> select nvl2(null, 'a', 'b');
+--------------------------------+
| nvl2(NULL,Utf8("a"),Utf8("b")) |
+--------------------------------+
| b                              |
+--------------------------------+
> select nvl2('data', 'a', 'b');
+----------------------------------------+
| nvl2(Utf8("data"),Utf8("a"),Utf8("b")) |
+----------------------------------------+
| a                                      |
+----------------------------------------+

General Functions 20

any_value

aggregate
any_value(expression)

Returns an arbitrary non-null value from a group, or NULL if the group contains only NULL values.

expression

The expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT any_value(column_name) FROM table_name;
+------------------------+
| any_value(column_name) |
+------------------------+
| arbitrary_value        |
+------------------------+

array_agg

aggregate
array_agg(expression [ORDER BY expression])

Returns an array created from the expression elements. If ordering is required, elements are inserted in the specified order. This aggregation function can only mix DISTINCT and ORDER BY if the ordering expression is exactly the same as the argument expression.

expression

The expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT array_agg(column_name ORDER BY other_column) FROM table_name;
+-----------------------------------------------+
| array_agg(column_name ORDER BY other_column)  |
+-----------------------------------------------+
| [element1, element2, element3]                |
+-----------------------------------------------+
> SELECT array_agg(DISTINCT column_name ORDER BY column_name) FROM table_name;
+--------------------------------------------------------+
| array_agg(DISTINCT column_name ORDER BY column_name)  |
+--------------------------------------------------------+
| [element1, element2, element3]                         |
+--------------------------------------------------------+

avg

aggregate
avg(expression)

Returns the average of numeric values in the specified column.

expression

The expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT avg(column_name) FROM table_name;
+---------------------------+
| avg(column_name)           |
+---------------------------+
| 42.75                      |
+---------------------------+

Also called mean.

bit_and

aggregate
bit_and(expression)

Computes the bitwise AND of all non-null input values.

expression

Integer expression to operate on. Can be a constant, column, or function, and any combination of operators.

bit_or

aggregate
bit_or(expression)

Computes the bitwise OR of all non-null input values.

expression

Integer expression to operate on. Can be a constant, column, or function, and any combination of operators.

bit_xor

aggregate
bit_xor(expression)

Computes the bitwise exclusive OR of all non-null input values.

expression

Integer expression to operate on. Can be a constant, column, or function, and any combination of operators.

bool_and

aggregate
bool_and(expression)

Returns true if all non-null input values are true, otherwise false.

expression

The expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT bool_and(column_name) FROM table_name;
+----------------------------+
| bool_and(column_name)       |
+----------------------------+
| true                        |
+----------------------------+

bool_or

aggregate
bool_or

Returns true if all non-null input values are true, otherwise false.

expression

The expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT bool_and(column_name) FROM table_name;
+----------------------------+
| bool_and(column_name)       |
+----------------------------+
| true                        |
+----------------------------+

count

aggregate
count(expression)

Returns the number of non-null values in the specified column. To include null values in the total count, use count(*).

expression

The expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT count(column_name) FROM table_name;
+-----------------------+
| count(column_name)     |
+-----------------------+
| 100                   |
+-----------------------+

> SELECT count(*) FROM table_name;
+------------------+
| count(*)         |
+------------------+
| 120              |
+------------------+

first_value

aggregate
first_value(expression [ORDER BY expression])

Returns the first element in an aggregation group according to the requested ordering. If no ordering is given, returns an arbitrary element from the group.

expression

The expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT first_value(column_name ORDER BY other_column) FROM table_name;
+-----------------------------------------------+
| first_value(column_name ORDER BY other_column)|
+-----------------------------------------------+
| first_element                                 |
+-----------------------------------------------+

grouping

aggregate
grouping(expression)

Returns 1 if the data is aggregated across the specified column, or 0 if it is not aggregated in the result set.

expression

Expression to evaluate whether data is aggregated across the specified column. Can be a constant, column, or function.

Example
> SELECT column_name, GROUPING(column_name) AS group_column
  FROM table_name
  GROUP BY GROUPING SETS ((column_name), ());
+-------------+-------------+
| column_name | group_column |
+-------------+-------------+
| value1      | 0           |
| value2      | 0           |
| NULL        | 1           |
+-------------+-------------+

last_value

aggregate
last_value(expression [ORDER BY expression])

Returns the last element in an aggregation group according to the requested ordering. If no ordering is given, returns an arbitrary element from the group.

expression

The expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT last_value(column_name ORDER BY other_column) FROM table_name;
+-----------------------------------------------+
| last_value(column_name ORDER BY other_column) |
+-----------------------------------------------+
| last_element                                  |
+-----------------------------------------------+

max

aggregate
max(expression)

Returns the maximum value in the specified column.

expression

The expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT max(column_name) FROM table_name;
+----------------------+
| max(column_name)      |
+----------------------+
| 150                  |
+----------------------+

median

aggregate
median(expression)

Returns the median value in the specified column.

expression

The expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT median(column_name) FROM table_name;
+----------------------+
| median(column_name)   |
+----------------------+
| 45.5                 |
+----------------------+

min

aggregate
min(expression)

Returns the minimum value in the specified column.

expression

The expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT min(column_name) FROM table_name;
+----------------------+
| min(column_name)      |
+----------------------+
| 12                   |
+----------------------+

percentile_cont

aggregate
percentile_cont(percentile) WITHIN GROUP (ORDER BY expression)

Returns the exact percentile of input values, interpolating between values if needed.

expression

The expression to operate on. Can be a constant, column, or function, and any combination of operators.

percentile

Percentile to compute. Must be a float value between 0 and 1 (inclusive).

Example
> SELECT percentile_cont(0.75) WITHIN GROUP (ORDER BY column_name) FROM table_name;
+----------------------------------------------------------+
| percentile_cont(0.75) WITHIN GROUP (ORDER BY column_name) |
+----------------------------------------------------------+
| 45.5                                                     |
+----------------------------------------------------------+

> SELECT percentile_cont(column_name, 0.75) FROM table_name;
+---------------------------------------+
| percentile_cont(column_name, 0.75)    |
+---------------------------------------+
| 45.5                                  |
+---------------------------------------+

Also called quantile_cont.

string_agg

aggregate
string_agg([DISTINCT] expression, delimiter [ORDER BY expression])

Concatenates the values of string expressions and places separator values between them. If ordering is required, strings are concatenated in the specified order. This aggregation function can only mix DISTINCT and ORDER BY if the ordering expression is exactly the same as the first argument expression.

expression

The string expression to concatenate. Can be a column or any valid string expression.

delimiter

A literal string used as a separator between the concatenated values.

Example
> SELECT string_agg(name, ', ') AS names_list
  FROM employee;
+--------------------------+
| names_list               |
+--------------------------+
| Alice, Bob, Bob, Charlie |
+--------------------------+
> SELECT string_agg(name, ', ' ORDER BY name DESC) AS names_list
  FROM employee;
+--------------------------+
| names_list               |
+--------------------------+
| Charlie, Bob, Bob, Alice |
+--------------------------+
> SELECT string_agg(DISTINCT name, ', ' ORDER BY name DESC) AS names_list
  FROM employee;
+--------------------------+
| names_list               |
+--------------------------+
| Charlie, Bob, Alice |
+--------------------------+

sum

aggregate
sum(expression)

Returns the sum of all values in the specified column.

expression

The expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT sum(column_name) FROM table_name;
+-----------------------+
| sum(column_name)       |
+-----------------------+
| 12345                 |
+-----------------------+

var

aggregate
var(expression)

Returns the statistical sample variance of a set of numbers.

expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Also called var_sample, var_samp.

var_pop

aggregate
var_pop(expression)

Returns the statistical population variance of a set of numbers.

expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Also called var_population.

Hashing Functions 6

digest

scalar
digest(expression, algorithm)

Computes the binary hash of an expression using the specified algorithm.

expression

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

algorithm

String expression specifying algorithm to use. Must be one of:

  • md5
  • sha224
  • sha256
  • sha384
  • sha512
  • blake2s
  • blake2b
  • blake3
Example
> select digest('foo', 'sha256');
+------------------------------------------------------------------+
| digest(Utf8("foo"),Utf8("sha256"))                               |
+------------------------------------------------------------------+
| 2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae |
+------------------------------------------------------------------+

md5

scalar
md5(expression)

Computes an MD5 128-bit checksum for a string expression.

expression

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> select md5('foo');
+----------------------------------+
| md5(Utf8("foo"))                 |
+----------------------------------+
| acbd18db4cc2f85cedef654fccc4a4d8 |
+----------------------------------+

sha224

scalar
sha224(expression)

Computes the SHA-224 hash of a binary string.

expression

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> select sha224('foo');
+----------------------------------------------------------+
| sha224(Utf8("foo"))                                      |
+----------------------------------------------------------+
| 0808f64e60d58979fcb676c96ec938270dea42445aeefcd3a4e6f8db |
+----------------------------------------------------------+

sha256

scalar
sha256(expression)

Computes the SHA-256 hash of a binary string.

expression

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> select sha256('foo');
+------------------------------------------------------------------+
| sha256(Utf8("foo"))                                              |
+------------------------------------------------------------------+
| 2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae |
+------------------------------------------------------------------+

sha384

scalar
sha384(expression)

Computes the SHA-384 hash of a binary string.

expression

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> select sha384('foo');
+--------------------------------------------------------------------------------------------------+
| sha384(Utf8("foo"))                                                                              |
+--------------------------------------------------------------------------------------------------+
| 98c11ffdfdd540676b1a137cb1a22b2a70350c9a44171d6b1180c6be5cbb2ee3f79d532c8a1dd9ef2e8e08e752a3babb |
+--------------------------------------------------------------------------------------------------+

sha512

scalar
sha512(expression)

Computes the SHA-512 hash of a binary string.

expression

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> select sha512('foo');
+----------------------------------------------------------------------------------------------------------------------------------+
| sha512(Utf8("foo"))                                                                                                              |
+----------------------------------------------------------------------------------------------------------------------------------+
| f7fbba6e0636f890e56fbbf3283e524c6fa3204ae298382d624741d0dc6638326e282c41be5e4254d8820772c5518a2c5a8c0c7f7eda19594a7eb539453e1ed7 |
+----------------------------------------------------------------------------------------------------------------------------------+

Map Functions 5

map

scalar
map(key, value)
map {key: value}

Returns a map with the specified key-value pairs. The make_map function creates a map from two lists: one for keys and one for values. Each key must be unique and non-null.

key

For map: Expression to be used for key. Can be a constant, column, function, or any combination of arithmetic or string operators. For make_map: The list of keys to be used in the map. Each key must be unique and non-null.

value

For map: Expression to be used for value. Can be a constant, column, function, or any combination of arithmetic or string operators. For make_map: The list of values to be mapped to the corresponding keys.

Example
-- Using map function
SELECT MAP('type', 'test');
----
{type: test}

SELECT MAP(['POST', 'HEAD', 'PATCH'], [41, 33, null]);
----
{POST: 41, HEAD: 33, PATCH: NULL}

SELECT MAP([[1,2], [3,4]], ['a', 'b']);
----
{[1, 2]: a, [3, 4]: b}

SELECT MAP { 'a': 1, 'b': 2 };
----
{a: 1, b: 2}

-- Using make_map function
SELECT MAKE_MAP(['POST', 'HEAD'], [41, 33]);
----
{POST: 41, HEAD: 33}

SELECT MAKE_MAP(['key1', 'key2'], ['value1', null]);
----
{key1: value1, key2: }

map_entries

scalar
map_entries(map)

Returns a list of all entries in the map.

map

Map expression. Can be a constant, column, or function, and any combination of map operators.

Example
SELECT map_entries(MAP {'a': 1, 'b': NULL, 'c': 3});
----
[{'key': a, 'value': 1}, {'key': b, 'value': NULL}, {'key': c, 'value': 3}]

SELECT map_entries(map([100, 5], [42, 43]));
----
[{'key': 100, 'value': 42}, {'key': 5, 'value': 43}]

map_extract

scalar
map_extract(map, key)

Returns a list containing the value for the given key or an empty list if the key is not present in the map.

map

Map expression. Can be a constant, column, or function, and any combination of map operators.

key

Key to extract from the map. Can be a constant, column, or function, any combination of arithmetic or string operators, or a named expression of the previously listed.

Example
SELECT map_extract(MAP {'a': 1, 'b': NULL, 'c': 3}, 'a');
----
[1]

SELECT map_extract(MAP {1: 'one', 2: 'two'}, 2);
----
['two']

SELECT map_extract(MAP {'x': 10, 'y': NULL, 'z': 30}, 'y');
----
[NULL]

-- non-existing key
SELECT map_extract(MAP {'x': 10, 'y': NULL, 'z': 30}, 'a');
----
[]

Also called element_at.

map_keys

scalar
map_keys(map)

Returns a list of all keys in the map.

map

Map expression. Can be a constant, column, or function, and any combination of map operators.

Example
SELECT map_keys(MAP {'a': 1, 'b': NULL, 'c': 3});
----
[a, b, c]

SELECT map_keys(map([100, 5], [42, 43]));
----
[100, 5]

map_values

scalar
map_values(map)

Returns a list of all values in the map.

map

Map expression. Can be a constant, column, or function, and any combination of map operators.

Example
SELECT map_values(MAP {'a': 1, 'b': NULL, 'c': 3});
----
[1, , 3]

SELECT map_values(map([100, 5], [42, 43]));
----
[42, 43]

Math Functions 38

abs

scalar
abs(numeric_expression)

Returns the absolute value of a number.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT abs(-5);
+----------+
| abs(-5)  |
+----------+
| 5        |
+----------+

acos

scalar
acos(numeric_expression)

Returns the arc cosine or inverse cosine of a number.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT acos(1);
+----------+
| acos(1)  |
+----------+
| 0.0      |
+----------+

acosh

scalar
acosh(numeric_expression)

Returns the area hyperbolic cosine or inverse hyperbolic cosine of a number.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT acosh(2);
+------------+
| acosh(2)   |
+------------+
| 1.31696    |
+------------+

asin

scalar
asin(numeric_expression)

Returns the arc sine or inverse sine of a number.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT asin(0.5);
+------------+
| asin(0.5)  |
+------------+
| 0.5235988  |
+------------+

asinh

scalar
asinh(numeric_expression)

Returns the area hyperbolic sine or inverse hyperbolic sine of a number.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT asinh(1);
+------------+
| asinh(1)   |
+------------+
| 0.8813736  |
+------------+

atan

scalar
atan(numeric_expression)

Returns the arc tangent or inverse tangent of a number.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT atan(1);
+-----------+
| atan(1)   |
+-----------+
| 0.7853982 |
+-----------+

atan2

scalar
atan2(expression_y, expression_x)

Returns the arc tangent or inverse tangent of expression_y / expression_x.

expression_y

First numeric expression to operate on. Can be a constant, column, or function, and any combination of arithmetic operators.

expression_x

Second numeric expression to operate on. Can be a constant, column, or function, and any combination of arithmetic operators.

Example
> SELECT atan2(1, 1);
+--------------------+
| atan2(1,1)         |
+--------------------+
| 0.7853981633974483 |
+--------------------+

atanh

scalar
atanh(numeric_expression)

Returns the area hyperbolic tangent or inverse hyperbolic tangent of a number.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT atanh(0.5);
+-------------+
| atanh(0.5)  |
+-------------+
| 0.5493061   |
+-------------+

cbrt

scalar
cbrt(numeric_expression)

Returns the cube root of a number.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT cbrt(27);
+-----------+
| cbrt(27)  |
+-----------+
| 3.0       |
+-----------+

ceil

scalar
ceil(numeric_expression)

Returns the nearest integer greater than or equal to a number.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT ceil(3.14);
+------------+
| ceil(3.14) |
+------------+
| 4.0        |
+------------+

cos

scalar
cos(numeric_expression)

Returns the cosine of a number.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT cos(0);
+--------+
| cos(0) |
+--------+
| 1.0    |
+--------+

cosh

scalar
cosh(numeric_expression)

Returns the hyperbolic cosine of a number.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT cosh(1);
+-----------+
| cosh(1)   |
+-----------+
| 1.5430806 |
+-----------+

cot

scalar
cot(numeric_expression)

Returns the cotangent of a number.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT cot(1);
+---------+
| cot(1)  |
+---------+
| 0.64209 |
+---------+

degrees

scalar
degrees(numeric_expression)

Converts radians to degrees.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT degrees(pi());
+------------+
| degrees(0) |
+------------+
| 180.0      |
+------------+

exp

scalar
exp(numeric_expression)

Returns the base-e exponential of a number.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT exp(1);
+---------+
| exp(1)  |
+---------+
| 2.71828 |
+---------+

factorial

scalar
factorial(numeric_expression)

Factorial of a non-negative integer. Errors if the argument is negative or the result overflows.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT factorial(5);
+---------------+
| factorial(5)  |
+---------------+
| 120           |
+---------------+

floor

scalar
floor(numeric_expression)

Returns the nearest integer less than or equal to a number.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT floor(3.14);
+-------------+
| floor(3.14) |
+-------------+
| 3.0         |
+-------------+

gcd

scalar
gcd(expression_x, expression_y)

Returns the greatest common divisor of expression_x and expression_y. Returns 0 if both inputs are zero.

expression_x

First numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

expression_y

Second numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT gcd(48, 18);
+------------+
| gcd(48,18) |
+------------+
| 6          |
+------------+

isnan

scalar
isnan(numeric_expression)

Returns true if a given number is +NaN or -NaN otherwise returns false.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT isnan(1);
+----------+
| isnan(1) |
+----------+
| false    |
+----------+

iszero

scalar
iszero(numeric_expression)

Returns true if a given number is +0.0 or -0.0 otherwise returns false.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT iszero(0);
+------------+
| iszero(0)  |
+------------+
| true       |
+------------+

lcm

scalar
lcm(expression_x, expression_y)

Returns the least common multiple of expression_x and expression_y. Returns 0 if either input is zero.

expression_x

First numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

expression_y

Second numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT lcm(4, 5);
+----------+
| lcm(4,5) |
+----------+
| 20       |
+----------+

ln

scalar
ln(numeric_expression)

Returns the natural logarithm of a number.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT ln(2.71828);
+-------------+
| ln(2.71828) |
+-------------+
| 1.0         |
+-------------+

log

scalar
log(base, numeric_expression)
log(numeric_expression)

Returns the base-x logarithm of a number. Can either provide a specified base, or if omitted then takes the base-10 of a number.

base

Base numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT log(10);
+---------+
| log(10) |
+---------+
| 1.0     |
+---------+

log10

scalar
log10(numeric_expression)

Returns the base-10 logarithm of a number.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT log10(100);
+-------------+
| log10(100)  |
+-------------+
| 2.0         |
+-------------+

log2

scalar
log2(numeric_expression)

Returns the base-2 logarithm of a number.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT log2(8);
+-----------+
| log2(8)   |
+-----------+
| 3.0       |
+-----------+

nanvl

scalar
nanvl(expression_x, expression_y)

Returns the first argument if it's not NaN. Returns the second argument otherwise.

expression_x

Numeric expression to return if it's not NaN. Can be a constant, column, or function, and any combination of arithmetic operators.

expression_y

Numeric expression to return if the first expression is NaN. Can be a constant, column, or function, and any combination of arithmetic operators.

Example
> SELECT nanvl(0, 5);
+------------+
| nanvl(0,5) |
+------------+
| 0          |
+------------+

pi

scalar
pi()

Returns an approximate value of π.

power

scalar
power(base, exponent)

Returns a base expression raised to the power of an exponent.

base

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

exponent

Exponent numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT power(2, 3);
+-------------+
| power(2,3)  |
+-------------+
| 8           |
+-------------+

Also called pow.

radians

scalar
radians(numeric_expression)

Converts degrees to radians.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT radians(180);
+----------------+
| radians(180)   |
+----------------+
| 3.14159265359  |
+----------------+

random

scalar
random()

Returns a random float value in the range [0, 1). The random seed is unique to each row.

Example
> SELECT random();
+------------------+
| random()         |
+------------------+
| 0.7389238902938  |
+------------------+

Also called rand.

round

scalar
round(numeric_expression[, decimal_places])

Rounds a number to the nearest integer.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

decimal_places

Optional. The number of decimal places to round to. Defaults to 0.

Example
> SELECT round(3.14159);
+--------------+
| round(3.14159)|
+--------------+
| 3.0          |
+--------------+

signum

scalar
signum(numeric_expression)

Returns the sign of a number. Negative numbers return -1. Zero and positive numbers return 1.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT signum(-42);
+-------------+
| signum(-42) |
+-------------+
| -1          |
+-------------+

sin

scalar
sin(numeric_expression)

Returns the sine of a number.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT sin(0);
+----------+
| sin(0)   |
+----------+
| 0.0      |
+----------+

sinh

scalar
sinh(numeric_expression)

Returns the hyperbolic sine of a number.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT sinh(1);
+-----------+
| sinh(1)   |
+-----------+
| 1.1752012 |
+-----------+

sqrt

scalar
sqrt(numeric_expression)

Returns the square root of a number.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

tan

scalar
tan(numeric_expression)

Returns the tangent of a number.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT tan(pi()/4);
+--------------+
| tan(PI()/4)  |
+--------------+
| 1.0          |
+--------------+

tanh

scalar
tanh(numeric_expression)

Returns the hyperbolic tangent of a number.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT tanh(20);
+----------+
| tanh(20) |
+----------+
| 1.0      |
+----------+

trunc

scalar
trunc(numeric_expression[, decimal_places])

Truncates a number to a whole number or truncated to the specified decimal places.

numeric_expression

Numeric expression to operate on. Can be a constant, column, or function, and any combination of operators.

decimal_places

Optional. The number of decimal places to truncate to. Defaults to 0 (truncate to a whole number). If decimal_places is a positive integer, truncates digits to the right of the decimal point. If decimal_places is a negative integer, replaces digits to the left of the decimal point with 0.

Example
> SELECT trunc(42.738);
+----------------+
| trunc(42.738)  |
+----------------+
| 42             |
+----------------+

Other Functions 12

arrow_cast

scalar
arrow_cast(expression, datatype)

Casts a value to a specific data type.

expression

Expression to cast. The expression can be a constant, column, or function, and any combination of operators.

datatype

data type name to cast to, as a string. The format is the same as that returned by [arrow_typeof]

Example
> select
  arrow_cast(-5,    'Int8') as a,
  arrow_cast('foo', 'Dictionary(Int32, Utf8)') as b,
  arrow_cast('bar', 'LargeUtf8') as c;

+----+-----+-----+
| a  | b   | c   |
+----+-----+-----+
| -5 | foo | bar |
+----+-----+-----+

> select
  arrow_cast('2023-01-02T12:53:02', 'Timestamp(µs, "+08:00")') as d,
  arrow_cast('2023-01-02T12:53:02', 'Timestamp(µs)') as e;

+---------------------------+---------------------+
| d                         | e                   |
+---------------------------+---------------------+
| 2023-01-02T12:53:02+08:00 | 2023-01-02T12:53:02 |
+---------------------------+---------------------+

arrow_field

scalar
arrow_field(expression)

Returns a struct containing the Arrow field information of the expression, including name, data type, nullability, and metadata.

expression

Expression to evaluate. The expression can be a constant, column, or function, and any combination of operators.

Example
> select arrow_field(1);
+-------------------------------------------------------------+
| arrow_field(Int64(1))                                       |
+-------------------------------------------------------------+
| {name: lit, data_type: Int64, nullable: false, metadata: {}} |
+-------------------------------------------------------------+

> select arrow_field(1)['data_type'];
+-----------------------------------+
| arrow_field(Int64(1))[data_type]  |
+-----------------------------------+
| Int64                             |
+-----------------------------------+

arrow_metadata

scalar
arrow_metadata(expression[, key])

Returns the metadata of the input expression. If a key is provided, returns the value for that key. If no key is provided, returns a Map of all metadata.

expression

The expression to retrieve metadata from. Can be a column or other expression.

key

Optional. The specific metadata key to retrieve.

Example
> select arrow_metadata(col) from table;
+----------------------------+
| arrow_metadata(table.col)  |
+----------------------------+
| {k: v}                     |
+----------------------------+
> select arrow_metadata(col, 'k') from table;
+-------------------------------+
| arrow_metadata(table.col, 'k')|
+-------------------------------+
| v                             |
+-------------------------------+

arrow_try_cast

scalar
arrow_try_cast(expression, datatype)

Casts a value to a specific data type, returning NULL if the cast fails.

expression

Expression to cast. The expression can be a constant, column, or function, and any combination of operators.

datatype

data type name to cast to, as a string. The format is the same as that returned by [arrow_typeof]

Example
> select arrow_try_cast('123', 'Int64') as a,
         arrow_try_cast('not_a_number', 'Int64') as b;

+-----+------+
| a   | b    |
+-----+------+
| 123 | NULL |
+-----+------+

arrow_typeof

scalar
arrow_typeof(expression)

Returns the name of the underlying data type of the expression.

expression

Expression to evaluate. The expression can be a constant, column, or function, and any combination of operators.

Example
> select arrow_typeof('foo'), arrow_typeof(1);
+---------------------------+------------------------+
| arrow_typeof(Utf8("foo")) | arrow_typeof(Int64(1)) |
+---------------------------+------------------------+
| Utf8                      | Int64                  |
+---------------------------+------------------------+

cast_to_type

scalar
cast_to_type(expression, reference)

Casts the first argument to the data type of the second argument. Only the type of the second argument is used; its value is ignored.

expression

The expression to cast. It can be a constant, column, or function, and any combination of operators.

reference

Reference expression whose data type determines the target cast type. The value is ignored.

Example
> select cast_to_type('42', NULL::INTEGER) as a;
+----+
| a  |
+----+
| 42 |
+----+

> select cast_to_type(1 + 2, NULL::DOUBLE) as b;
+-----+
| b   |
+-----+
| 3.0 |
+-----+

file_row_index

scalar
file_row_index()

Returns the zero-based row offset within the source file that produced the current row. The value is scoped to one file, so rows from different files in the same scan can have the same row index. This function is intended to be rewritten at file-scan time. If the input file is not known (for example, if this function is evaluated outside a file scan, or was not pushed down into one), direct evaluation returns an error.

Example
SELECT file_row_index() FROM t;

get_field

scalar
get_field(expression, field_name[, field_name2, ...])

Returns a field within a map or a struct with the given key. Supports nested field access by providing multiple field names. Note: most users invoke get_field indirectly via field access syntax such as my_struct_col['field_name'] which results in a call to get_field(my_struct_col, 'field_name'). Nested access like my_struct['a']['b'] is optimized to a single call: get_field(my_struct, 'a', 'b').

expression

The map or struct to retrieve a field from.

field_name

The field name(s) to access, in order for nested access. Must evaluate to strings.

Example
> -- Access a field from a struct column
> create table test( struct_col) as values
    ({name: 'Alice', age: 30}),
    ({name: 'Bob', age: 25});
> select struct_col from test;
+-----------------------------+
| struct_col                  |
+-----------------------------+
| {name: Alice, age: 30}      |
| {name: Bob, age: 25}        |
+-----------------------------+
> select struct_col['name'] as name from test;
+-------+
| name  |
+-------+
| Alice |
| Bob   |
+-------+

> -- Nested field access with multiple arguments
> create table test(struct_col) as values
    ({outer: {inner_val: 42}});
> select struct_col['outer']['inner_val'] as result from test;
+--------+
| result |
+--------+
| 42     |
+--------+

input_file_name

scalar
input_file_name()

Returns the path of the input file that produced the current row. Note: file paths/URIs may be sensitive metadata depending on your environment. This function is intended to be rewritten at file-scan time (when the file is known). If the input file is not known (for example, if this function is evaluated outside a file scan, or was not pushed down into one), direct evaluation returns an error.

Example
SELECT input_file_name() FROM t;

try_cast_to_type

scalar
try_cast_to_type(expression, reference)

Casts the first argument to the data type of the second argument, returning NULL if the cast fails. Only the type of the second argument is used; its value is ignored.

expression

The expression to cast. It can be a constant, column, or function, and any combination of operators.

reference

Reference expression whose data type determines the target cast type. The value is ignored.

Example
> select try_cast_to_type('123', NULL::INTEGER) as a,
         try_cast_to_type('not_a_number', NULL::INTEGER) as b;

+-----+------+
| a   | b    |
+-----+------+
| 123 | NULL |
+-----+------+

version

scalar
version()

Returns the version of the query engine.

with_metadata

scalar
with_metadata(expression, key1, value1[, key2, value2, ...])

Attaches Arrow field metadata (key/value pairs) to the input expression. Keys must be non-empty constant strings and values must be constant strings (empty values are allowed). Existing metadata on the input field is preserved; new keys overwrite on collision. This is the inverse of arrow_metadata.

expression

The expression whose output Arrow field should be annotated. Values flow through unchanged.

key

Metadata key. Must be a non-empty constant string literal.

value

Metadata value. Must be a constant string literal (may be empty).

Example
> select arrow_metadata(with_metadata(column1, 'unit', 'ms'), 'unit') from (values (1));
+---------------------------------------------------------------+
| arrow_metadata(with_metadata(column1,Utf8("unit"),Utf8("ms")),Utf8("unit")) |
+---------------------------------------------------------------+
| ms                                                            |
+---------------------------------------------------------------+
> select arrow_metadata(with_metadata(column1, 'unit', 'ms', 'source', 'sensor')) from (values (1));
+--------------------------+
| {source: sensor, unit: ms} |
+--------------------------+

Ranking Functions 6

cume_dist

window
cume_dist()

Relative rank of the current row: (number of rows preceding or peer with the current row) / (total rows).

Example
-- Example usage of the cume_dist window function:
SELECT salary,
    cume_dist() OVER (ORDER BY salary) AS cume_dist
FROM employees;

+--------+-----------+
| salary | cume_dist |
+--------+-----------+
| 30000  | 0.33      |
| 50000  | 0.67      |
| 70000  | 1.00      |
+--------+-----------+

dense_rank

window
dense_rank()

Returns the rank of the current row without gaps. This function ranks rows in a dense manner, meaning consecutive ranks are assigned even for identical values.

Example
-- Example usage of the dense_rank window function:
SELECT department,
    salary,
    dense_rank() OVER (PARTITION BY department ORDER BY salary DESC) AS dense_rank
FROM employees;

+-------------+--------+------------+
| department  | salary | dense_rank |
+-------------+--------+------------+
| Sales       | 70000  | 1          |
| Sales       | 50000  | 2          |
| Sales       | 50000  | 2          |
| Sales       | 30000  | 3          |
| Engineering | 90000  | 1          |
| Engineering | 80000  | 2          |
+-------------+--------+------------+

ntile

window
ntile(expression)

Integer ranging from 1 to the argument value, dividing the partition as equally as possible

expression

An integer describing the number groups the partition should be split into

Example
-- Example usage of the ntile window function:
SELECT employee_id,
    salary,
    ntile(4) OVER (ORDER BY salary DESC) AS quartile
FROM employees;

+-------------+--------+----------+
| employee_id | salary | quartile |
+-------------+--------+----------+
| 1           | 90000  | 1        |
| 2           | 85000  | 1        |
| 3           | 80000  | 2        |
| 4           | 70000  | 2        |
| 5           | 60000  | 3        |
| 6           | 50000  | 3        |
| 7           | 40000  | 4        |
| 8           | 30000  | 4        |
+-------------+--------+----------+

percent_rank

window
percent_rank()

Returns the percentage rank of the current row within its partition. The value ranges from 0 to 1 and is computed as (rank - 1) / (total_rows - 1).

Example
    -- Example usage of the percent_rank window function:
SELECT employee_id,
    salary,
    percent_rank() OVER (ORDER BY salary) AS percent_rank
FROM employees;

+-------------+--------+---------------+
| employee_id | salary | percent_rank  |
+-------------+--------+---------------+
| 1           | 30000  | 0.00          |
| 2           | 50000  | 0.50          |
| 3           | 70000  | 1.00          |
+-------------+--------+---------------+

rank

window
rank()

Returns the rank of the current row within its partition, allowing gaps between ranks. This function provides a ranking similar to row_number, but skips ranks for identical values.

Example
-- Example usage of the rank window function:
SELECT department,
    salary,
    rank() OVER (PARTITION BY department ORDER BY salary DESC) AS rank
FROM employees;

+-------------+--------+------+
| department  | salary | rank |
+-------------+--------+------+
| Sales       | 70000  | 1    |
| Sales       | 50000  | 2    |
| Sales       | 50000  | 2    |
| Sales       | 30000  | 4    |
| Engineering | 90000  | 1    |
| Engineering | 80000  | 2    |
+-------------+--------+------+

row_number

window
row_number()

Number of the current row within its partition, counting from 1.

Example
-- Example usage of the row_number window function:
SELECT department,
  salary,
  row_number() OVER (PARTITION BY department ORDER BY salary DESC) AS row_num
FROM employees;

+-------------+--------+---------+
| department  | salary | row_num |
+-------------+--------+---------+
| Sales       | 70000  | 1       |
| Sales       | 50000  | 2       |
| Sales       | 50000  | 3       |
| Sales       | 30000  | 4       |
| Engineering | 90000  | 1       |
| Engineering | 80000  | 2       |
+-------------+--------+---------+

Regular Expression Functions 5

regexp_count

scalar
regexp_count(str, regexp[, start[, flags]])

Returns the number of matches that a regular expression has in a string.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

regexp

Regular expression to operate on. Can be a constant, column, or function, and any combination of operators.

start

Optional start position (the first position is 1) to search for the regular expression. Can be a constant, column, or function.

flags

Optional regular expression flags that control the behavior of the regular expression. Refer to the flags reference above for supported flags.

Example
> select regexp_count('abcAbAbc', 'abc', 2, 'i');
+---------------------------------------------------------------+
| regexp_count(Utf8("abcAbAbc"),Utf8("abc"),Int64(2),Utf8("i")) |
+---------------------------------------------------------------+
| 1                                                             |
+---------------------------------------------------------------+

regexp_instr

scalar
regexp_instr(str, regexp[, start[, N[, flags[, subexpr]]]])

Returns the position in a string where the specified occurrence of a POSIX regular expression is located.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

regexp

Regular expression to operate on. Can be a constant, column, or function, and any combination of operators.

start

Optional start position (the first position is 1) to search for the regular expression. Can be a constant, column, or function. Defaults to 1

N

Optional The N-th occurrence of pattern to find. Defaults to 1 (first match). Can be a constant, column, or function.

flags

Optional regular expression flags that control the behavior of the regular expression. Refer to the flags reference above for supported flags.

subexpr

Optional Specifies which capture group (subexpression) to return the position for. Defaults to 0, which returns the position of the entire match.

Example
> SELECT regexp_instr('ABCDEF', 'C(.)(..)');
+---------------------------------------------------------------+
| regexp_instr(Utf8("ABCDEF"),Utf8("C(.)(..)"))                 |
+---------------------------------------------------------------+
| 3                                                             |
+---------------------------------------------------------------+

regexp_like

scalar
regexp_like(str, regexp[, flags])

Returns true if a regular expression has at least one match in a string, false otherwise.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

regexp

Regular expression to operate on. Can be a constant, column, or function, and any combination of operators.

flags

Optional regular expression flags that control the behavior of the regular expression. Refer to the flags reference above for supported flags.

Example
select regexp_like('Köln', '[a-zA-Z]ö[a-zA-Z]{2}');
+--------------------------------------------------------+
| regexp_like(Utf8("Köln"),Utf8("[a-zA-Z]ö[a-zA-Z]{2}")) |
+--------------------------------------------------------+
| true                                                   |
+--------------------------------------------------------+
SELECT regexp_like('aBc', '(b|d)', 'i');
+--------------------------------------------------+
| regexp_like(Utf8("aBc"),Utf8("(b|d)"),Utf8("i")) |
+--------------------------------------------------+
| true                                             |
+--------------------------------------------------+

regexp_match

scalar
regexp_match(str, regexp[, flags])

Returns the first regular expression matches in a string.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

regexp

Regular expression to match against. Can be a constant, column, or function.

flags

Optional regular expression flags that control the behavior of the regular expression. Refer to the flags reference above for supported flags.

Example
> select regexp_match('Köln', '[a-zA-Z]ö[a-zA-Z]{2}');
+---------------------------------------------------------+
| regexp_match(Utf8("Köln"),Utf8("[a-zA-Z]ö[a-zA-Z]{2}")) |
+---------------------------------------------------------+
| [Köln]                                                  |
+---------------------------------------------------------+
SELECT regexp_match('aBc', '(b|d)', 'i');
+---------------------------------------------------+
| regexp_match(Utf8("aBc"),Utf8("(b|d)"),Utf8("i")) |
+---------------------------------------------------+
| [B]                                               |
+---------------------------------------------------+

regexp_replace

scalar
regexp_replace(str, regexp, replacement[, flags])

Replaces substrings in a string that match a regular expression.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

regexp

Regular expression to match against. Can be a constant, column, or function.

replacement

Replacement string expression to operate on. Can be a constant, column, or function, and any combination of operators.

flags

Optional regular expression flags that control the behavior of the regular expression. Refer to the flags reference above for supported flags.

Example
> select regexp_replace('foobarbaz', 'b(..)', 'X\\1Y', 'g');
+------------------------------------------------------------------------+
| regexp_replace(Utf8("foobarbaz"),Utf8("b(..)"),Utf8("X\1Y"),Utf8("g")) |
+------------------------------------------------------------------------+
| fooXarYXazY                                                            |
+------------------------------------------------------------------------+
SELECT regexp_replace('aBc', '(b|d)', 'Ab\\1a', 'i');
+-------------------------------------------------------------------+
| regexp_replace(Utf8("aBc"),Utf8("(b|d)"),Utf8("Ab\1a"),Utf8("i")) |
+-------------------------------------------------------------------+
| aAbBac                                                            |
+-------------------------------------------------------------------+

Statistical Functions 15

corr

aggregate
corr(expression1, expression2)

Returns the coefficient of correlation between two numeric values.

expression1

First expression to operate on. Can be a constant, column, or function, and any combination of operators.

expression2

Second expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT corr(column1, column2) FROM table_name;
+--------------------------------+
| corr(column1, column2)         |
+--------------------------------+
| 0.85                           |
+--------------------------------+

covar_pop

aggregate
covar_pop

Returns the population covariance of a set of number pairs.

expression1

First expression to operate on. Can be a constant, column, or function, and any combination of operators.

expression2

Second expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT covar_samp(column1, column2) FROM table_name;
+-----------------------------------+
| covar_samp(column1, column2)      |
+-----------------------------------+
| 8.25                              |
+-----------------------------------+

covar_samp

aggregate
covar_samp(expression1, expression2)

Returns the sample covariance of a set of number pairs.

expression1

First expression to operate on. Can be a constant, column, or function, and any combination of operators.

expression2

Second expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT covar_samp(column1, column2) FROM table_name;
+-----------------------------------+
| covar_samp(column1, column2)      |
+-----------------------------------+
| 8.25                              |
+-----------------------------------+

Also called covar.

nth_value

aggregate
nth_value(expression, n ORDER BY expression)

Returns the nth value in a group of values.

expression

The column or expression to retrieve the nth value from.

n

The position (nth) of the value to retrieve, based on the ordering.

Example
> SELECT dept_id, salary, NTH_VALUE(salary, 2) OVER (PARTITION BY dept_id ORDER BY salary ASC) AS second_salary_by_dept
  FROM employee;
+---------+--------+-------------------------+
| dept_id | salary | second_salary_by_dept   |
+---------+--------+-------------------------+
| 1       | 30000  | NULL                    |
| 1       | 40000  | 40000                   |
| 1       | 50000  | 40000                   |
| 2       | 35000  | NULL                    |
| 2       | 45000  | 45000                   |
+---------+--------+-------------------------+

regr_avgx

aggregate
regr_avgx(expression_y, expression_x)

Computes the average of the independent variable (input) expression_x for the non-null paired data points.

expression_y

Dependent variable expression to operate on. Can be a constant, column, or function, and any combination of operators.

expression_x

Independent variable expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
create table daily_sales(day int, total_sales int) as values (1,100), (2,150), (3,200), (4,NULL), (5,250);
select * from daily_sales;
+-----+-------------+
| day | total_sales |
| --- | ----------- |
| 1   | 100         |
| 2   | 150         |
| 3   | 200         |
| 4   | NULL        |
| 5   | 250         |
+-----+-------------+

SELECT regr_avgx(total_sales, day) AS avg_day FROM daily_sales;
+----------+
| avg_day  |
+----------+
|   2.75   |
+----------+

regr_avgy

aggregate
regr_avgy(expression_y, expression_x)

Computes the average of the dependent variable (output) expression_y for the non-null paired data points.

expression_y

Dependent variable expression to operate on. Can be a constant, column, or function, and any combination of operators.

expression_x

Independent variable expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
create table daily_temperature(day int, temperature int) as values (1,30), (2,32), (3, NULL), (4,35), (5,36);
select * from daily_temperature;
+-----+-------------+
| day | temperature |
| --- | ----------- |
| 1   | 30          |
| 2   | 32          |
| 3   | NULL        |
| 4   | 35          |
| 5   | 36          |
+-----+-------------+

-- temperature as Dependent Variable(Y), day as Independent Variable(X)
SELECT regr_avgy(temperature, day) AS avg_temperature FROM daily_temperature;
+-----------------+
| avg_temperature |
+-----------------+
| 33.25           |
+-----------------+

regr_count

aggregate
regr_count(expression_y, expression_x)

Counts the number of non-null paired data points.

expression_y

Dependent variable expression to operate on. Can be a constant, column, or function, and any combination of operators.

expression_x

Independent variable expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
create table daily_metrics(day int, user_signups int) as values (1,100), (2,120), (3, NULL), (4,110), (5,NULL);
select * from daily_metrics;
+-----+---------------+
| day | user_signups  |
| --- | ------------- |
| 1   | 100           |
| 2   | 120           |
| 3   | NULL          |
| 4   | 110           |
| 5   | NULL          |
+-----+---------------+

SELECT regr_count(user_signups, day) AS valid_pairs FROM daily_metrics;
+-------------+
| valid_pairs |
+-------------+
| 3           |
+-------------+

regr_intercept

aggregate
regr_intercept(expression_y, expression_x)

Computes the y-intercept of the linear regression line. For the equation (y = kx + b), this function returns b.

expression_y

Dependent variable expression to operate on. Can be a constant, column, or function, and any combination of operators.

expression_x

Independent variable expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
create table weekly_performance(week int, productivity_score int) as values (1,60), (2,65), (3, 70), (4,75), (5,80);
select * from weekly_performance;
+------+---------------------+
| week | productivity_score  |
| ---- | ------------------- |
| 1    | 60                  |
| 2    | 65                  |
| 3    | 70                  |
| 4    | 75                  |
| 5    | 80                  |
+------+---------------------+

SELECT regr_intercept(productivity_score, week) AS intercept FROM weekly_performance;
+----------+
|intercept|
|intercept |
+----------+
|  55      |
+----------+

regr_r2

aggregate
regr_r2(expression_y, expression_x)

Computes the square of the correlation coefficient between the independent and dependent variables.

expression_y

Dependent variable expression to operate on. Can be a constant, column, or function, and any combination of operators.

expression_x

Independent variable expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
create table weekly_performance(day int ,user_signups int) as values (1,60), (2,65), (3, 70), (4,75), (5,80);
select * from weekly_performance;
+-----+--------------+
| day | user_signups |
+-----+--------------+
| 1   | 60           |
| 2   | 65           |
| 3   | 70           |
| 4   | 75           |
| 5   | 80           |
+-----+--------------+

SELECT regr_r2(user_signups, day) AS r_squared FROM weekly_performance;
+---------+
|r_squared|
+---------+
| 1.0     |
+---------+

regr_slope

aggregate
regr_slope(expression_y, expression_x)

Returns the slope of the linear regression line for non-null pairs in aggregate columns. Given input column Y and X: regr_slope(Y, X) returns the slope (k in Y = k*X + b) using minimal RSS fitting.

expression_y

Dependent variable expression to operate on. Can be a constant, column, or function, and any combination of operators.

expression_x

Independent variable expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
create table weekly_performance(day int, user_signups int) as values (1,60), (2,65), (3, 70), (4,75), (5,80);
select * from weekly_performance;
+-----+--------------+
| day | user_signups |
+-----+--------------+
| 1   | 60           |
| 2   | 65           |
| 3   | 70           |
| 4   | 75           |
| 5   | 80           |
+-----+--------------+

SELECT regr_slope(user_signups, day) AS slope FROM weekly_performance;
+--------+
| slope  |
+--------+
| 5.0    |
+--------+

regr_sxx

aggregate
regr_sxx(expression_y, expression_x)

Computes the sum of squares of the independent variable.

expression_y

Dependent variable expression to operate on. Can be a constant, column, or function, and any combination of operators.

expression_x

Independent variable expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
create table study_hours(student_id int, hours int, test_score int) as values (1,2,55), (2,4,65), (3,6,75), (4,8,85), (5,10,95);
select * from study_hours;
+------------+-------+------------+
| student_id | hours | test_score |
+------------+-------+------------+
| 1          | 2     | 55         |
| 2          | 4     | 65         |
| 3          | 6     | 75         |
| 4          | 8     | 85         |
| 5          | 10    | 95         |
+------------+-------+------------+

SELECT regr_sxx(test_score, hours) AS sxx FROM study_hours;
+------+
| sxx  |
+------+
| 40.0 |
+------+

regr_sxy

aggregate
regr_sxy(expression_y, expression_x)

Computes the sum of products of paired data points.

expression_y

Dependent variable expression to operate on. Can be a constant, column, or function, and any combination of operators.

expression_x

Independent variable expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
create table employee_productivity(week int, productivity_score int) as values(1,60), (2,65), (3,70);
select * from employee_productivity;
+------+--------------------+
| week | productivity_score |
+------+--------------------+
| 1    | 60                 |
| 2    | 65                 |
| 3    | 70                 |
+------+--------------------+

SELECT regr_sxy(productivity_score, week) AS sum_product_deviations FROM employee_productivity;
+------------------------+
| sum_product_deviations |
+------------------------+
|       10.0             |
+------------------------+

regr_syy

aggregate
regr_syy(expression_y, expression_x)

Computes the sum of squares of the dependent variable.

expression_y

Dependent variable expression to operate on. Can be a constant, column, or function, and any combination of operators.

expression_x

Independent variable expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
create table employee_productivity(week int, productivity_score int) as values (1,60), (2,65), (3,70);
select * from employee_productivity;
+------+--------------------+
| week | productivity_score |
+------+--------------------+
| 1    | 60                 |
| 2    | 65                 |
| 3    | 70                 |
+------+--------------------+

SELECT regr_syy(productivity_score, week) AS sum_squares_y FROM employee_productivity;
+---------------+
| sum_squares_y |
+---------------+
|    50.0       |
+---------------+

stddev

aggregate
stddev(expression)

Returns the standard deviation of a set of numbers.

expression

The expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT stddev(column_name) FROM table_name;
+----------------------+
| stddev(column_name)   |
+----------------------+
| 12.34                |
+----------------------+

Also called stddev_samp.

stddev_pop

aggregate
stddev_pop(expression)

Returns the population standard deviation of a set of numbers.

expression

The expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> SELECT stddev_pop(column_name) FROM table_name;
+--------------------------+
| stddev_pop(column_name)   |
+--------------------------+
| 10.56                    |
+--------------------------+

String Functions 33

ascii

scalar
ascii(str)

Returns the first Unicode scalar value of a string.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> select ascii('abc');
+--------------------+
| ascii(Utf8("abc")) |
+--------------------+
| 97                 |
+--------------------+
> select ascii('🚀');
+-------------------+
| ascii(Utf8("🚀")) |
+-------------------+
| 128640            |
+-------------------+

Related: chr.

bit_length

scalar
bit_length(str)

Returns the bit length of a string.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

Related: length, octet_length.

btrim

scalar
btrim(str[, trim_str])

Trims the specified trim string from the start and end of a string. If no trim string is provided, all spaces are removed from the start and end of the input string.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

trim_str

String expression to operate on. Can be a constant, column, or function, and any combination of operators. Default is a space.

Also written:

trim(BOTH trim_str FROM str)
trim(trim_str FROM str)

Also called trim. Related: ltrim, rtrim.

character_length

scalar
character_length(str)

Returns the number of characters in a string.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> select character_length('Ångström');
+------------------------------------+
| character_length(Utf8("Ångström")) |
+------------------------------------+
| 8                                  |
+------------------------------------+

Also called length, char_length. Related: bit_length, octet_length.

chr

scalar
chr(expression)

Returns a string containing the character with the specified Unicode scalar value.

expression

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> select chr(128640);
+--------------------+
| chr(Int64(128640)) |
+--------------------+
| 🚀                 |
+--------------------+

Related: ascii.

concat

scalar
concat(str[, ..., str_n])

Concatenates multiple strings together.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

str_n

Subsequent string expressions to concatenate.

Related: concat_ws.

concat_ws

scalar
concat_ws(separator, str[, ..., str_n])

Concatenates multiple strings together with a specified separator.

separator

Separator to insert between concatenated strings.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

str_n

Subsequent string expressions to concatenate.

Example
> select concat_ws('_', 'data', 'fusion');
+--------------------------------------------------+
| concat_ws(Utf8("_"),Utf8("data"),Utf8("fusion")) |
+--------------------------------------------------+
| data_fusion                                      |
+--------------------------------------------------+

Related: concat.

contains

scalar
contains(str, search_str)

Return true if search_str is found within string (case-sensitive).

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

search_str

The string to search for in str.

Example
> select contains('the quick brown fox', 'row');
+---------------------------------------------------+
| contains(Utf8("the quick brown fox"),Utf8("row")) |
+---------------------------------------------------+
| true                                              |
+---------------------------------------------------+

ends_with

scalar
ends_with(str, substr)

Tests if a string ends with a substring.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

substr

Substring to test for.

find_in_set

scalar
find_in_set(str, strlist)

Returns a value in the range of 1 to N if the string str is in the string list strlist consisting of N substrings.

str

String expression to find in strlist.

strlist

A string list is a string composed of substrings separated by , characters.

Example
> select find_in_set('b', 'a,b,c,d');
+----------------------------------------+
| find_in_set(Utf8("b"),Utf8("a,b,c,d")) |
+----------------------------------------+
| 2                                      |
+----------------------------------------+

initcap

scalar
initcap(str)

Capitalizes the first character in each word in the input string. Words are delimited by non-alphanumeric characters.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

Related: lower, upper.

left

scalar
left(str, n)

Returns a specified number of characters from the left side of a string.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

n

Number of characters to return.

Related: right.

levenshtein

scalar
levenshtein(str1, str2)

Returns the Levenshtein distance between the two given strings.

str1

String expression to compute Levenshtein distance with str2.

str2

String expression to compute Levenshtein distance with str1.

Example
> select levenshtein('kitten', 'sitting');
+---------------------------------------------+
| levenshtein(Utf8("kitten"),Utf8("sitting")) |
+---------------------------------------------+
| 3                                           |
+---------------------------------------------+

lower

scalar
lower(str)

Converts a string to lower-case.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> select lower('Ångström');
+-------------------------+
| lower(Utf8("Ångström")) |
+-------------------------+
| ångström                |
+-------------------------+

Related: initcap, upper.

lpad

scalar
lpad(str, n[, padding_str])

Pads the left side of a string with another string to a specified string length.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

n

String length to pad to. If the input string is longer than this length, it is truncated (on the right).

padding_str

Optional string expression to pad with. Can be a constant, column, or function, and any combination of string operators. Default is a space.

Example
> select lpad('Dolly', 10, 'hello');
+---------------------------------------------+
| lpad(Utf8("Dolly"),Int64(10),Utf8("hello")) |
+---------------------------------------------+
| helloDolly                                  |
+---------------------------------------------+

Related: rpad.

ltrim

scalar
ltrim(str[, trim_str])

Trims the specified trim string from the beginning of a string. If no trim string is provided, spaces are removed from the start of the input string.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

trim_str

String expression to trim from the beginning of the input string. Can be a constant, column, or function, and any combination of arithmetic operators. Default is a space.

Also written:

trim(LEADING trim_str FROM str)

Related: btrim, rtrim.

octet_length

scalar
octet_length(str)

Returns the length of a string in bytes.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> select octet_length('Ångström');
+--------------------------------+
| octet_length(Utf8("Ångström")) |
+--------------------------------+
| 10                             |
+--------------------------------+

Related: bit_length, length.

overlay

scalar
overlay(str PLACING substr FROM pos [FOR count])

Returns the string which is replaced by another string from the specified position and specified count length.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

substr

Substring to replace in str.

pos

The start position to start the replace in str.

count

The count of characters to be replaced from start position of str. If not specified, will use substr length instead.

Example
> select overlay('Txxxxas' placing 'hom' from 2 for 4);
+--------------------------------------------------------+
| overlay(Utf8("Txxxxas"),Utf8("hom"),Int64(2),Int64(4)) |
+--------------------------------------------------------+
| Thomas                                                 |
+--------------------------------------------------------+

repeat

scalar
repeat(str, n)

Returns a string with an input string repeated a specified number.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

n

Number of times to repeat the input string.

Example
> select repeat('data', 3);
+-------------------------------+
| repeat(Utf8("data"),Int64(3)) |
+-------------------------------+
| datadatadata                  |
+-------------------------------+

replace

scalar
replace(str, substr, replacement)

Replaces all occurrences of a specified substring in a string with a new substring.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

substr

Substring expression to replace in the input string. Substring expression to operate on. Can be a constant, column, or function, and any combination of operators.

replacement

Replacement substring expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> select replace('ABabbaBA', 'ab', 'cd');
+-------------------------------------------------+
| replace(Utf8("ABabbaBA"),Utf8("ab"),Utf8("cd")) |
+-------------------------------------------------+
| ABcdbaBA                                        |
+-------------------------------------------------+

reverse

scalar
reverse(str)

Reverses the character order of a string.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

right

scalar
right(str, n)

Returns a specified number of characters from the right side of a string.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

n

Number of characters to return.

Related: left.

rpad

scalar
rpad(str, n[, padding_str])

Pads the right side of a string with another string to a specified string length.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

n

String length to pad to. If the input string is longer than this length, it is truncated.

padding_str

String expression to pad with. Can be a constant, column, or function, and any combination of string operators. Default is a space.

Related: lpad.

rtrim

scalar
rtrim(str[, trim_str])

Trims the specified trim string from the end of a string. If no trim string is provided, all spaces are removed from the end of the input string.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

trim_str

String expression to trim from the end of the input string. Can be a constant, column, or function, and any combination of arithmetic operators. Default is a space.

Also written:

trim(TRAILING trim_str FROM str)

Related: btrim, ltrim.

split_part

scalar
split_part(str, delimiter, pos)

Splits a string based on a specified delimiter and returns the substring in the specified position.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

delimiter

String or character to split on.

pos

Position of the part to return (counting from 1). Negative values count backward from the end of the string.

Example
> select split_part('1.2.3.4.5', '.', 3);
+--------------------------------------------------+
| split_part(Utf8("1.2.3.4.5"),Utf8("."),Int64(3)) |
+--------------------------------------------------+
| 3                                                |
+--------------------------------------------------+

starts_with

scalar
starts_with(str, substr)

Tests if a string starts with a substring.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

substr

Substring to test for.

strpos

scalar
strpos(str, substr)

Returns the starting position of a specified substring in a string. Positions begin at 1. If the substring does not exist in the string, the function returns 0.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

substr

Substring expression to search for.

Also written:

position(substr in origstr)

Also called instr, position.

substr

scalar
substr(str, start_pos[, length])

Extracts a substring of a specified number of characters from a specific starting position in a string.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

start_pos

Character position to start the substring at. The first character in the string has a position of 1. If the start position is less than 1, it is treated as if it is before the start of the string and the (absolute) number of characters before position 1 is subtracted from length (if given). For example, substr('abc', -3, 6) returns 'ab'.

length

Number of characters to extract. If not specified, returns the rest of the string after the start position.

Also written:

substring(str from start_pos for length)

Also called substring.

substr_index

scalar
substr_index(str, delim, count)

Returns the substring from str before count occurrences of the delimiter delim. If count is positive, everything to the left of the final delimiter (counting from the left) is returned. If count is negative, everything to the right of the final delimiter (counting from the right) is returned.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

delim

The string to find in str to split str.

count

The number of times to search for the delimiter. Can be either a positive or negative number.

Example
> select substr_index('www.apache.org', '.', 1);
+---------------------------------------------------------+
| substr_index(Utf8("www.apache.org"),Utf8("."),Int64(1)) |
+---------------------------------------------------------+
| www                                                     |
+---------------------------------------------------------+
> select substr_index('www.apache.org', '.', -1);
+----------------------------------------------------------+
| substr_index(Utf8("www.apache.org"),Utf8("."),Int64(-1)) |
+----------------------------------------------------------+
| org                                                      |
+----------------------------------------------------------+

Also called substring_index.

to_hex

scalar
to_hex(int)

Converts an integer to a hexadecimal string.

int

Integer expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> select to_hex(12345689);
+-------------------------+
| to_hex(Int64(12345689)) |
+-------------------------+
| bc6159                  |
+-------------------------+

translate

scalar
translate(str, from, to)

Performs character-wise substitution based on a mapping.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

from

The characters to be replaced.

to

The characters to replace them with. Each character in from that is found in str is replaced by the character at the same index in to. Any characters in from that don't have a corresponding character in to are removed. If a character appears more than once in from, the first occurrence determines the mapping.

Example
> select translate('twice', 'wic', 'her');
+--------------------------------------------------+
| translate(Utf8("twice"),Utf8("wic"),Utf8("her")) |
+--------------------------------------------------+
| there                                            |
+--------------------------------------------------+

upper

scalar
upper(str)

Converts a string to upper-case.

str

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

Related: initcap, lower.

uuid

scalar
uuid()

Returns UUID v4 string value which is unique per row.

Example
> select uuid();
+--------------------------------------+
| uuid()                               |
+--------------------------------------+
| 6ec17ef8-1934-41cc-8d59-d0c8f9eea1f0 |
+--------------------------------------+

Struct Functions 2

named_struct

scalar
named_struct(expression1_name, expression1_input[, ..., expression_n_name, expression_n_input])

Returns a struct using the specified name and input expressions pairs. For information on comparing and ordering struct values (including NULL handling), see Comparison and Ordering.

expression_n_name

Name of the column field. Must be a constant string.

expression_n_input

Expression to include in the output struct. Can be a constant, column, or function, and any combination of arithmetic or string operators.

Example
> select * from t;
+---+---+
| a | b |
+---+---+
| 1 | 2 |
| 3 | 4 |
+---+---+
> select named_struct('field_a', a, 'field_b', b) from t;
+-------------------------------------------------------+
| named_struct(Utf8("field_a"),t.a,Utf8("field_b"),t.b) |
+-------------------------------------------------------+
| {field_a: 1, field_b: 2}                              |
| {field_a: 3, field_b: 4}                              |
+-------------------------------------------------------+

struct

scalar
struct(expression1[, ..., expression_n])

Returns a struct using the specified input expressions optionally named. Fields in the returned struct use the optional name or the cN naming convention. For example: c0, c1, c2, etc. For information on comparing and ordering struct values (including NULL handling), see Comparison and Ordering.

expression1, expression_n

Expression to include in the output struct. Can be a constant, column, or function, any combination of arithmetic or string operators.

Example
> select * from t;
+---+---+
| a | b |
+---+---+
| 1 | 2 |
| 3 | 4 |
+---+---+

-- use default names `c0`, `c1`
> select struct(a, b) from t;
+-----------------+
| struct(t.a,t.b) |
+-----------------+
| {c0: 1, c1: 2}  |
| {c0: 3, c1: 4}  |
+-----------------+

-- name the first field `field_a`
select struct(a as field_a, b) from t;
+--------------------------------------------------+
| named_struct(Utf8("field_a"),t.a,Utf8("c1"),t.b) |
+--------------------------------------------------+
| {field_a: 1, c1: 2}                              |
| {field_a: 3, c1: 4}                              |
+--------------------------------------------------+

Also called row.

Time and Date Functions 19

current_date

scalar
current_date()

Returns the current date in the session time zone. The current_date() return value is determined at query time and will return the same date, no matter when in the query plan the function executes.

Also called today.

current_time

scalar
current_time()

Returns the current time in the session time zone. The current_time() return value is determined at query time and will return the same time, no matter when in the query plan the function executes. The time zone can be a value like +00:00, 'Europe/London' etc.

date_bin

scalar
date_bin(interval, expression[, origin_timestamp])

Calculates time intervals and returns the start of the interval nearest to the specified timestamp. Use date_bin to downsample time series data by grouping rows into time-based "bins" or "windows" and applying an aggregate or selector function to each window. For example, if you "bin" or "window" data into 15 minute intervals, an input timestamp of 2023-01-01T18:18:18Z will be updated to the start time of the 15 minute bin it is in: 2023-01-01T18:15:00Z.

interval

Bin interval.

expression

Time expression to operate on. Can be a constant, column, or function.

origin_timestamp

Optional. Starting point used to determine bin boundaries. If not specified defaults 1970-01-01T00:00:00Z (the UNIX epoch in UTC). The following intervals are supported:

  • nanoseconds
  • microseconds
  • milliseconds
  • seconds
  • minutes
  • hours
  • days
  • weeks
  • months
  • years
  • century
Example
-- Bin the timestamp into 1 day intervals
> SELECT date_bin(interval '1 day', time) as bin
FROM VALUES ('2023-01-01T18:18:18Z'), ('2023-01-03T19:00:03Z')  t(time);
+---------------------+
| bin                 |
+---------------------+
| 2023-01-01T00:00:00 |
| 2023-01-03T00:00:00 |
+---------------------+
2 row(s) fetched.

-- Bin the timestamp into 1 day intervals starting at 3AM on  2023-01-01
> SELECT date_bin(interval '1 day', time,  '2023-01-01T03:00:00') as bin
FROM VALUES ('2023-01-01T18:18:18Z'), ('2023-01-03T19:00:03Z')  t(time);
+---------------------+
| bin                 |
+---------------------+
| 2023-01-01T03:00:00 |
| 2023-01-03T03:00:00 |
+---------------------+
2 row(s) fetched.

-- Bin the time into 15 minute intervals starting at 1 min
>  SELECT date_bin(interval '15 minutes', time, TIME '00:01:00') as bin
FROM VALUES (TIME '02:18:18'), (TIME '19:00:03')  t(time);
+----------+
| bin      |
+----------+
| 02:16:00 |
| 18:46:00 |
+----------+
2 row(s) fetched.

date_part

scalar
date_part(part, expression)

Returns the specified part of the date as an integer.

part

Part of the date to return. The following date parts are supported:

  • year
  • isoyear (ISO 8601 week-numbering year)
  • quarter (emits value in inclusive range [1, 4] based on which quartile of the year the date is in)
  • month
  • week (week of the year)
  • day (day of the month)
  • hour
  • minute
  • second
  • millisecond
  • microsecond
  • nanosecond
  • dow (day of the week where Sunday is 0)
  • doy (day of the year)
  • epoch (seconds since Unix epoch for timestamps/dates, total seconds for intervals)
  • isodow (ISO 8601 day of the week where Monday is 1 and Sunday is 7)
expression

Time expression to operate on. Can be a constant, column, or function.

Also written:

extract(field FROM source)
Example
> SELECT date_part('year', '2024-05-01T00:00:00');
+-----------------------------------------------------+
| date_part(Utf8("year"),Utf8("2024-05-01T00:00:00")) |
+-----------------------------------------------------+
| 2024                                                |
+-----------------------------------------------------+
> SELECT extract(day FROM timestamp '2024-05-01T00:00:00');
+----------------------------------------------------+
| date_part(Utf8("DAY"),Utf8("2024-05-01T00:00:00")) |
+----------------------------------------------------+
| 1                                                  |
+----------------------------------------------------+

Also called datepart.

date_trunc

scalar
date_trunc(precision, expression)

Truncates a timestamp or time value to a specified precision.

precision

Time precision to truncate to. The following precisions are supported:

For Timestamp types:

  • year / YEAR
  • quarter / QUARTER
  • month / MONTH
  • week / WEEK
  • day / DAY
  • hour / HOUR
  • minute / MINUTE
  • second / SECOND
  • millisecond / MILLISECOND
  • microsecond / MICROSECOND

For Time types (hour, minute, second, millisecond, microsecond only):

  • hour / HOUR
  • minute / MINUTE
  • second / SECOND
  • millisecond / MILLISECOND
  • microsecond / MICROSECOND
expression

Timestamp or time expression to operate on. Can be a constant, column, or function.

Example
> SELECT date_trunc('month', '2024-05-15T10:30:00');
+-----------------------------------------------+
| date_trunc(Utf8("month"),Utf8("2024-05-15T10:30:00")) |
+-----------------------------------------------+
| 2024-05-01T00:00:00                           |
+-----------------------------------------------+
> SELECT date_trunc('hour', '2024-05-15T10:30:00');
+----------------------------------------------+
| date_trunc(Utf8("hour"),Utf8("2024-05-15T10:30:00")) |
+----------------------------------------------+
| 2024-05-15T10:00:00                          |
+----------------------------------------------+

Also called datetrunc.

from_unixtime

scalar
from_unixtime(expression[, timezone])

Converts an integer to RFC3339 timestamp format (YYYY-MM-DDT00:00:00.000000000Z). Integers and unsigned integers are interpreted as seconds since the unix epoch (1970-01-01T00:00:00Z) return the corresponding timestamp.

expression

The expression to operate on. Can be a constant, column, or function, and any combination of operators.

timezone

Optional timezone to use when converting the integer to a timestamp. If not provided, the default timezone is UTC.

Example
> select from_unixtime(1599572549, 'America/New_York');
+-----------------------------------------------------------+
| from_unixtime(Int64(1599572549),Utf8("America/New_York")) |
+-----------------------------------------------------------+
| 2020-09-08T09:42:29-04:00                                 |
+-----------------------------------------------------------+

make_date

scalar
make_date(year, month, day)

Make a date from year/month/day component parts.

year

Year to use when making the date. Can be a constant, column or function, and any combination of arithmetic operators.

month

Month to use when making the date. Can be a constant, column or function, and any combination of arithmetic operators.

day

Day to use when making the date. Can be a constant, column or function, and any combination of arithmetic operators.

Example
> select make_date(2023, 1, 31);
+-------------------------------------------+
| make_date(Int64(2023),Int64(1),Int64(31)) |
+-------------------------------------------+
| 2023-01-31                                |
+-------------------------------------------+
> select make_date('2023', '01', '31');
+-----------------------------------------------+
| make_date(Utf8("2023"),Utf8("01"),Utf8("31")) |
+-----------------------------------------------+
| 2023-01-31                                    |
+-----------------------------------------------+

make_time

scalar
make_time(hour, minute, second)

Make a time from hour/minute/second component parts.

hour

Hour to use when making the time. Can be a constant, column or function, and any combination of arithmetic operators.

minute

Minute to use when making the time. Can be a constant, column or function, and any combination of arithmetic operators.

second

Second to use when making the time. Can be a constant, column or function, and any combination of arithmetic operators.

Example
> select make_time(13, 23, 1);
+-------------------------------------------+
| make_time(Int64(13),Int64(23),Int64(1))   |
+-------------------------------------------+
| 13:23:01                                  |
+-------------------------------------------+
> select make_time('23', '01', '31');
+-----------------------------------------------+
| make_time(Utf8("23"),Utf8("01"),Utf8("31"))   |
+-----------------------------------------------+
| 23:01:31                                      |
+-----------------------------------------------+

now

scalar
now()

Returns the current timestamp in the system configured timezone (None by default). The now() return value is determined at query time and will return the same timestamp, no matter when in the query plan the function executes.

Also called current_timestamp.

to_char

scalar
to_char(expression, format)

Returns a string representation of a date, time, timestamp or duration based on a strftime format. Unlike the PostgreSQL equivalent of this function numerical formatting is not supported.

expression

Expression to operate on. Can be a constant, column, or function that results in a date, time, timestamp or duration.

format

A strftime format string to use to convert the expression.

Example
> select to_char('2023-03-01'::date, '%d-%m-%Y');
+----------------------------------------------+
| to_char(Utf8("2023-03-01"),Utf8("%d-%m-%Y")) |
+----------------------------------------------+
| 01-03-2023                                   |
+----------------------------------------------+

Also called date_format.

to_date

scalar
to_date(expression[, format1, ..., format_n])

Converts a value to a date (YYYY-MM-DD). Supports strings, numeric and timestamp types as input. Strings are parsed as YYYY-MM-DD (e.g. '2023-07-20') if no strftime formats are provided. Integers and doubles are interpreted as days since the unix epoch (1970-01-01T00:00:00Z). Returns the corresponding date. Note: to_date returns Date32, which represents its values as the number of days since unix epoch(1970-01-01) stored as signed 32 bit value. The largest supported date value is 9999-12-31.

expression

String expression to operate on. Can be a constant, column, or function, and any combination of operators.

format_n

Optional strftime format strings to use to parse the expression. Formats will be tried in the order they appear with the first successful one being returned. If none of the formats successfully parse the expression an error will be returned. NULL formats are skipped. If every format is NULL the result is NULL.

Example
> select to_date('2023-01-31');
+-------------------------------+
| to_date(Utf8("2023-01-31")) |
+-------------------------------+
| 2023-01-31                    |
+-------------------------------+
> select to_date('2023/01/31', '%Y-%m-%d', '%Y/%m/%d');
+---------------------------------------------------------------------+
| to_date(Utf8("2023/01/31"),Utf8("%Y-%m-%d"),Utf8("%Y/%m/%d")) |
+---------------------------------------------------------------------+
| 2023-01-31                                                          |
+---------------------------------------------------------------------+

to_local_time

scalar
to_local_time(expression)

Converts a timestamp with a timezone to a timestamp without a timezone (with no offset or timezone information). This function handles daylight saving time changes.

expression

Time expression to operate on. Can be a constant, column, or function.

Example
> SELECT to_local_time('2024-04-01T00:00:20Z'::timestamp);
+---------------------------------------------+
| to_local_time(Utf8("2024-04-01T00:00:20Z")) |
+---------------------------------------------+
| 2024-04-01T00:00:20                         |
+---------------------------------------------+

> SELECT to_local_time('2024-04-01T00:00:20Z'::timestamp AT TIME ZONE 'Europe/Brussels');
+---------------------------------------------+
| to_local_time(Utf8("2024-04-01T00:00:20Z")) |
+---------------------------------------------+
| 2024-04-01T00:00:20                         |
+---------------------------------------------+

> SELECT
  time,
  arrow_typeof(time) as type,
  to_local_time(time) as to_local_time,
  arrow_typeof(to_local_time(time)) as to_local_time_type
FROM (
  SELECT '2024-04-01T00:00:20Z'::timestamp AT TIME ZONE 'Europe/Brussels' AS time
);
+---------------------------+----------------------------------+---------------------+--------------------+
| time                      | type                             | to_local_time       | to_local_time_type |
+---------------------------+----------------------------------+---------------------+--------------------+
| 2024-04-01T00:00:20+02:00 | Timestamp(ns, "Europe/Brussels") | 2024-04-01T00:00:20 | Timestamp(ns)      |
+---------------------------+----------------------------------+---------------------+--------------------+

# combine `to_local_time()` with `date_bin()` to bin on boundaries in the timezone rather
# than UTC boundaries

> SELECT date_bin(interval '1 day', to_local_time('2024-04-01T00:00:20Z'::timestamp AT TIME ZONE 'Europe/Brussels')) AS date_bin;
+---------------------+
| date_bin            |
+---------------------+
| 2024-04-01T00:00:00 |
+---------------------+

> SELECT date_bin(interval '1 day', to_local_time('2024-04-01T00:00:20Z'::timestamp AT TIME ZONE 'Europe/Brussels')) AT TIME ZONE 'Europe/Brussels' AS date_bin_with_timezone;
+---------------------------+
| date_bin_with_timezone    |
+---------------------------+
| 2024-04-01T00:00:00+02:00 |
+---------------------------+

to_time

scalar
to_time(expression[, format1, ..., format_n])

Converts a value to a time (HH:MM:SS.nnnnnnnnn). Supports strings and timestamps as input. Strings are parsed as HH:MM:SS, HH:MM:SS.nnnnnnnnn, or HH:MM if no strftime formats are provided. Timestamps will have the time portion extracted. Returns the corresponding time. Note: to_time returns Time64(Nanosecond), which represents the time of day in nanoseconds since midnight.

expression

String or Timestamp expression to operate on. Can be a constant, column, or function, and any combination of operators.

format_n

Optional strftime format strings to use to parse the expression. Formats will be tried in the order they appear with the first successful one being returned. If none of the formats successfully parse the expression an error will be returned.

Example
> select to_time('12:30:45');
+---------------------------+
| to_time(Utf8("12:30:45")) |
+---------------------------+
| 12:30:45                  |
+---------------------------+
> select to_time('12-30-45', '%H-%M-%S');
+--------------------------------------------+
| to_time(Utf8("12-30-45"),Utf8("%H-%M-%S")) |
+--------------------------------------------+
| 12:30:45                                   |
+--------------------------------------------+
> select to_time('2024-01-15 14:30:45'::timestamp);
+--------------------------------------------------+
| to_time(Utf8("2024-01-15 14:30:45"))             |
+--------------------------------------------------+
| 14:30:45                                         |
+--------------------------------------------------+

to_timestamp

scalar
to_timestamp(expression[, ..., format_n])

Converts a value to a timestamp (YYYY-MM-DDT00:00:00.000000<TZ>) in the session time zone. Supports strings, integer, unsigned integer, and double types as input. Strings are parsed as RFC3339 (e.g. '2023-07-20T05:44:00') if no strftime formats are provided. Strings that parse without a time zone are treated as if they are in the session time zone, or UTC if no session time zone is set. Integers, unsigned integers, and doubles are interpreted as seconds since the unix epoch (1970-01-01T00:00:00Z). Note: to_timestamp returns Timestamp(ns, TimeZone) where the time zone is the session time zone. The supported range for integer input is between-9223372037 and 9223372036. Supported range for string input is between 1677-09-21T00:12:44.0 and 2262-04-11T23:47:16.0. Please use to_timestamp_seconds for the input outside of supported bounds. The session time zone can be set using the statement SET TIMEZONE = 'desired time zone'. The time zone can be a value like +00:00, 'Europe/London' etc.

expression

Expression to operate on. Can be a constant, column, or function, and any combination of arithmetic operators.

format_n

Optional strftime format strings to use to parse the expression. Formats will be tried in the order they appear with the first successful one being returned. If none of the formats successfully parse the expression an error will be returned. NULL formats are skipped. If every format is NULL the result is NULL. Note: parsing of named timezones (e.g. 'America/New_York') using %Z is only supported at the end of the string preceded by a space.

Example
> select to_timestamp('2023-01-31T09:26:56.123456789-05:00');
+-----------------------------------------------------------+
| to_timestamp(Utf8("2023-01-31T09:26:56.123456789-05:00")) |
+-----------------------------------------------------------+
| 2023-01-31T14:26:56.123456789                             |
+-----------------------------------------------------------+
> select to_timestamp('03:59:00.123456789 05-17-2023', '%c', '%+', '%H:%M:%S%.f %m-%d-%Y');
+--------------------------------------------------------------------------------------------------------+
| to_timestamp(Utf8("03:59:00.123456789 05-17-2023"),Utf8("%c"),Utf8("%+"),Utf8("%H:%M:%S%.f %m-%d-%Y")) |
+--------------------------------------------------------------------------------------------------------+
| 2023-05-17T03:59:00.123456789                                                                          |
+--------------------------------------------------------------------------------------------------------+

to_timestamp_micros

scalar
to_timestamp_micros(expression[, ..., format_n])

Converts a value to a timestamp (YYYY-MM-DDT00:00:00.000000<TZ>) in the session time zone. Supports strings, integer, unsigned integer, and double types as input. Strings are parsed as RFC3339 (e.g. '2023-07-20T05:44:00') if no strftime formats are provided. Strings that parse without a time zone are treated as if they are in the session time zone, or UTC if no session time zone is set. Integers, unsigned integers, and doubles are interpreted as microseconds since the unix epoch (1970-01-01T00:00:00Z). The session time zone can be set using the statement SET TIMEZONE = 'desired time zone'. The time zone can be a value like +00:00, 'Europe/London' etc.

expression

Expression to operate on. Can be a constant, column, or function, and any combination of arithmetic operators.

format_n

Optional strftime format strings to use to parse the expression. Formats will be tried in the order they appear with the first successful one being returned. If none of the formats successfully parse the expression an error will be returned. NULL formats are skipped. If every format is NULL the result is NULL. Note: parsing of named timezones (e.g. 'America/New_York') using %Z is only supported at the end of the string preceded by a space.

Example
> select to_timestamp_micros('2023-01-31T09:26:56.123456789-05:00');
+------------------------------------------------------------------+
| to_timestamp_micros(Utf8("2023-01-31T09:26:56.123456789-05:00")) |
+------------------------------------------------------------------+
| 2023-01-31T14:26:56.123456                                       |
+------------------------------------------------------------------+
> select to_timestamp_micros('03:59:00.123456789 05-17-2023', '%c', '%+', '%H:%M:%S%.f %m-%d-%Y');
+---------------------------------------------------------------------------------------------------------------+
| to_timestamp_micros(Utf8("03:59:00.123456789 05-17-2023"),Utf8("%c"),Utf8("%+"),Utf8("%H:%M:%S%.f %m-%d-%Y")) |
+---------------------------------------------------------------------------------------------------------------+
| 2023-05-17T03:59:00.123456                                                                                    |
+---------------------------------------------------------------------------------------------------------------+

to_timestamp_millis

scalar
to_timestamp_millis(expression[, ..., format_n])

Converts a value to a timestamp (YYYY-MM-DDT00:00:00.000<TZ>) in the session time zone. Supports strings, integer, unsigned integer, and double types as input. Strings are parsed as RFC3339 (e.g. '2023-07-20T05:44:00') if no strftime formats are provided. Strings that parse without a time zone are treated as if they are in the session time zone, or UTC if no session time zone is set. Integers, unsigned integers, and doubles are interpreted as milliseconds since the unix epoch (1970-01-01T00:00:00Z). The session time zone can be set using the statement SET TIMEZONE = 'desired time zone'. The time zone can be a value like +00:00, 'Europe/London' etc.

expression

Expression to operate on. Can be a constant, column, or function, and any combination of arithmetic operators.

format_n

Optional strftime format strings to use to parse the expression. Formats will be tried in the order they appear with the first successful one being returned. If none of the formats successfully parse the expression an error will be returned. NULL formats are skipped. If every format is NULL the result is NULL. Note: parsing of named timezones (e.g. 'America/New_York') using %Z is only supported at the end of the string preceded by a space.

Example
> select to_timestamp_millis('2023-01-31T09:26:56.123456789-05:00');
+------------------------------------------------------------------+
| to_timestamp_millis(Utf8("2023-01-31T09:26:56.123456789-05:00")) |
+------------------------------------------------------------------+
| 2023-01-31T14:26:56.123                                          |
+------------------------------------------------------------------+
> select to_timestamp_millis('03:59:00.123456789 05-17-2023', '%c', '%+', '%H:%M:%S%.f %m-%d-%Y');
+---------------------------------------------------------------------------------------------------------------+
| to_timestamp_millis(Utf8("03:59:00.123456789 05-17-2023"),Utf8("%c"),Utf8("%+"),Utf8("%H:%M:%S%.f %m-%d-%Y")) |
+---------------------------------------------------------------------------------------------------------------+
| 2023-05-17T03:59:00.123                                                                                       |
+---------------------------------------------------------------------------------------------------------------+

to_timestamp_nanos

scalar
to_timestamp_nanos(expression[, ..., format_n])

Converts a value to a timestamp (YYYY-MM-DDT00:00:00.000000000<TZ>) in the session time zone. Supports strings, integer, unsigned integer, and double types as input. Strings are parsed as RFC3339 (e.g. '2023-07-20T05:44:00') if no strftime formats are provided. Strings that parse without a time zone are treated as if they are in the session time zone. Integers, unsigned integers, and doubles are interpreted as nanoseconds since the unix epoch (1970-01-01T00:00:00Z). The session time zone can be set using the statement SET TIMEZONE = 'desired time zone'. The time zone can be a value like +00:00, 'Europe/London' etc.

expression

Expression to operate on. Can be a constant, column, or function, and any combination of arithmetic operators.

format_n

Optional strftime format strings to use to parse the expression. Formats will be tried in the order they appear with the first successful one being returned. If none of the formats successfully parse the expression an error will be returned. NULL formats are skipped. If every format is NULL the result is NULL. Note: parsing of named timezones (e.g. 'America/New_York') using %Z is only supported at the end of the string preceded by a space.

Example
> select to_timestamp_nanos('2023-01-31T09:26:56.123456789-05:00');
+-----------------------------------------------------------------+
| to_timestamp_nanos(Utf8("2023-01-31T09:26:56.123456789-05:00")) |
+-----------------------------------------------------------------+
| 2023-01-31T14:26:56.123456789                                   |
+-----------------------------------------------------------------+
> select to_timestamp_nanos('03:59:00.123456789 05-17-2023', '%c', '%+', '%H:%M:%S%.f %m-%d-%Y');
+--------------------------------------------------------------------------------------------------------------+
| to_timestamp_nanos(Utf8("03:59:00.123456789 05-17-2023"),Utf8("%c"),Utf8("%+"),Utf8("%H:%M:%S%.f %m-%d-%Y")) |
+--------------------------------------------------------------------------------------------------------------+
| 2023-05-17T03:59:00.123456789                                                                                |
+---------------------------------------------------------------------------------------------------------------+

to_timestamp_seconds

scalar
to_timestamp_seconds(expression[, ..., format_n])

Converts a value to a timestamp (YYYY-MM-DDT00:00:00<TZ>) in the session time zone. Supports strings, integer, unsigned integer, and double types as input. Strings are parsed as RFC3339 (e.g. '2023-07-20T05:44:00') if no strftime formats are provided. Strings that parse without a time zone are treated as if they are in the session time zone, or UTC if no session time zone is set. Integers, unsigned integers, and doubles are interpreted as seconds since the unix epoch (1970-01-01T00:00:00Z). The session time zone can be set using the statement SET TIMEZONE = 'desired time zone'. The time zone can be a value like +00:00, 'Europe/London' etc.

expression

Expression to operate on. Can be a constant, column, or function, and any combination of arithmetic operators.

format_n

Optional strftime format strings to use to parse the expression. Formats will be tried in the order they appear with the first successful one being returned. If none of the formats successfully parse the expression an error will be returned. NULL formats are skipped. If every format is NULL the result is NULL. Note: parsing of named timezones (e.g. 'America/New_York') using %Z is only supported at the end of the string preceded by a space.

Example
> select to_timestamp_seconds('2023-01-31T09:26:56.123456789-05:00');
+-------------------------------------------------------------------+
| to_timestamp_seconds(Utf8("2023-01-31T09:26:56.123456789-05:00")) |
+-------------------------------------------------------------------+
| 2023-01-31T14:26:56                                               |
+-------------------------------------------------------------------+
> select to_timestamp_seconds('03:59:00.123456789 05-17-2023', '%c', '%+', '%H:%M:%S%.f %m-%d-%Y');
+----------------------------------------------------------------------------------------------------------------+
| to_timestamp_seconds(Utf8("03:59:00.123456789 05-17-2023"),Utf8("%c"),Utf8("%+"),Utf8("%H:%M:%S%.f %m-%d-%Y")) |
+----------------------------------------------------------------------------------------------------------------+
| 2023-05-17T03:59:00                                                                                            |
+----------------------------------------------------------------------------------------------------------------+

to_unixtime

scalar
to_unixtime(expression[, ..., format_n])

Converts a value to seconds since the unix epoch (1970-01-01T00:00:00). Supports strings, dates, timestamps, integer, unsigned integer, and float types as input. Strings are parsed as RFC3339 (e.g. '2023-07-20T05:44:00') if no strftime formats are provided. Integers, unsigned integers, and floats are interpreted as seconds since the unix epoch (1970-01-01T00:00:00).

expression

Expression to operate on. Can be a constant, column, or function, and any combination of arithmetic operators.

format_n

Optional strftime format strings to use to parse the expression. Formats will be tried in the order they appear with the first successful one being returned. If none of the formats successfully parse the expression an error will be returned. NULL formats are skipped. If every format is NULL the result is NULL.

Example
> select to_unixtime('2020-09-08T12:00:00+00:00');
+------------------------------------------------+
| to_unixtime(Utf8("2020-09-08T12:00:00+00:00")) |
+------------------------------------------------+
| 1599566400                                     |
+------------------------------------------------+
> select to_unixtime('01-14-2023 01:01:30+05:30', '%q', '%d-%m-%Y %H/%M/%S', '%+', '%m-%d-%Y %H:%M:%S%#z');
+-----------------------------------------------------------------------------------------------------------------------------+
| to_unixtime(Utf8("01-14-2023 01:01:30+05:30"),Utf8("%q"),Utf8("%d-%m-%Y %H/%M/%S"),Utf8("%+"),Utf8("%m-%d-%Y %H:%M:%S%#z")) |
+-----------------------------------------------------------------------------------------------------------------------------+
| 1673638290                                                                                                                  |
+-----------------------------------------------------------------------------------------------------------------------------+

Union Functions 2

union_extract

scalar
union_extract(union, field_name)

Returns the value of the given field in the union when selected, or NULL otherwise.

union

Union expression to operate on. Can be a constant, column, or function, and any combination of operators.

field_name

String expression to operate on. Must be a constant.

Example
> select union_column, union_extract(union_column, 'a'), union_extract(union_column, 'b') from table_with_union;
+--------------+----------------------------------+----------------------------------+
| union_column | union_extract(union_column, 'a') | union_extract(union_column, 'b') |
+--------------+----------------------------------+----------------------------------+
| {a=1}        | 1                                |                                  |
| {b=3.0}      |                                  | 3.0                              |
| {a=4}        | 4                                |                                  |
| {b=}         |                                  |                                  |
| {a=}         |                                  |                                  |
+--------------+----------------------------------+----------------------------------+

union_tag

scalar
union_tag(union_expression)

Returns the name of the currently selected field in the union

union

Union expression to operate on. Can be a constant, column, or function, and any combination of operators.

Example
> select union_column, union_tag(union_column) from table_with_union;
+--------------+-------------------------+
| union_column | union_tag(union_column) |
+--------------+-------------------------+
| {a=1}        | a                       |
| {b=3.0}      | b                       |
| {a=4}        | a                       |
| {b=}         | b                       |
| {a=}         | a                       |
+--------------+-------------------------+

datumhue.com

(c) 2026 Shuusei AB. Quote excerpts of this manual, with attribution to DatumHue, in your own documentation, tutorials, course materials, reviews, and other writing or video. Republishing it in whole or in substantial part needs written permission: support@datumhue.com.

Victor Mono is licensed under the SIL Open Font License 1.1
Copyright (c) 2024, Rune Bjørnerås (https://github.com/rubjo)

This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL


-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------

PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.

The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.

DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.

"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).

"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).

"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.

"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.

PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:

1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.

2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.

3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.

4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.

5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.

TERMINATION
This license becomes null and void if any of the above conditions are
not met.

DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

Try

    ↑↓ selectEnter openTab filter

    Settings

    Theme
    Text
    Print

    Keyboard shortcuts

    / or Ctrl KSearch
    ↑ ↓ EnterPick a result
    TabNext result filter
    j kNext or previous entry
    [ ]Previous or next page
    yCopy a link to the current entry
    ?These shortcuts
    EscClose

    On this page