id stringlengths 36 36 | document stringlengths 3 3k | metadata stringlengths 23 69 | embeddings listlengths 384 384 |
|---|---|---|---|
f2903322-dbcf-4a2e-be32-f42405f2895b | description: 'Documentation for Tuple functions'
sidebar_label: 'Tuples'
slug: /sql-reference/functions/tuple-functions
title: 'Tuple functions'
doc_type: 'reference'
:::note
The documentation below is generated from the
system.functions
system table.
:::
flattenTuple {#flattenTuple}
Introduced in: v22.6
Flattens a named and nested tuple.
The elements of the returned tuple are the paths of the input tuple.
Syntax
sql
flattenTuple(input)
Arguments
input
β Named and nested tuple to flatten.
Tuple(n1 T1[, n2 T2, ... ])
Returned value
Returns an output tuple whose elements are paths from the original input.
Tuple(T)
Examples
Usage example
```sql title=Query
CREATE TABLE tab(t Tuple(a UInt32, b Tuple(c String, d UInt32))) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO tab VALUES ((3, ('c', 4)));
SELECT flattenTuple(t) FROM tab;
```
response title=Response
ββflattenTuple(t)β
β (3, 'c', 4) β
ββββββββββββββββββ
tuple {#tuple}
Introduced in: v
Returns a tuple by grouping input arguments.
For columns C1, C2, ... with the types T1, T2, ..., it returns a named Tuple(C1 T1, C2 T2, ...) type tuple containing these columns if their names are unique and can be treated as unquoted identifiers, otherwise a Tuple(T1, T2, ...) is returned. There is no cost to execute the function.
Tuples are normally used as intermediate values for an argument of IN operators, or for creating a list of formal parameters of lambda functions. Tuples can't be written to a table.
The function implements the operator
(x, y, ...)
.
Syntax
```sql
```
Arguments
None.
Returned value
Examples
typical
sql title=Query
SELECT tuple(1, 2)
response title=Response
(1,2)
tupleConcat {#tupleConcat}
Introduced in: v23.8
Combines tuples passed as arguments.
Syntax
sql
tupleConcat(tuple1[, tuple2, [...]])
Arguments
tupleN
β Arbitrary number of arguments of Tuple type.
Tuple(T)
Returned value
Returns a tuple containing all elements from the input tuples.
Tuple(T)
Examples
Usage example
sql title=Query
SELECT tupleConcat((1, 2), ('a',), (true, false))
response title=Response
(1, 2, 'a', true, false)
tupleDivide {#tupleDivide}
Introduced in: v21.11
Calculates the division of corresponding elements of two tuples of the same size.
:::note
Division by zero will return
inf
.
:::
Syntax
sql
tupleDivide(t1, t2)
Arguments
t1
β First tuple.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
t2
β Second tuple.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
Returned value
Returns tuple with the result of division.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
Examples
Basic usage
sql title=Query
SELECT tupleDivide((1, 2), (2, 3))
response title=Response
(0.5, 0.6666666666666666)
tupleDivideByNumber {#tupleDivideByNumber}
Introduced in: v21.11
Returns a tuple with all elements divided by a number. | {"source_file": "tuple-functions.md"} | [
-0.010104358196258545,
-0.02724589966237545,
-0.008745167404413223,
0.001117940992116928,
-0.06457912176847458,
-0.016317088156938553,
0.05519040673971176,
0.03658483177423477,
-0.05648723989725113,
-0.029783038422465324,
-0.016798174008727074,
-0.006043759640306234,
0.03213062137365341,
-... |
1cb1f03a-a8ad-40dc-b8d1-8f077346b731 | response title=Response
(0.5, 0.6666666666666666)
tupleDivideByNumber {#tupleDivideByNumber}
Introduced in: v21.11
Returns a tuple with all elements divided by a number.
:::note
Division by zero will return
inf
.
:::
Syntax
sql
tupleDivideByNumber(tuple, number)
Arguments
tuple
β Tuple to divide.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
number
β Divider.
(U)Int*
or
Float*
or
Decimal
Returned value
Returns a tuple with divided elements.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
Examples
Basic usage
sql title=Query
SELECT tupleDivideByNumber((1, 2), 0.5)
response title=Response
(2, 4)
tupleElement {#tupleElement}
Introduced in: v1.1
Extracts an element from a tuple by index or name.
For access by index, an 1-based numeric index is expected.
For access by name, the element name can be provided as a string (works only for named tuples).
An optional third argument specifies a default value which is returned instead of throwing an exception when the accessed element does not exist.
All arguments must be constants.
This function has zero runtime cost and implements the operators
x.index
and
x.name
.
Syntax
sql
tupleElement(tuple, index|name[, default_value])
Arguments
tuple
β A tuple or array of tuples.
Tuple(T)
or
Array(Tuple(T))
index
β Column index, starting from 1.
const UInt8/16/32/64
name
β Name of the element.
const String
default_value
β Default value returned when index is out of bounds or element doesn't exist.
Any
Returned value
Returns the element at the specified index or name.
Any
Examples
Index access
sql title=Query
SELECT tupleElement((1, 'hello'), 2)
response title=Response
hello
Named tuple with table
sql title=Query
CREATE TABLE example (values Tuple(name String, age UInt32)) ENGINE = Memory;
INSERT INTO example VALUES (('Alice', 30));
SELECT tupleElement(values, 'name') FROM example;
response title=Response
Alice
With default value
sql title=Query
SELECT tupleElement((1, 2), 5, 'not_found')
response title=Response
not_found
Operator syntax
sql title=Query
SELECT (1, 'hello').2
response title=Response
hello
tupleHammingDistance {#tupleHammingDistance}
Introduced in: v21.1
Returns the
Hamming Distance
between two tuples of the same size.
:::note
The result type is determined the same way it is for
Arithmetic functions
, based on the number of elements in the input tuples.
sql
SELECT
toTypeName(tupleHammingDistance(tuple(0), tuple(0))) AS t1,
toTypeName(tupleHammingDistance((0, 0), (0, 0))) AS t2,
toTypeName(tupleHammingDistance((0, 0, 0), (0, 0, 0))) AS t3,
toTypeName(tupleHammingDistance((0, 0, 0, 0), (0, 0, 0, 0))) AS t4,
toTypeName(tupleHammingDistance((0, 0, 0, 0, 0), (0, 0, 0, 0, 0))) AS t5
text
ββt1βββββ¬βt2ββββββ¬βt3ββββββ¬βt4ββββββ¬βt5ββββββ
β UInt8 β UInt16 β UInt32 β UInt64 β UInt64 β
βββββββββ΄βββββββββ΄βββββββββ΄βββββββββ΄βββββββββ
:::
Syntax | {"source_file": "tuple-functions.md"} | [
-0.008803822100162506,
0.002575923455879092,
-0.046095576137304306,
0.03780587017536163,
-0.0030255138408392668,
-0.05632432550191879,
0.07043305039405823,
-0.01721682772040367,
-0.008622557856142521,
-0.00828440673649311,
-0.015749119222164154,
-0.06540010124444962,
0.023567013442516327,
... |
8260d7aa-743a-43e7-89a5-60a82d3b625b | text
ββt1βββββ¬βt2ββββββ¬βt3ββββββ¬βt4ββββββ¬βt5ββββββ
β UInt8 β UInt16 β UInt32 β UInt64 β UInt64 β
βββββββββ΄βββββββββ΄βββββββββ΄βββββββββ΄βββββββββ
:::
Syntax
sql
tupleHammingDistance(t1, t2)
Arguments
t1
β First tuple.
Tuple(*)
t2
β Second tuple.
Tuple(*)
Returned value
Returns the Hamming distance.
UInt8/16/32/64
Examples
Usage example
sql title=Query
SELECT tupleHammingDistance((1, 2, 3), (3, 2, 1))
response title=Response
2
With MinHash to detect semi-duplicate strings
sql title=Query
SELECT tupleHammingDistance(wordShingleMinHash(string), wordShingleMinHashCaseInsensitive(string)) FROM (SELECT 'ClickHouse is a column-oriented database management system for online analytical processing of queries.' AS string)
response title=Response
2
tupleIntDiv {#tupleIntDiv}
Introduced in: v23.8
Performs an integer division with a tuple of numerators and a tuple of denominators. Returns a tuple of quotients.
If either tuple contains non-integer elements then the result is calculated by rounding to the nearest integer for each non-integer numerator or divisor.
Division by 0 causes an error to be thrown.
Syntax
sql
tupleIntDiv(tuple_num, tuple_div)
Arguments
tuple_num
β Tuple of numerator values.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
tuple_div
β Tuple of divisor values.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
Returned value
Returns a tuple of the quotients.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
Examples
Basic usage
sql title=Query
SELECT tupleIntDiv((15, 10, 5), (5, 5, 5))
response title=Response
(3, 2, 1)
With decimals
sql title=Query
SELECT tupleIntDiv((15, 10, 5), (5.5, 5.5, 5.5))
response title=Response
(2, 1, 0)
tupleIntDivByNumber {#tupleIntDivByNumber}
Introduced in: v23.8
Performs integer division of a tuple of numerators by a given denominator, and returns a tuple of the quotients.
If either of the input parameters contain non-integer elements then the result is calculated by rounding to the nearest integer for each non-integer numerator or divisor.
An error will be thrown for division by 0.
Syntax
sql
tupleIntDivByNumber(tuple_num, div)
Arguments
tuple_num
β Tuple of numerator values.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
div
β The divisor value.
(U)Int*
or
Float*
or
Decimal
Returned value
Returns a tuple of the quotients.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
Examples
Basic usage
sql title=Query
SELECT tupleIntDivByNumber((15, 10, 5), 5)
response title=Response
(3, 2, 1)
With decimals
sql title=Query
SELECT tupleIntDivByNumber((15.2, 10.7, 5.5), 5.8)
response title=Response
(2, 1, 0)
tupleIntDivOrZero {#tupleIntDivOrZero}
Introduced in: v23.8 | {"source_file": "tuple-functions.md"} | [
0.035951245576143265,
-0.014092638157308102,
-0.020610274747014046,
-0.026437371969223022,
-0.06154466047883034,
-0.02146477811038494,
0.07259281724691391,
-0.027961019426584244,
-0.045231182128190994,
-0.013426785357296467,
0.023252535611391068,
-0.04557515308260918,
0.06587565690279007,
... |
aefaadd0-10ab-468e-83a4-03bbf30a61a6 | With decimals
sql title=Query
SELECT tupleIntDivByNumber((15.2, 10.7, 5.5), 5.8)
response title=Response
(2, 1, 0)
tupleIntDivOrZero {#tupleIntDivOrZero}
Introduced in: v23.8
Like
tupleIntDiv
performs integer division of a tuple of numerators and a tuple of denominators, and returns a tuple of the quotients.
In case of division by 0, returns the quotient as 0 instead of throwing an exception.
If either tuple contains non-integer elements then the result is calculated by rounding to the nearest integer for each non-integer numerator or divisor.
Syntax
sql
tupleIntDivOrZero(tuple_num, tuple_div)
Arguments
tuple_num
β Tuple of numerator values.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
tuple_div
β Tuple of divisor values.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
Returned value
Returns tuple of the quotients. Returns 0 for quotients where the divisor is 0.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
Examples
With zero divisors
sql title=Query
SELECT tupleIntDivOrZero((5, 10, 15), (0, 0, 0))
response title=Response
(0, 0, 0)
tupleIntDivOrZeroByNumber {#tupleIntDivOrZeroByNumber}
Introduced in: v23.8
Like
tupleIntDivByNumber
it does integer division of a tuple of numerators by a given denominator, and returns a tuple of the quotients.
It does not throw an error for zero divisors, but rather returns the quotient as zero.
If either the tuple or div contain non-integer elements then the result is calculated by rounding to the nearest integer for each non-integer numerator or divisor.
Syntax
sql
tupleIntDivOrZeroByNumber(tuple_num, div)
Arguments
tuple_num
β Tuple of numerator values.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
div
β The divisor value.
(U)Int*
or
Float*
or
Decimal
Returned value
Returns a tuple of the quotients with
0
for quotients where the divisor is
0
.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
Examples
Basic usage
sql title=Query
SELECT tupleIntDivOrZeroByNumber((15, 10, 5), 5)
response title=Response
(3, 2, 1)
With zero divisor
sql title=Query
SELECT tupleIntDivOrZeroByNumber((15, 10, 5), 0)
response title=Response
(0, 0, 0)
tupleMinus {#tupleMinus}
Introduced in: v21.11
Calculates the difference between corresponding elements of two tuples of the same size.
Syntax
sql
tupleMinus(t1, t2)
Aliases
:
vectorDifference
Arguments
t1
β First tuple.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
t2
β Second tuple.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
Returned value
Returns a tuple containing the results of the subtractions.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
Examples
Basic usage
sql title=Query
SELECT tupleMinus((1, 2), (2, 3))
response title=Response
(-1, -1)
tupleModulo {#tupleModulo}
Introduced in: v23.8
Returns a tuple of the remainders (moduli) of division operations of two tuples.
Syntax | {"source_file": "tuple-functions.md"} | [
-0.002540664281696081,
0.019908636808395386,
-0.013204703107476234,
0.021255919709801674,
0.0013381298631429672,
-0.07566613703966141,
0.07959666103124619,
0.029687467962503433,
-0.03659491240978241,
-0.02199675887823105,
-0.04213374853134155,
-0.10732690244913101,
0.003903285600244999,
-0... |
76bbc161-c42a-4dbb-9495-ec7e1e5866c9 | response title=Response
(-1, -1)
tupleModulo {#tupleModulo}
Introduced in: v23.8
Returns a tuple of the remainders (moduli) of division operations of two tuples.
Syntax
sql
tupleModulo(tuple_num, tuple_mod)
Arguments
tuple_num
β Tuple of numerator values.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
tuple_mod
β Tuple of modulus values.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
Returned value
Returns tuple of the remainders of division. An error is thrown for division by zero.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
Examples
Basic usage
sql title=Query
SELECT tupleModulo((15, 10, 5), (5, 3, 2))
response title=Response
(0, 1, 1)
tupleModuloByNumber {#tupleModuloByNumber}
Introduced in: v23.8
Returns a tuple of the moduli (remainders) of division operations of a tuple and a given divisor.
Syntax
sql
tupleModuloByNumber(tuple_num, div)
Arguments
tuple_num
β Tuple of numerator elements.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
div
β The divisor value.
(U)Int*
or
Float*
or
Decimal
Returned value
Returns tuple of the remainders of division. An error is thrown for division by zero.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
Examples
Basic usage
sql title=Query
SELECT tupleModuloByNumber((15, 10, 5), 2)
response title=Response
(1, 0, 1)
tupleMultiply {#tupleMultiply}
Introduced in: v21.11
Calculates the multiplication of corresponding elements of two tuples of the same size.
Syntax
sql
tupleMultiply(t1, t2)
Arguments
t1
β First tuple.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
t2
β Second tuple.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
Returned value
Returns a tuple with the results of the multiplications.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
Examples
Basic usage
sql title=Query
SELECT tupleMultiply((1, 2), (2, 3))
response title=Response
(2, 6)
tupleMultiplyByNumber {#tupleMultiplyByNumber}
Introduced in: v21.11
Returns a tuple with all elements multiplied by a number.
Syntax
sql
tupleMultiplyByNumber(tuple, number)
Arguments
tuple
β Tuple to multiply.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
number
β Multiplier.
(U)Int*
or
Float*
or
Decimal
Returned value
Returns a tuple with multiplied elements.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
Examples
Basic usage
sql title=Query
SELECT tupleMultiplyByNumber((1, 2), -2.1)
response title=Response
(-2.1, -4.2)
tupleNames {#tupleNames}
Introduced in: v
Converts a tuple into an array of column names. For a tuple in the form
Tuple(a T, b T, ...)
, it returns an array of strings representing the named columns of the tuple. If the tuple elements do not have explicit names, their indices will be used as the column names instead.
Syntax
```sql
```
Arguments
None.
Returned value
Examples
typical | {"source_file": "tuple-functions.md"} | [
-0.041429851204156876,
-0.03032379224896431,
-0.042059291154146194,
0.030516501516103745,
-0.0032813320867717266,
-0.061331260949373245,
0.08708766102790833,
0.0018623999785631895,
-0.03774357587099075,
-0.032752875238657,
0.024976620450615883,
-0.07031320780515671,
0.040725041180849075,
-... |
4d3a8a5f-0945-453e-8889-27480071d528 | Syntax
```sql
```
Arguments
None.
Returned value
Examples
typical
sql title=Query
SELECT tupleNames(tuple(1 as a, 2 as b))
response title=Response
['a','b']
tupleNegate {#tupleNegate}
Introduced in: v21.11
Calculates the negation of the tuple elements.
Syntax
sql
tupleNegate(t)
Arguments
t
β Tuple to negate.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
Returned value
Returns a tuple with the result of negation.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
Examples
Basic usage
sql title=Query
SELECT tupleNegate((1, 2))
response title=Response
(-1, -2)
tuplePlus {#tuplePlus}
Introduced in: v21.11
Calculates the sum of corresponding elements of two tuples of the same size.
Syntax
sql
tuplePlus(t1, t2)
Aliases
:
vectorSum
Arguments
t1
β First tuple.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
t2
β Second tuple.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
Returned value
Returns a tuple containing the sums of corresponding input tuple arguments.
Tuple((U)Int*)
or
Tuple(Float*)
or
Tuple(Decimal)
Examples
Basic usage
sql title=Query
SELECT tuplePlus((1, 2), (2, 3))
response title=Response
(3, 5)
tupleToNameValuePairs {#tupleToNameValuePairs}
Introduced in: v21.9
Converts a tuple to an array of
(name, value)
pairs.
For example, tuple
Tuple(n1 T1, n2 T2, ...)
is converted to
Array(Tuple('n1', T1), Tuple('n2', T2), ...)
.
All values in the tuple must be of the same type.
Syntax
sql
tupleToNameValuePairs(tuple)
Arguments
tuple
β Named tuple with any types of values.
Tuple(n1 T1[, n2 T2, ...])
Returned value
Returns an array with
(name, value)
pairs.
Array(Tuple(String, T))
Examples
Named tuple
sql title=Query
SELECT tupleToNameValuePairs(tuple(1593 AS user_ID, 2502 AS session_ID))
response title=Response
[('1', 1593), ('2', 2502)]
Unnamed tuple
sql title=Query
SELECT tupleToNameValuePairs(tuple(3, 2, 1))
response title=Response
[('1', 3), ('2', 2), ('3', 1)]
untuple {#untuple}
Performs syntactic substitution of
tuple
elements in the call location.
The names of the result columns are implementation-specific and subject to change. Do not assume specific column names after
untuple
.
Syntax
sql
untuple(x)
You can use the
EXCEPT
expression to skip columns as a result of the query.
Arguments
x
β A
tuple
function, column, or tuple of elements.
Tuple
.
Returned value
None.
Examples
Input table:
text
ββkeyββ¬βv1ββ¬βv2ββ¬βv3ββ¬βv4ββ¬βv5ββ¬βv6βββββββββ
β 1 β 10 β 20 β 40 β 30 β 15 β (33,'ab') β
β 2 β 25 β 65 β 70 β 40 β 6 β (44,'cd') β
β 3 β 57 β 30 β 20 β 10 β 5 β (55,'ef') β
β 4 β 55 β 12 β 7 β 80 β 90 β (66,'gh') β
β 5 β 30 β 50 β 70 β 25 β 55 β (77,'kl') β
βββββββ΄βββββ΄βββββ΄βββββ΄βββββ΄βββββ΄ββββββββββββ
Example of using a
Tuple
-type column as the
untuple
function parameter:
Query:
sql
SELECT untuple(v6) FROM kv;
Result: | {"source_file": "tuple-functions.md"} | [
-0.031533438712358475,
-0.03264982998371124,
-0.03458648920059204,
0.022832898423075676,
-0.05901831015944481,
-0.0680672824382782,
0.05445447564125061,
-0.03552772477269173,
-0.026154272258281708,
-0.04572204500436783,
-0.03153533115983009,
-0.032968536019325256,
0.050038035959005356,
-0.... |
3602d52d-422e-4c2e-953f-3dde1abf552a | Example of using a
Tuple
-type column as the
untuple
function parameter:
Query:
sql
SELECT untuple(v6) FROM kv;
Result:
text
ββ_ut_1ββ¬β_ut_2ββ
β 33 β ab β
β 44 β cd β
β 55 β ef β
β 66 β gh β
β 77 β kl β
βββββββββ΄ββββββββ
Example of using an
EXCEPT
expression:
Query:
sql
SELECT untuple((* EXCEPT (v2, v3),)) FROM kv;
Result:
text
ββkeyββ¬βv1ββ¬βv4ββ¬βv5ββ¬βv6βββββββββ
β 1 β 10 β 30 β 15 β (33,'ab') β
β 2 β 25 β 40 β 6 β (44,'cd') β
β 3 β 57 β 10 β 5 β (55,'ef') β
β 4 β 55 β 80 β 90 β (66,'gh') β
β 5 β 30 β 25 β 55 β (77,'kl') β
βββββββ΄βββββ΄βββββ΄βββββ΄ββββββββββββ
Distance functions {#distance-functions}
All supported functions are described in
distance functions documentation
. | {"source_file": "tuple-functions.md"} | [
-0.00992626417428255,
-0.006802667398005724,
-0.010602100752294064,
-0.052076540887355804,
0.014470969326794147,
0.048883892595767975,
-0.006687491666525602,
-0.07358214259147644,
-0.06231527775526047,
-0.020760584622621536,
0.058872636407613754,
-0.022888246923685074,
-0.02289779670536518,
... |
ca19af12-2f25-4e58-a389-22ac555c6c0b | description: 'Documentation for string replacement functions'
sidebar_label: 'String replacement'
slug: /sql-reference/functions/string-replace-functions
title: 'Functions for string replacement'
doc_type: 'reference'
keywords: ['string replacement']
Functions for string replacement
General strings functions
and
functions for searching in strings
are described separately.
:::note
The documentation below is generated from the
system.functions
system table.
:::
format {#format}
Introduced in: v20.1
Format the
pattern
string with the values (strings, integers, etc.) listed in the arguments, similar to formatting in Python.
The pattern string can contain replacement fields surrounded by curly braces
{}
.
Anything not contained in braces is considered literal text and copied verbatim into the output.
Literal brace character can be escaped by two braces:
{{
and
}}
.
Field names can be numbers (starting from zero) or empty (then they are implicitly given monotonically increasing numbers).
Syntax
sql
format(pattern, s0[, s1, ...])
Arguments
pattern
β The format string containing placeholders.
String
s0[, s1, ...]
β One or more values to substitute into the pattern.
Any
Returned value
Returns a formatted string.
String
Examples
Numbered placeholders
sql title=Query
SELECT format('{1} {0} {1}', 'World', 'Hello')
response title=Response
ββformat('{1} {0} {1}', 'World', 'Hello')ββ
β Hello World Hello β
βββββββββββββββββββββββββββββββββββββββββββ
Implicit numbering
sql title=Query
SELECT format('{} {}', 'Hello', 'World')
response title=Response
ββformat('{} {}', 'Hello', 'World')ββ
β Hello World β
βββββββββββββββββββββββββββββββββββββ
overlay {#overlay}
Introduced in: v24.9
Replaces part of the string
input
with another string
replace
, starting at the 1-based index
offset
.
Syntax
sql
overlay(s, replace, offset[, length])
Arguments
s
β The input string.
String
replace
β The replacement string
const String
offset
β An integer type
Int
(1-based). If
offset
is negative, it is counted from the end of the string
s
.
Int
length
β Optional. An integer type
Int
.
length
specifies the length of the snippet within the input string
s
to be replaced. If
length
is not specified, the number of bytes removed from
s
equals the length of
replace
; otherwise
length
bytes are removed.
Int
Returned value
Returns a string with replacement.
String
Examples
Basic replacement
sql title=Query
SELECT overlay('My father is from Mexico.', 'mother', 4) AS res;
response title=Response
ββresβββββββββββββββββββββββ
β My mother is from Mexico.β
ββββββββββββββββββββββββββββ
Replacement with length
sql title=Query
SELECT overlay('My father is from Mexico.', 'dad', 4, 6) AS res;
response title=Response
ββresββββββββββββββββββββ
β My dad is from Mexico.β
βββββββββββββββββββββββββ
overlayUTF8 {#overlayUTF8} | {"source_file": "string-replace-functions.md"} | [
-0.03304766118526459,
0.05322070047259331,
0.0072155604138970375,
-0.010338595137000084,
-0.06254090368747711,
0.010752526111900806,
0.03281255066394806,
0.08675938844680786,
-0.06083056330680847,
0.011741750873625278,
-0.028734052553772926,
0.034152135252952576,
0.07580270618200302,
-0.07... |
ec9b6753-9bbd-401a-b960-dd8f17142fc4 | response title=Response
ββresββββββββββββββββββββ
β My dad is from Mexico.β
βββββββββββββββββββββββββ
overlayUTF8 {#overlayUTF8}
Introduced in: v24.9
Replace part of the string
s
with another string
replace
, starting at the 1-based index
offset
.
Assumes that the string contains valid UTF-8 encoded text.
If this assumption is violated, no exception is thrown and the result is undefined.
Syntax
sql
overlayUTF8(s, replace, offset[, length])
Arguments
s
β The input string.
String
replace
β The replacement string.
const String
offset
β An integer type
Int
(1-based). If
offset
is negative, it is counted from the end of the input string
s
.
(U)Int*
length
β Optional. Specifies the length of the snippet within the input string
s
to be replaced. If
length
is not specified, the number of characters removed from
s
equals the length of
replace
, otherwise
length
characters are removed.
(U)Int*
Returned value
Returns a string with replacement.
String
Examples
UTF-8 replacement
sql title=Query
SELECT overlayUTF8('Mein Vater ist aus Γsterreich.', 'der TΓΌrkei', 20) AS res;
response title=Response
ββresββββββββββββββββββββββββββββ
β Mein Vater ist aus der TΓΌrkei.β
βββββββββββββββββββββββββββββββββ
printf {#printf}
Introduced in: v24.8
The
printf
function formats the given string with the values (strings, integers, floating-points etc.) listed in the arguments, similar to printf function in C++.
The format string can contain format specifiers starting with
%
character.
Anything not contained in
%
and the following format specifier is considered literal text and copied verbatim into the output.
Literal
%
character can be escaped by
%%
.
Syntax
sql
printf(format[, sub1, sub2, ...])
Arguments
format
β The format string with
%
specifiers.
String
sub1, sub2, ...
β Optional. Zero or more values to substitute into the format string.
Any
Returned value
Returns a formatted string.
String
Examples
C++-style formatting
sql title=Query
SELECT printf('%%%s %s %d', 'Hello', 'World', 2024);
response title=Response
ββprintf('%%%s %s %d', 'Hello', 'World', 2024)ββ
β %Hello World 2024 β
ββββββββββββββββββββββββββββββββββββββββββββββββ
regexpQuoteMeta {#regexpQuoteMeta}
Introduced in: v20.1
Adds a backslash before these characters with special meaning in regular expressions:
\0
,
\\
,
|
,
(
,
)
,
^
,
$
,
.
,
[
,
]
,
?
,
*
,
+
,
{
,
:
,
-
.
This implementation slightly differs from re2::RE2::QuoteMeta.
It escapes zero byte as
\0
instead of
\x00
and it escapes only required characters.
Syntax
sql
regexpQuoteMeta(s)
Arguments
s
β The input string containing characters to be escaped for regex.
String
Returned value
Returns a string with regex special characters escaped.
String
Examples
Escape regex special characters
sql title=Query
SELECT regexpQuoteMeta('Hello. [World]? (Yes)*') AS res | {"source_file": "string-replace-functions.md"} | [
0.016033293679356575,
0.06490424275398254,
0.06928207725286484,
0.003970044199377298,
-0.07076422870159149,
0.033763233572244644,
0.060115996748209,
0.04468444362282753,
0.00033204525243490934,
-0.06835038959980011,
0.038831863552331924,
-0.025936085730791092,
0.0778227373957634,
-0.108267... |
f3b7252d-e720-4a1c-a427-9041b30d7b36 | Returns a string with regex special characters escaped.
String
Examples
Escape regex special characters
sql title=Query
SELECT regexpQuoteMeta('Hello. [World]? (Yes)*') AS res
response title=Response
ββresββββββββββββββββββββββββββββ
β Hello\. \[World\]\? \(Yes\)\* β
βββββββββββββββββββββββββββββββββ
replaceAll {#replaceAll}
Introduced in: v1.1
Replaces all occurrences of the substring
pattern
in
haystack
by the
replacement
string.
Syntax
sql
replaceAll(haystack, pattern, replacement)
Aliases
:
replace
Arguments
haystack
β The input string to search in.
String
pattern
β The substring to find and replace.
const String
replacement
β The string to replace the pattern with.
const String
Returned value
Returns a string with all occurrences of pattern replaced.
String
Examples
Replace all occurrences
sql title=Query
SELECT replaceAll('Hello, Hello world', 'Hello', 'Hi') AS res;
response title=Response
ββresβββββββββββ
β Hi, Hi world β
ββββββββββββββββ
replaceOne {#replaceOne}
Introduced in: v1.1
Replaces the first occurrence of the substring
pattern
in
haystack
by the
replacement
string.
Syntax
sql
replaceOne(haystack, pattern, replacement)
Arguments
haystack
β The input string to search in.
String
pattern
β The substring to find and replace.
const String
replacement
β The string to replace the pattern with.
const String
Returned value
Returns a string with the first occurrence of pattern replaced.
String
Examples
Replace first occurrence
sql title=Query
SELECT replaceOne('Hello, Hello world', 'Hello', 'Hi') AS res;
response title=Response
ββresββββββββββββββ
β Hi, Hello world β
βββββββββββββββββββ
replaceRegexpAll {#replaceRegexpAll}
Introduced in: v1.1
Like
replaceRegexpOne
but replaces all occurrences of the pattern.
As an exception, if a regular expression worked on an empty substring, the replacement is not made more than once.
Syntax
sql
replaceRegexpAll(haystack, pattern, replacement)
Aliases
:
REGEXP_REPLACE
Arguments
haystack
β The input string to search in.
String
pattern
β The regular expression pattern to find.
const String
replacement
β The string to replace the pattern with, may contain substitutions.
const String
Returned value
Returns a string with all regex matches replaced.
String
Examples
Replace all characters with doubled version
sql title=Query
SELECT replaceRegexpAll('Hello123', '.', '\\\\0\\\\0') AS res
response title=Response
ββresβββββββββββββββββββ
β HHeelllloo112233 β
ββββββββββββββββββββββββ
Empty substring replacement example
sql title=Query
SELECT replaceRegexpAll('Hello, World!', '^', 'here: ') AS res
response title=Response
ββresββββββββββββββββββ
β here: Hello, World! β
βββββββββββββββββββββββ
replaceRegexpOne {#replaceRegexpOne}
Introduced in: v1.1 | {"source_file": "string-replace-functions.md"} | [
-0.05166151002049446,
-0.002322993939742446,
0.12188930809497833,
0.04399356618523598,
-0.04696042090654373,
-0.04712539538741112,
0.02665838785469532,
0.002384783700108528,
0.006672459188848734,
-0.007944220677018166,
-0.043937794864177704,
-0.011279047466814518,
0.024372553452849388,
-0.... |
381a5d23-e7ba-4490-a46b-5cbdaaac3d02 | response title=Response
ββresββββββββββββββββββ
β here: Hello, World! β
βββββββββββββββββββββββ
replaceRegexpOne {#replaceRegexpOne}
Introduced in: v1.1
Replaces the first occurrence of the substring matching the regular expression
pattern
(in re2 syntax) in
haystack
by the
replacement
string.
replacement
can contain substitutions
\0-\9
.
Substitutions
\1-\9
correspond to the 1st to 9th capturing group (submatch), substitution
\0
corresponds to the entire match.
To use a verbatim
\
character in the
pattern
or
replacement
strings, escape it using
\
.
Also keep in mind that string literals require extra escaping.
Syntax
sql
replaceRegexpOne(haystack, pattern, replacement)
Arguments
haystack
β The input string to search in.
String
pattern
β The regular expression pattern to find.
const String
replacement
β The string to replace the pattern with, may contain substitutions.
const String
Returned value
Returns a string with the first regex match replaced.
String
Examples
Converting ISO dates to American format
sql title=Query
SELECT DISTINCT
EventDate,
replaceRegexpOne(toString(EventDate), '(\\d{4})-(\\d{2})-(\\d{2})', '\\2/\\3/\\1') AS res
FROM test.hits
LIMIT 7
FORMAT TabSeparated
response title=Response
2014-03-17 03/17/2014
2014-03-18 03/18/2014
2014-03-19 03/19/2014
2014-03-20 03/20/2014
2014-03-21 03/21/2014
2014-03-22 03/22/2014
2014-03-23 03/23/2014
Copying a string ten times
sql title=Query
SELECT replaceRegexpOne('Hello, World!', '.*', '\\\\0\\\\0\\\\0\\\\0\\\\0\\\\0\\\\0\\\\0\\\\0\\\\0') AS res
response title=Response
ββresβββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Hello, World!Hello, World!Hello, World!Hello, World!Hello, World!Hello, World!Hello, World!Hello, World!Hello, World!Hello, World! β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
translate {#translate}
Introduced in: v22.7
Replaces characters in the string
s
using a one-to-one character mapping defined by
from
and
to
strings.
from
and
to
must be constant ASCII strings.
If
from
and
to
have equal sizes, each occurrence of the first character of
first
in
s
is replaced by the first character of
to
, the second character of
first
in
s
is replaced by the second character of
to
, etc.
If
from
contains more characters than
to
, all occurrences of the characters at the end of
from
that have no corresponding character in
to
are deleted from
s
.
Non-ASCII characters in
s
are not modified by the function.
Syntax
sql
translate(s, from, to)
Arguments
s
β The input string to translate.
String
from
β A constant ASCII string containing characters to replace.
const String
to
β A constant ASCII string containing replacement characters.
const String | {"source_file": "string-replace-functions.md"} | [
0.025955256074666977,
0.011401208117604256,
0.09523428976535797,
0.05410150811076164,
-0.05377728119492531,
0.05110261216759682,
0.05492815375328064,
0.025466352701187134,
-0.05508977547287941,
-0.013719907030463219,
-0.027110431343317032,
-0.08327187597751617,
-0.01214818935841322,
-0.076... |
eb707a98-9af0-4acd-b1cc-cff3d7edf02d | from
β A constant ASCII string containing characters to replace.
const String
to
β A constant ASCII string containing replacement characters.
const String
Returned value
Returns a string with character translations applied.
String
Examples
Character mapping
sql title=Query
SELECT translate('Hello, World!', 'delor', 'DELOR') AS res
response title=Response
ββresββββββββββββ
β HELLO, WORLD! β
βββββββββββββββββ
Different lengths
sql title=Query
SELECT translate('clickhouse', 'clickhouse', 'CLICK') AS res
response title=Response
ββresββββ
β CLICK β
βββββββββ
translateUTF8 {#translateUTF8}
Introduced in: v22.7
Like
translate
but assumes
s
,
from
and
to
are UTF-8 encoded strings.
Syntax
sql
translateUTF8(s, from, to)
Arguments
s
β UTF-8 input string to translate.
String
from
β A constant UTF-8 string containing characters to replace.
const String
to
β A constant UTF-8 string containing replacement characters.
const String
Returned value
Returns a
String
data type value.
String
Examples
UTF-8 character translation
sql title=Query
SELECT translateUTF8('MΓΌnchener StraΓe', 'ΓΌΓ', 'us') AS res;
response title=Response
ββresβββββββββββββββ
β Munchener Strase β
ββββββββββββββββββββ | {"source_file": "string-replace-functions.md"} | [
-0.015526950359344482,
-0.040182970464229584,
0.06192135065793991,
0.04402328282594681,
-0.06326384842395782,
-0.015567125752568245,
0.08604247123003006,
0.01959298551082611,
0.007408246863633394,
-0.03541739657521248,
-0.024967854842543602,
-0.06232601776719093,
0.013615141622722149,
-0.0... |
328872b2-fcdd-4be6-bb8b-6001d7fba673 | description: 'Documentation for UDFs User Defined Functions'
sidebar_label: 'UDF'
slug: /sql-reference/functions/udf
title: 'UDFs User Defined Functions'
doc_type: 'reference'
import PrivatePreviewBadge from '@theme/badges/PrivatePreviewBadge';
UDFs User Defined Functions
Executable User Defined Functions {#executable-user-defined-functions}
:::note
This feature is supported in private preview in ClickHouse Cloud. Please contact ClickHouse Support at https://clickhouse.cloud/support to access.
:::
ClickHouse can call any external executable program or script to process data.
The configuration of executable user defined functions can be located in one or more xml-files. The path to the configuration is specified in the
user_defined_executable_functions_config
parameter.
A function configuration contains the following settings: | {"source_file": "udf.md"} | [
-0.0008076446247287095,
-0.09784488379955292,
-0.07014919817447662,
-0.0029235119000077248,
0.0022599915973842144,
-0.030519776046276093,
-0.006148925982415676,
0.03257543221116066,
-0.055411554872989655,
0.01782522164285183,
0.03847922757267952,
-0.011345199309289455,
-0.0009583525825291872... |
9436e210-50e8-4fa2-bd8b-7ed5236defab | | Parameter | Description | Required | Default Value |
|-------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------|-----------------------|
|
name
| A function name | Yes | - |
|
command
| Script name to execute or command if
execute_direct
is false | Yes | - |
|
argument
| Argument description with the
type
, and optional
name
of an argument. Each argument is described in a separate setting. Specifying name is necessary if argument names are part of serialization for user defined function format like
Native
or
JSONEachRow
| Yes |
c
+ argument_number |
|
format
| A
format
in which arguments are passed to the command. The command output is expected to use the same format too | Yes | - |
|
return_type | {"source_file": "udf.md"} | [
0.02740832231938839,
0.06670575588941574,
-0.03908486291766167,
-0.00019217900990042835,
-0.07271697372198105,
0.030385518446564674,
0.01923644170165062,
0.04008970782160759,
-0.007428995333611965,
-0.041814737021923065,
0.032796137034893036,
-0.1134740486741066,
0.028254574164748192,
-0.0... |
68e17adb-1604-472c-9429-e2624cd0b12b | |
return_type
| The type of a returned value | Yes | - |
|
return_name
| Name of returned value. Specifying return name is necessary if return name is part of serialization for user defined function format like
Native
or
JSONEachRow
| Optional |
result
|
|
type
| An executable type. If
type
is set to
executable
then single command is started. If it is set to
executable_pool
then a pool of commands is created | Yes | - |
|
max_command_execution_time
| Maximum execution time in seconds for processing block of data. This setting is valid for
executable_pool
commands only | Optional |
10
|
|
command_termination_timeout
| Time in seconds during which a command should finish after its pipe is closed. After that time
SIGTERM
is sent to the process executing the command | Optional |
10
|
|
command_read_timeout
| Timeout for reading data from command stdout in milliseconds | Optional |
10000
|
|
command_write_timeout | {"source_file": "udf.md"} | [
0.004372890572994947,
-0.0071741556748747826,
-0.08697465062141418,
0.03630705922842026,
-0.04728405922651291,
-0.04048563167452812,
-0.009954729117453098,
0.08394249528646469,
0.022551268339157104,
-0.029623936861753464,
0.030967742204666138,
-0.06318208575248718,
-0.0435970313847065,
-0.... |
d3fce72b-251b-4f2d-8fb5-aa66ee36ded7 | 10000
|
|
command_write_timeout
| Timeout for writing data to command stdin in milliseconds | Optional |
10000
|
|
pool_size
| The size of a command pool | Optional |
16
|
|
send_chunk_header
| Controls whether to send row count before sending a chunk of data to process | Optional |
false
|
|
execute_direct
| If
execute_direct
=
1
, then
command
will be searched inside user_scripts folder specified by
user_scripts_path
. Additional script arguments can be specified using whitespace separator. Example:
script_name arg1 arg2
. If
execute_direct
=
0
,
command
is passed as argument for
bin/sh -c
| Optional |
1
|
|
lifetime
| The reload interval of a function in seconds. If it is set to
0
then the function is not reloaded | Optional |
0
|
|
deterministic
| If the function is deterministic (returns the same result for the same input) | Optional |
false
| | {"source_file": "udf.md"} | [
-0.007886712439358234,
0.01490434817969799,
-0.09751792997121811,
0.06513446569442749,
-0.0428081639111042,
-0.058641448616981506,
-0.00902734138071537,
0.08495380729436874,
-0.013082856312394142,
0.022118741646409035,
0.012598896399140358,
-0.013489785604178905,
0.021158263087272644,
-0.1... |
8b5baace-43aa-4443-a7ad-d09e57c3c851 | The command must read arguments from
STDIN
and must output the result to
STDOUT
. The command must process arguments iteratively. That is after processing a chunk of arguments it must wait for the next chunk.
Examples {#examples}
Inline script
Creating
test_function_sum
manually specifying
execute_direct
to
0
using XML configuration.
File
test_function.xml
(
/etc/clickhouse-server/test_function.xml
with default path settings).
xml
<functions>
<function>
<type>executable</type>
<name>test_function_sum</name>
<return_type>UInt64</return_type>
<argument>
<type>UInt64</type>
<name>lhs</name>
</argument>
<argument>
<type>UInt64</type>
<name>rhs</name>
</argument>
<format>TabSeparated</format>
<command>cd /; clickhouse-local --input-format TabSeparated --output-format TabSeparated --structure 'x UInt64, y UInt64' --query "SELECT x + y FROM table"</command>
<execute_direct>0</execute_direct>
<deterministic>true</deterministic>
</function>
</functions>
Query:
sql
SELECT test_function_sum(2, 2);
Result:
text
ββtest_function_sum(2, 2)ββ
β 4 β
βββββββββββββββββββββββββββ
Python script
Reads a value from
STDIN
and returns it as a string:
Creating
test_function
using XML configuration.
File
test_function.xml
(
/etc/clickhouse-server/test_function.xml
with default path settings).
xml
<functions>
<function>
<type>executable</type>
<name>test_function_python</name>
<return_type>String</return_type>
<argument>
<type>UInt64</type>
<name>value</name>
</argument>
<format>TabSeparated</format>
<command>test_function.py</command>
</function>
</functions>
Script file inside
user_scripts
folder
test_function.py
(
/var/lib/clickhouse/user_scripts/test_function.py
with default path settings).
```python
!/usr/bin/python3
import sys
if
name
== '
main
':
for line in sys.stdin:
print("Value " + line, end='')
sys.stdout.flush()
```
Query:
sql
SELECT test_function_python(toUInt64(2));
Result:
text
ββtest_function_python(2)ββ
β Value 2 β
βββββββββββββββββββββββββββ
Read two values from
STDIN
and returns their sum as a JSON object:
Creating
test_function_sum_json
with named arguments and format
JSONEachRow
using XML configuration.
File
test_function.xml
(
/etc/clickhouse-server/test_function.xml
with default path settings). | {"source_file": "udf.md"} | [
0.06691712141036987,
0.003617330454289913,
-0.06746594607830048,
0.03559867665171623,
-0.08131618052721024,
-0.030960267409682274,
0.0647035464644432,
0.06059971824288368,
-0.04764388129115105,
0.029672222211956978,
0.07788511365652084,
-0.0902293473482132,
-0.015184305608272552,
-0.078681... |
d4ac8f39-d0a1-4df1-ad18-f1c93d8102cf | xml
<functions>
<function>
<type>executable</type>
<name>test_function_sum_json</name>
<return_type>UInt64</return_type>
<return_name>result_name</return_name>
<argument>
<type>UInt64</type>
<name>argument_1</name>
</argument>
<argument>
<type>UInt64</type>
<name>argument_2</name>
</argument>
<format>JSONEachRow</format>
<command>test_function_sum_json.py</command>
</function>
</functions>
Script file inside
user_scripts
folder
test_function_sum_json.py
(
/var/lib/clickhouse/user_scripts/test_function_sum_json.py
with default path settings).
```python
!/usr/bin/python3
import sys
import json
if
name
== '
main
':
for line in sys.stdin:
value = json.loads(line)
first_arg = int(value['argument_1'])
second_arg = int(value['argument_2'])
result = {'result_name': first_arg + second_arg}
print(json.dumps(result), end='\n')
sys.stdout.flush()
```
Query:
sql
SELECT test_function_sum_json(2, 2);
Result:
text
ββtest_function_sum_json(2, 2)ββ
β 4 β
ββββββββββββββββββββββββββββββββ
Use parameters in
command
setting:
Executable user defined functions can take constant parameters configured in
command
setting (works only for user defined functions with
executable
type). It also requires the
execute_direct
option (to ensure no shell argument expansion vulnerability).
File
test_function_parameter_python.xml
(
/etc/clickhouse-server/test_function_parameter_python.xml
with default path settings).
xml
<functions>
<function>
<type>executable</type>
<execute_direct>true</execute_direct>
<name>test_function_parameter_python</name>
<return_type>String</return_type>
<argument>
<type>UInt64</type>
</argument>
<format>TabSeparated</format>
<command>test_function_parameter_python.py {test_parameter:UInt64}</command>
</function>
</functions>
Script file inside
user_scripts
folder
test_function_parameter_python.py
(
/var/lib/clickhouse/user_scripts/test_function_parameter_python.py
with default path settings).
```python
!/usr/bin/python3
import sys
if
name
== "
main
":
for line in sys.stdin:
print("Parameter " + str(sys.argv[1]) + " value " + str(line), end="")
sys.stdout.flush()
```
Query:
sql
SELECT test_function_parameter_python(1)(2);
Result:
text
ββtest_function_parameter_python(1)(2)ββ
β Parameter 1 value 2 β
ββββββββββββββββββββββββββββββββββββββββ
Shell script
Shell script that multiplies each value by 2:
Executable user defined functions can be used with shell script.
File
test_function_shell.xml
(
/etc/clickhouse-server/test_function_shell.xml
with default path settings). | {"source_file": "udf.md"} | [
-0.046014733612537384,
0.019753841683268547,
-0.07800887525081635,
-0.003588352119550109,
-0.08662857115268707,
-0.04821227490901947,
-0.01464878674596548,
0.08526430279016495,
-0.04870572313666344,
-0.050126492977142334,
0.05905485153198242,
-0.024668769910931587,
-0.038443006575107574,
0... |
ba38ec2e-a321-4efb-9d12-34616dabe328 | Executable user defined functions can be used with shell script.
File
test_function_shell.xml
(
/etc/clickhouse-server/test_function_shell.xml
with default path settings).
xml
<functions>
<function>
<type>executable</type>
<name>test_shell</name>
<return_type>String</return_type>
<argument>
<type>UInt8</type>
<name>value</name>
</argument>
<format>TabSeparated</format>
<command>test_shell.sh</command>
</function>
</functions>
Script file inside
user_scripts
folder
test_shell.sh
(
/var/lib/clickhouse/user_scripts/test_shell.sh
with default path settings).
```bash
!/bin/bash
while read read_data;
do printf "$(expr $read_data * 2)\n";
done
```
Query:
sql
SELECT test_shell(number) FROM numbers(10);
Result:
text
ββtest_shell(number)ββ
1. β 0 β
2. β 2 β
3. β 4 β
4. β 6 β
5. β 8 β
6. β 10 β
7. β 12 β
8. β 14 β
9. β 16 β
10. β 18 β
ββββββββββββββββββββββ
Error Handling {#error-handling}
Some functions might throw an exception if the data is invalid. In this case, the query is canceled and an error text is returned to the client. For distributed processing, when an exception occurs on one of the servers, the other servers also attempt to abort the query.
Evaluation of Argument Expressions {#evaluation-of-argument-expressions}
In almost all programming languages, one of the arguments might not be evaluated for certain operators. This is usually the operators
&&
,
||
, and
?:
.
But in ClickHouse, arguments of functions (operators) are always evaluated. This is because entire parts of columns are evaluated at once, instead of calculating each row separately.
Performing Functions for Distributed Query Processing {#performing-functions-for-distributed-query-processing}
For distributed query processing, as many stages of query processing as possible are performed on remote servers, and the rest of the stages (merging intermediate results and everything after that) are performed on the requestor server.
This means that functions can be performed on different servers.
For example, in the query
SELECT f(sum(g(x))) FROM distributed_table GROUP BY h(y),
if a
distributed_table
has at least two shards, the functions 'g' and 'h' are performed on remote servers, and the function 'f' is performed on the requestor server.
if a
distributed_table
has only one shard, all the 'f', 'g', and 'h' functions are performed on this shard's server. | {"source_file": "udf.md"} | [
0.07179336249828339,
0.0018999731400981545,
-0.12564335763454437,
-0.022050825878977776,
-0.11020740866661072,
-0.054661281406879425,
0.08207263052463531,
0.15112219750881195,
-0.0792030468583107,
0.04162035882472992,
0.06558801978826523,
-0.030101414769887924,
0.008751214481890202,
-0.049... |
81254b7c-196d-448d-9951-94bd16dbe23a | if a
distributed_table
has only one shard, all the 'f', 'g', and 'h' functions are performed on this shard's server.
The result of a function usually does not depend on which server it is performed on. However, sometimes this is important.
For example, functions that work with dictionaries use the dictionary that exists on the server they are running on.
Another example is the
hostName
function, which returns the name of the server it is running on in order to make
GROUP BY
by servers in a
SELECT
query.
If a function in a query is performed on the requestor server, but you need to perform it on remote servers, you can wrap it in an 'any' aggregate function or add it to a key in
GROUP BY
.
SQL User Defined Functions {#sql-user-defined-functions}
Custom functions from lambda expressions can be created using the
CREATE FUNCTION
statement. To delete these functions use the
DROP FUNCTION
statement.
Related Content {#related-content}
User-defined functions in ClickHouse Cloud
{#user-defined-functions-in-clickhouse-cloud} | {"source_file": "udf.md"} | [
0.031069960445165634,
-0.051867686212062836,
-0.015755148604512215,
0.01872551068663597,
-0.0719878077507019,
-0.059637147933244705,
0.006787018850445747,
-0.10595450550317764,
0.057754985988140106,
0.02209080569446087,
0.04792495444417,
0.012892600148916245,
0.06966273486614227,
-0.075771... |
fddbb9c6-88c6-4528-a592-2e4042b05a79 | description: 'Documentation for Comparison Functions'
sidebar_label: 'Comparison'
slug: /sql-reference/functions/comparison-functions
title: 'Comparison Functions'
doc_type: 'reference'
Comparison functions
Comparison rules {#comparison-rules}
The comparison functions below return
0
or
1
with type
UInt8
. Only values within the same group can be
compared (e.g.
UInt16
and
UInt64
) but not across groups (e.g.
UInt16
and
DateTime
).
Comparison of numbers and strings are possible, as is comparison of strings with dates and dates with times.
For tuples and arrays, the comparison is lexicographic meaning that the comparison is made for each corresponding
element of the left side and right side tuple/array.
The following types can be compared:
- numbers and decimals
- strings and fixed strings
- dates
- dates with times
- tuples (lexicographic comparison)
- arrays (lexicographic comparison)
:::note
Strings are compared byte-by-byte. This may lead to unexpected results if one of the strings contains UTF-8 encoded multi-byte characters.
A string S1 which has another string S2 as prefix is considered longer than S2.
:::
equals {#equals}
Introduced in: v1.1
Compares two values for equality.
Syntax
sql
equals(a, b)
-- a = b
-- a == b
Arguments
a
β First value.
*
-
b
β Second value.
*
Returned value
Returns
1
if
a
is equal to
b
, otherwise
0
UInt8
Examples
Usage example
sql title=Query
SELECT 1 = 1, 1 = 2;
response title=Response
ββequals(1, 1)ββ¬βequals(1, 2)ββ
β 1 β 0 β
ββββββββββββββββ΄βββββββββββββββ
greater {#greater}
Introduced in: v1.1
Compares two values for greater-than relation.
Syntax
sql
greater(a, b)
-- a > b
Arguments
a
β First value.
*
-
b
β Second value.
*
Returned value
Returns
1
if
a
is greater than
b
, otherwise
0
UInt8
Examples
Usage example
sql title=Query
SELECT 2 > 1, 1 > 2;
response title=Response
ββgreater(2, 1)ββ¬βgreater(1, 2)ββ
β 1 β 0 β
βββββββββββββββββ΄ββββββββββββββββ
greaterOrEquals {#greaterOrEquals}
Introduced in: v1.1
Compares two values for greater-than-or-equal-to relation.
Syntax
sql
greaterOrEquals(a, b)
-- a >= b
Arguments
a
β First value.
*
-
b
β Second value.
*
Returned value
Returns
1
if
a
is greater than or equal to
b
, otherwise
0
UInt8
Examples
Usage example
sql title=Query
SELECT 2 >= 1, 2 >= 2, 1 >= 2;
response title=Response
ββgreaterOrEquals(2, 1)ββ¬βgreaterOrEquals(2, 2)ββ¬βgreaterOrEquals(1, 2)ββ
β 1 β 1 β 0 β
βββββββββββββββββββββββββ΄ββββββββββββββββββββββββ΄ββββββββββββββββββββββββ
less {#less}
Introduced in: v1.1
Compares two values for less-than relation.
Syntax
sql
less(a, b)
-- a < b
Arguments
a
β First value.
*
-
b
β Second value.
*
Returned value | {"source_file": "comparison-functions.md"} | [
-0.029844101518392563,
-0.001504734274931252,
-0.016000032424926758,
-0.02458530105650425,
-0.06440095603466034,
-0.05003688111901283,
-0.020900284871459007,
0.016797734424471855,
-0.0490262396633625,
-0.05547996982932091,
-0.01623099111020565,
-0.03279319405555725,
0.02114678919315338,
-0... |
f73935f2-e704-4f83-ac93-27ccc90d4f70 | Introduced in: v1.1
Compares two values for less-than relation.
Syntax
sql
less(a, b)
-- a < b
Arguments
a
β First value.
*
-
b
β Second value.
*
Returned value
Returns
1
if
a
is less than
b
, otherwise
0
UInt8
Examples
Usage example
sql title=Query
SELECT 1 < 2, 2 < 1;
response title=Response
ββless(1, 2)ββ¬βless(2, 1)ββ
β 1 β 0 β
ββββββββββββββ΄βββββββββββββ
lessOrEquals {#lessOrEquals}
Introduced in: v1.1
Compares two values for less-than-or-equal-to relation.
Syntax
sql
lessOrEquals(a, b)
-- a <= b
Arguments
a
β First value.
*
-
b
β Second value.
*
Returned value
Returns
1
if
a
is less than or equal to
b
, otherwise
0
UInt8
Examples
Usage example
sql title=Query
SELECT 1 <= 2, 2 <= 2, 3 <= 2;
response title=Response
ββlessOrEquals(1, 2)ββ¬βlessOrEquals(2, 2)ββ¬βlessOrEquals(3, 2)ββ
β 1 β 1 β 0 β
ββββββββββββββββββββββ΄βββββββββββββββββββββ΄βββββββββββββββββββββ
notEquals {#notEquals}
Introduced in: v1.1
Compares two values for inequality.
Syntax
sql
notEquals(a, b)
-- a != b
-- a <> b
Arguments
a
β First value.
*
-
b
β Second value.
*
Returned value
Returns
1
if
a
is not equal to
b
, otherwise
0
.
UInt8
Examples
Usage example
sql title=Query
SELECT 1 != 2, 1 != 1;
response title=Response
ββnotEquals(1, 2)ββ¬βnotEquals(1, 1)ββ
β 1 β 0 β
βββββββββββββββββββ΄ββββββββββββββββββ | {"source_file": "comparison-functions.md"} | [
-0.021498726680874825,
0.028231700882315636,
0.001919397385790944,
-0.01791342720389366,
-0.09456409513950348,
-0.03288248926401138,
-0.05152500420808792,
0.0436418391764164,
0.006086303852498531,
-0.01783468760550022,
-0.016957614570856094,
-0.027311477810144424,
0.12274394184350967,
-0.0... |
e94f2229-2c06-42c7-9a22-b653389616fe | description: 'Documentation for the "other" functions category'
sidebar_label: 'Other'
slug: /sql-reference/functions/other-functions
title: 'Other functions'
doc_type: 'reference'
import ExperimentalBadge from '@theme/badges/ExperimentalBadge';
import CloudNotSupportedBadge from '@theme/badges/CloudNotSupportedBadge';
import DeprecatedBadge from '@theme/badges/DeprecatedBadge';
Other functions
:::note
The function documentation below is generated from the
system.functions
system table.
:::
FQDN {#FQDN}
Introduced in: v20.1
Returns the fully qualified domain name of the ClickHouse server.
Syntax
sql
fqdn()
Aliases
:
fullHostName
Arguments
None.
Returned value
Returns the fully qualified domain name of the ClickHouse server.
String
Examples
Usage example
sql title=Query
SELECT fqdn()
response title=Response
ββFQDN()βββββββββββββββββββββββββββ
β clickhouse.us-east-2.internal β
βββββββββββββββββββββββββββββββββββ
MACNumToString {#MACNumToString}
Introduced in: v1.1
Interprets a
UInt64
number as a MAC address in big endian format.
Returns the corresponding MAC address in format
AA:BB:CC:DD:EE:FF
(colon-separated numbers in hexadecimal form) as string.
Syntax
sql
MACNumToString(num)
Arguments
num
β UInt64 number.
UInt64
Returned value
Returns a MAC address in format AA:BB:CC:DD:EE:FF.
String
Examples
Usage example
sql title=Query
SELECT MACNumToString(149809441867716) AS mac_address;
response title=Response
ββmac_addressββββββββ
β 88:00:11:22:33:44 β
βββββββββββββββββββββ
MACStringToNum {#MACStringToNum}
Introduced in: v1.1
The inverse function of MACNumToString. If the MAC address has an invalid format, it returns 0.
Syntax
sql
MACStringToNum(s)
Arguments
s
β MAC address string.
String
Returned value
Returns a UInt64 number.
UInt64
Examples
Usage example
sql title=Query
SELECT MACStringToNum('01:02:03:04:05:06') AS mac_numeric;
response title=Response
1108152157446
MACStringToOUI {#MACStringToOUI}
Introduced in: v1.1
Given a MAC address in format AA:BB:CC:DD:EE:FF (colon-separated numbers in hexadecimal form), returns the first three octets as a UInt64 number. If the MAC address has an invalid format, it returns 0.
Syntax
sql
MACStringToOUI(s)
Arguments
s
β MAC address string.
String
Returned value
First three octets as UInt64 number.
UInt64
Examples
Usage example
sql title=Query
SELECT MACStringToOUI('00:50:56:12:34:56') AS oui;
response title=Response
20566
__filterContains {#__filterContains}
Introduced in: v25.10
Special function for JOIN runtime filtering.
Syntax
sql
__filterContains(filter_name, key)
Arguments
filter_name
β Internal name of runtime filter. It is built by BuildRuntimeFilterStep.
String
key
β Value of any type that is checked to be present in the filter
Returned value
True if the key was found in the filter
Bool
Examples
Example | {"source_file": "other-functions.md"} | [
-0.046220723539590836,
-0.021264906972646713,
-0.012918384745717049,
-0.0054944949224591255,
-0.04672908037900925,
-0.02432420291006565,
0.036569319665431976,
-0.026442069560289383,
0.019016364589333534,
-0.01074761152267456,
0.009440380148589611,
-0.03078054077923298,
0.05701175332069397,
... |
56789333-05a7-4265-b110-1c6c778b9d0a | key
β Value of any type that is checked to be present in the filter
Returned value
True if the key was found in the filter
Bool
Examples
Example
sql title=Query
This function is not supposed to be used in user queries. It might be added to query plan during optimization.
```response title=Response
```
__patchPartitionID {#__patchPartitionID}
Introduced in: v25.5
Internal function. Receives the name of a part and a hash of patch part's column names. Returns the name of partition of patch part. The argument must be a correct name of part, the behaviour is undefined otherwise.
Syntax
```sql
```
Arguments
None.
Returned value
Examples
authenticatedUser {#authenticatedUser}
Introduced in: v25.11
If the session user has been switched using the EXECUTE AS command, this function returns the name of the original user that was used for authentication and creating the session.
Alias: authUser()
Syntax
sql
authenticatedUser()
Aliases
:
authUser
Arguments
None.
Returned value
The name of the authenticated user.
String
Examples
Usage example
sql title=Query
EXECUTE as u1;
SELECT currentUser(), authenticatedUser();
response title=Response
ββcurrentUser()ββ¬βauthenticatedUser()ββ
β u1 β default β
βββββββββββββββββ΄ββββββββββββββββββββββ
bar {#bar}
Introduced in: v1.1
Builds a bar chart.
Draws a band with width proportional to (x - min) and equal to width characters when x = max.
The band is drawn with accuracy to one eighth of a symbol.
Syntax
sql
bar(x, min, max[, width])
Arguments
x
β Size to display.
(U)Int*
or
Float*
or
Decimal
min
β The minimum value.
(U)Int*
or
Float*
or
Decimal
max
β The maximum value.
(U)Int*
or
Float*
or
Decimal
width
β Optional. The width of the bar in characters. The default is
80
.
const (U)Int*
or
const Float*
or
const Decimal
Returned value
Returns a unicode-art bar string.
String
Examples
Usage example
sql title=Query
SELECT
toHour(EventTime) AS h,
count() AS c,
bar(c, 0, 600000, 20) AS bar
FROM test.hits
GROUP BY h
ORDER BY h ASC | {"source_file": "other-functions.md"} | [
-0.06268076598644257,
0.056269217282533646,
-0.015619475394487381,
0.015053466893732548,
-0.06466474384069443,
-0.03738783672451973,
0.16689816117286682,
-0.00809202715754509,
-0.0432821661233902,
0.007079035975039005,
0.004738028161227703,
-0.0818510577082634,
0.018433988094329834,
-0.062... |
c6f7096c-cc6b-48b6-a116-469c65b92aca | Examples
Usage example
sql title=Query
SELECT
toHour(EventTime) AS h,
count() AS c,
bar(c, 0, 600000, 20) AS bar
FROM test.hits
GROUP BY h
ORDER BY h ASC
response title=Response
βββhββ¬ββββββcββ¬βbarβββββββββββββββββ
β 0 β 292907 β ββββββββββ β
β 1 β 180563 β ββββββ β
β 2 β 114861 β ββββ β
β 3 β 85069 β βββ β
β 4 β 68543 β βββ β
β 5 β 78116 β βββ β
β 6 β 113474 β ββββ β
β 7 β 170678 β ββββββ β
β 8 β 278380 β ββββββββββ β
β 9 β 391053 β βββββββββββββ β
β 10 β 457681 β ββββββββββββββββ β
β 11 β 493667 β βββββββββββββββββ β
β 12 β 509641 β βββββββββββββββββ β
β 13 β 522947 β ββββββββββββββββββ β
β 14 β 539954 β ββββββββββββββββββ β
β 15 β 528460 β ββββββββββββββββββ β
β 16 β 539201 β ββββββββββββββββββ β
β 17 β 523539 β ββββββββββββββββββ β
β 18 β 506467 β βββββββββββββββββ β
β 19 β 520915 β ββββββββββββββββββ β
β 20 β 521665 β ββββββββββββββββββ β
β 21 β 542078 β ββββββββββββββββββ β
β 22 β 493642 β βββββββββββββββββ β
β 23 β 400397 β ββββββββββββββ β
ββββββ΄βββββββββ΄βββββββββββββββββββββ
blockNumber {#blockNumber}
Introduced in: v1.1
Returns a monotonically increasing sequence number of the
block
containing the row.
The returned block number is updated on a best-effort basis, i.e. it may not be fully accurate.
Syntax
sql
blockNumber()
Arguments
None.
Returned value
Sequence number of the data block where the row is located.
UInt64
Examples
Basic usage
sql title=Query
SELECT blockNumber()
FROM
(
SELECT *
FROM system.numbers
LIMIT 10
) SETTINGS max_block_size = 2
response title=Response
ββblockNumber()ββ
β 7 β
β 7 β
βββββββββββββββββ
ββblockNumber()ββ
β 8 β
β 8 β
βββββββββββββββββ
ββblockNumber()ββ
β 9 β
β 9 β
βββββββββββββββββ
ββblockNumber()ββ
β 10 β
β 10 β
βββββββββββββββββ
ββblockNumber()ββ
β 11 β
β 11 β
βββββββββββββββββ
blockSerializedSize {#blockSerializedSize}
Introduced in: v20.3
Returns the uncompressed size in bytes of a block of values on disk.
Syntax
sql
blockSerializedSize(x1[, x2[, ...]])
Arguments
x1[, x2, ...]
β Any number of values for which to get the uncompressed size of the block.
Any
Returned value
Returns the number of bytes that will be written to disk for a block of values without compression.
UInt64
Examples
Usage example
sql title=Query
SELECT blockSerializedSize(maxState(1)) AS x;
response title=Response
ββxββ
β 2 β
βββββ
blockSize {#blockSize}
Introduced in: v1.1
In ClickHouse, queries are processed in
blocks
(chunks).
This function returns the size (row count) of the block the function is called on.
Syntax
sql
blockSize()
Arguments
None.
Returned value
Returns the number of rows in the current block.
UInt64
Examples
Usage example | {"source_file": "other-functions.md"} | [
0.0019068153342232108,
-0.05073399841785431,
-0.004524406976997852,
0.12088035047054291,
-0.07392144203186035,
0.008408370427787304,
0.03217827156186104,
0.0051246038638055325,
0.018338117748498917,
0.03419085219502449,
0.012855453416705132,
-0.05955541878938675,
0.05486864596605301,
-0.10... |
b07d2583-265f-427c-ac4a-721dd593d513 | Syntax
sql
blockSize()
Arguments
None.
Returned value
Returns the number of rows in the current block.
UInt64
Examples
Usage example
sql title=Query
SELECT blockSize()
FROM system.numbers LIMIT 5
response title=Response
ββblockSize()ββ
β 5 β
β 5 β
β 5 β
β 5 β
β 5 β
βββββββββββββββ
byteSize {#byteSize}
Introduced in: v21.1
Returns an estimation of the uncompressed byte size of its arguments in memory.
For
String
arguments, the function returns the string length + 8 (length).
If the function has multiple arguments, the function accumulates their byte sizes.
Syntax
sql
byteSize(arg1[, arg2, ...])
Arguments
arg1[, arg2, ...]
β Values of any data type for which to estimate the uncompressed byte size.
Any
Returned value
Returns an estimation of the byte size of the arguments in memory.
UInt64
Examples
Usage example
sql title=Query
SELECT byteSize('string')
response title=Response
ββbyteSize('string')ββ
β 15 β
ββββββββββββββββββββββ
Multiple arguments
sql title=Query
SELECT byteSize(NULL, 1, 0.3, '')
response title=Response
ββbyteSize(NULL, 1, 0.3, '')ββ
β 19 β
ββββββββββββββββββββββββββββββ
catboostEvaluate {#catboostEvaluate}
Introduced in: v22.9
Evaluate an external catboost model.
CatBoost
is an open-source gradient boosting library developed by Yandex for machine learning.
Accepts a path to a catboost model and model arguments (features).
Prerequisites
Build the catboost evaluation library
Before evaluating catboost models, the
libcatboostmodel.<so|dylib>
library must be made available. See
CatBoost documentation
how to compile it.
Next, specify the path to
libcatboostmodel.<so|dylib>
in the clickhouse configuration:
xml
<clickhouse>
...
<catboost_lib_path>/path/to/libcatboostmodel.so</catboost_lib_path>
...
</clickhouse>
For security and isolation reasons, the model evaluation does not run in the server process but in the clickhouse-library-bridge process.
At the first execution of
catboostEvaluate()
, the server starts the library bridge process if it is not running already. Both processes
communicate using a HTTP interface. By default, port
9012
is used. A different port can be specified as follows - this is useful if port
9012
is already assigned to a different service.
xml
<library_bridge>
<port>9019</port>
</library_bridge>
Train a catboost model using libcatboost
See
Training and applying models
for how to train catboost models from a training data set.
Syntax
sql
catboostEvaluate(path_to_model, feature_1[, feature_2, ..., feature_n])
Arguments
path_to_model
β Path to catboost model.
const String
feature
β One or more model features/arguments.
Float*
Returned value
Returns the model evaluation result.
Float64
Examples
catboostEvaluate | {"source_file": "other-functions.md"} | [
-0.003733888966962695,
0.0033012484200298786,
-0.08554492890834808,
0.03388837352395058,
-0.05311008542776108,
-0.06643491238355637,
0.08292634040117264,
0.03484788537025452,
-0.05069589987397194,
-0.0077086929231882095,
-0.06271090358495712,
0.016278868541121483,
0.015111560933291912,
-0.... |
b18d606c-2546-4874-83bd-9365c55d7302 | feature
β One or more model features/arguments.
Float*
Returned value
Returns the model evaluation result.
Float64
Examples
catboostEvaluate
sql title=Query
SELECT catboostEvaluate('/root/occupy.bin', Temperature, Humidity, Light, CO2, HumidityRatio) AS prediction FROM occupancy LIMIT 1
response title=Response
4.695691092573497
colorOKLCHToSRGB {#colorOKLCHToSRGB}
Introduced in: v25.7
Converts a colour from the
OKLCH
perceptual colour space to the familiar
sRGB
colour space.
If
L
is outside the range
[0...1]
,
C
is negative, or
H
is outside the range
[0...360]
, the result is implementation-defined.
:::note
OKLCH
is a cylindrical version of the OKLab colour space.
It's three coordinates are
L
(the lightness in the range
[0...1]
),
C
(chroma
>= 0
) and
H
(hue in degrees from
[0...360]
)**.
OKLab/OKLCH is designed to be perceptually uniform while remaining cheap to compute.
:::
The conversion is the inverse of
colorSRGBToOKLCH
:
1) OKLCH to OKLab.
2) OKLab to Linear sRGB
3) Linear sRGB to sRGB
The second argument gamma is used at the last stage.
For references of colors in OKLCH space, and how they correspond to sRGB colors please see
https://oklch.com/
.
Syntax
sql
colorOKLCHToSRGB(tuple [, gamma])
Arguments
tuple
β A tuple of three numeric values
L
,
C
,
H
, where
L
is in the range
[0...1]
,
C >= 0
and
H
is in the range
[0...360]
.
Tuple(Float64, Float64, Float64)
gamma
β Optional. The exponent that is used to transform linear sRGB back to sRGB by applying
(x ^ (1 / gamma)) * 255
for each channel
x
. Defaults to
2.2
.
Float64
Returned value
Returns a tuple (R, G, B) representing sRGB color values.
Tuple(Float64, Float64, Float64)
Examples
Convert OKLCH to sRGB
sql title=Query
SELECT colorOKLCHToSRGB((0.4466, 0.0991, 45.44), 2.2) AS rgb
WITH colorOKLCHToSRGB((0.7, 0.1, 54)) as t SELECT tuple(toUInt8(t.1), toUInt8(t.2), toUInt8(t.3)) AS RGB
response title=Response
ββrgbβββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β (127.03349738778945,66.06672044472008,37.11802592155851) β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ββRGBβββββββββββ
β (205,139,97) β
ββββββββββββββββ
colorSRGBToOKLCH {#colorSRGBToOKLCH}
Introduced in: v25.7
Converts a colour encoded in the
sRGB
colour space to the perceptually uniform
OKLCH
colour space.
If any input channel is outside
[0...255]
or the gamma value is non-positive, the behaviour is implementation-defined.
:::note
OKLCH
is a cylindrical version of the OKLab colour space.
It's three coordinates are
L
(the lightness in the range
[0...1]
),
C
(chroma
>= 0
) and
H
(the hue in degrees from
[0...360]
).
OKLab/OKLCH is designed to be perceptually uniform while remaining cheap to compute.
:::
The conversion consists of three stages:
1) sRGB to Linear sRGB
2) Linear sRGB to OKLab
3) OKLab to OKLCH. | {"source_file": "other-functions.md"} | [
0.031642090529203415,
0.04724857583642006,
-0.015829218551516533,
0.07474742084741592,
0.048990823328495026,
-0.005231090355664492,
0.025092139840126038,
0.049804363399744034,
-0.018279679119586945,
-0.037847016006708145,
0.019925853237509727,
-0.16684405505657196,
0.08516453206539154,
-0.... |
a2cc011f-3133-494f-ae39-cee3f39567ef | The conversion consists of three stages:
1) sRGB to Linear sRGB
2) Linear sRGB to OKLab
3) OKLab to OKLCH.
For references of colors in the OKLCH space, and how they correspond to sRGB colors, please see
https://OKLCH.com/
.
Syntax
sql
colorSRGBToOKLCH(tuple[, gamma])
Arguments
tuple
β Tuple of three values R, G, B in the range
[0...255]
.
Tuple(UInt8, UInt8, UInt8)
gamma
β Optional. Exponent that is used to linearize sRGB by applying
(x / 255)^gamma
to each channel
x
. Defaults to
2.2
.
Float64
Returned value
Returns a tuple (L, C, H) representing the OKLCH color space values.
Tuple(Float64, Float64, Float64)
Examples
Convert sRGB to OKLCH
sql title=Query
SELECT colorSRGBToOKLCH((128, 64, 32), 2.2) AS lch
response title=Response
ββlchββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β (0.4436238384931984,0.10442699545678624,45.907345481930236) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
connectionId {#connectionId}
Introduced in: v21.3
Returns the connection ID of the client that submitted the current query.
This function is most useful in debugging scenarios.
It was created for compatibility with MySQL's
CONNECTION_ID
function.
It is not typically used in production queries.
Syntax
sql
connectionId()
Arguments
None.
Returned value
Returns the connection ID of the current client.
UInt64
Examples
Usage example
sql title=Query
SELECT connectionId();
response title=Response
ββconnectionId()ββ
β 0 β
ββββββββββββββββββ
countDigits {#countDigits}
Introduced in: v20.8
Returns the number of decimal digits needed to represent a value.
:::note
This function takes into account the scales of decimal values i.e., it calculates the result over the underlying integer type which is
(value * scale)
.
For example:
-
countDigits(42) = 2
-
countDigits(42.000) = 5
-
countDigits(0.04200) = 4
:::
:::tip
You can check decimal overflow for
Decimal64
with
countDigits(x) > 18
,
although it is slower than
isDecimalOverflow
.
:::
Syntax
sql
countDigits(x)
Arguments
x
β An integer or decimal value.
(U)Int*
or
Decimal
Returned value
Returns the number of digits needed to represent
x
.
UInt8
Examples
Usage example
sql title=Query
SELECT countDigits(toDecimal32(1, 9)), countDigits(toDecimal32(-1, 9)),
countDigits(toDecimal64(1, 18)), countDigits(toDecimal64(-1, 18)),
countDigits(toDecimal128(1, 38)), countDigits(toDecimal128(-1, 38)); | {"source_file": "other-functions.md"} | [
0.03198384493589401,
-0.06654395908117294,
-0.02571992762386799,
0.0030516483820974827,
0.027435045689344406,
-0.015573501586914062,
0.10980980098247528,
0.013387910090386868,
-0.010638536885380745,
-0.02182823047041893,
-0.025127781555056572,
-0.06036746874451637,
0.113146111369133,
-0.06... |
579139d3-67c7-47b1-8f6b-e7bccbe384e0 | response title=Response
ββcountDigits(toDecimal32(1, 9))ββ¬βcountDigits(toDecimal32(-1, 9))ββ¬βcountDigits(toDecimal64(1, 18))ββ¬βcountDigits(toDecimal64(-1, 18))ββ¬βcountDigits(toDecimal128(1, 38))ββ¬βcountDigits(toDecimal128(-1, 38))ββ
β 10 β 10 β 19 β 19 β 39 β 39 β
ββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββ
currentDatabase {#currentDatabase}
Introduced in: v1.1
Returns the name of the current database.
Useful in table engine parameters of
CREATE TABLE
queries where you need to specify the database.
Also see the
SET
statement
.
Syntax
sql
currentDatabase()
Aliases
:
current_database
,
SCHEMA
,
DATABASE
Arguments
None.
Returned value
Returns the current database name.
String
Examples
Usage example
sql title=Query
SELECT currentDatabase()
response title=Response
ββcurrentDatabase()ββ
β default β
βββββββββββββββββββββ
currentProfiles {#currentProfiles}
Introduced in: v21.9
Returns an array of the setting profiles for the current user.
Syntax
sql
currentProfiles()
Arguments
None.
Returned value
Returns an array of setting profiles for the current user.
Array(String)
Examples
Usage example
sql title=Query
SELECT currentProfiles();
response title=Response
ββcurrentProfiles()ββββββββββββββββββββββββββββββ
β ['default', 'readonly_user', 'web_analytics'] β
βββββββββββββββββββββββββββββββββββββββββββββββββ
currentQueryID {#currentQueryID}
Introduced in: v
Returns current Query id.
Syntax
sql
currentQueryID()
Aliases
:
current_query_id
Arguments
None.
Returned value
Examples
Example
sql title=Query
SELECT currentQueryID();
response title=Response
ββcurrentQueryID()ββββββββββββββββββββββ
β 1280d0e8-1a08-4524-be6e-77975bb68e7d β
ββββββββββββββββββββββββββββββββββββββββ
currentRoles {#currentRoles}
Introduced in: v21.9
Returns an array of the roles which are assigned to the current user.
Syntax
sql
currentRoles()
Arguments
None.
Returned value
Returns an array of the roles which are assigned to the current user.
Array(String)
Examples
Usage example
sql title=Query
SELECT currentRoles();
response title=Response
ββcurrentRoles()ββββββββββββββββββββββββββββββββββ
β ['sql-console-role:jane.smith@clickhouse.com'] β
ββββββββββββββββββββββββββββββββββββββββββββββββββ
currentSchemas {#currentSchemas}
Introduced in: v23.7
Same as function
currentDatabase
but
- accepts a boolean argument which is ignored
- returns the database name as an array with a single value.
Function
currentSchemas
only exists for compatibility with PostgreSQL.
Please use
currentDatabase
instead. | {"source_file": "other-functions.md"} | [
0.0036889021284878254,
-0.08160091191530228,
-0.03458014130592346,
0.05464298650622368,
-0.08984006196260452,
-0.0046484703198075294,
0.0944988802075386,
0.07549183815717697,
-0.07524454593658447,
-0.014523091726005077,
-0.02257586643099785,
-0.11753113567829132,
0.08173221349716187,
-0.07... |
3785781c-44b8-48dc-985f-f3866d445caf | Function
currentSchemas
only exists for compatibility with PostgreSQL.
Please use
currentDatabase
instead.
Also see the
SET
statement
.
Syntax
sql
currentSchemas(bool)
Aliases
:
current_schemas
Arguments
bool
β A boolean value, which is ignored.
Bool
Returned value
Returns a single-element array with the name of the current database.
Array(String)
Examples
Usage example
sql title=Query
SELECT currentSchemas(true)
response title=Response
ββcurrentSchemas(true)ββ
β ['default'] β
ββββββββββββββββββββββββ
currentUser {#currentUser}
Introduced in: v20.1
Returns the name of the current user.
In case of a distributed query, the name of the user who initiated the query is returned.
Syntax
sql
currentUser()
Aliases
:
user
,
current_user
Arguments
None.
Returned value
Returns the name of the current user, otherwise the login of the user who initiated the query.
String
Examples
Usage example
sql title=Query
SELECT currentUser()
response title=Response
ββcurrentUser()ββ
β default β
βββββββββββββββββ
defaultProfiles {#defaultProfiles}
Introduced in: v21.9
Returns an array of default setting profile names for the current user.
Syntax
sql
defaultProfiles()
Arguments
None.
Returned value
Returns an array of default setting profile names for the current user.
Array(String)
Examples
Usage example
sql title=Query
SELECT defaultProfiles();
response title=Response
ββdefaultProfiles()ββ
β ['default'] β
βββββββββββββββββββββ
defaultRoles {#defaultRoles}
Introduced in: v21.9
Returns an array of default roles for the current user.
Syntax
sql
defaultRoles()
Arguments
None.
Returned value
Returns an array of default roles for the current user.
Array(String)
Examples
Usage example
sql title=Query
SELECT defaultRoles();
response title=Response
ββdefaultRoles()ββββββββββββββββββββββββββββββββββ
β ['sql-console-role:jane.smith@clickhouse.com'] β
ββββββββββββββββββββββββββββββββββββββββββββββββββ
defaultValueOfArgumentType {#defaultValueOfArgumentType}
Introduced in: v1.1
Returns the default value for a given data type.
Does not include default values for custom columns set by the user.
Syntax
sql
defaultValueOfArgumentType(expression)
Arguments
expression
β Arbitrary type of value or an expression that results in a value of an arbitrary type.
Any
Returned value
Returns
0
for numbers, an empty string for strings or
NULL
for Nullable types.
UInt8
or
String
or
NULL
Examples
Usage example
sql title=Query
SELECT defaultValueOfArgumentType(CAST(1 AS Int8));
response title=Response
ββdefaultValueOfArgumentType(CAST(1, 'Int8'))ββ
β 0 β
βββββββββββββββββββββββββββββββββββββββββββββββ
Nullable example
sql title=Query
SELECT defaultValueOfArgumentType(CAST(1 AS Nullable(Int8))); | {"source_file": "other-functions.md"} | [
0.026830535382032394,
0.003742747474461794,
-0.028219662606716156,
0.021934736520051956,
-0.08565591275691986,
-0.046950146555900574,
0.15615375339984894,
0.021926086395978928,
-0.023768411949276924,
0.011426610872149467,
-0.05000863969326019,
-0.04372195154428482,
-0.028790857642889023,
-... |
3ecfca1d-fbef-4a4d-97dd-d4f3b7914513 | Nullable example
sql title=Query
SELECT defaultValueOfArgumentType(CAST(1 AS Nullable(Int8)));
response title=Response
ββdefaultValueOfArgumentType(CAST(1, 'Nullable(Int8)'))ββ
β α΄Ία΅α΄Έα΄Έ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
defaultValueOfTypeName {#defaultValueOfTypeName}
Introduced in: v1.1
Returns the default value for the given type name.
Syntax
sql
defaultValueOfTypeName(type)
Arguments
type
β A string representing a type name.
String
Returned value
Returns the default value for the given type name:
0
for numbers, an empty string for strings, or
NULL
for Nullable
UInt8
or
String
or
NULL
Examples
Usage example
sql title=Query
SELECT defaultValueOfTypeName('Int8');
response title=Response
ββdefaultValueOfTypeName('Int8')ββ
β 0 β
ββββββββββββββββββββββββββββββββββ
Nullable example
sql title=Query
SELECT defaultValueOfTypeName('Nullable(Int8)');
response title=Response
ββdefaultValueOfTypeName('Nullable(Int8)')ββ
β α΄Ία΅α΄Έα΄Έ β
ββββββββββββββββββββββββββββββββββββββββββββ
displayName {#displayName}
Introduced in: v22.11
Returns the value of
display_name
from
config
or the server's Fully Qualified Domain Name (FQDN) if not set.
Syntax
sql
displayName()
Arguments
None.
Returned value
Returns the value of
display_name
from config or server FQDN if not set.
String
Examples
Usage example
sql title=Query
SELECT displayName();
response title=Response
ββdisplayName()ββ
β production β
βββββββββββββββββ
dumpColumnStructure {#dumpColumnStructure}
Introduced in: v1.1
Outputs a detailed description of the internal structure of a column and its data type.
Syntax
sql
dumpColumnStructure(x)
Arguments
x
β Value for which to get the description of.
Any
Returned value
Returns a description of the column structure used for representing the value.
String
Examples
Usage example
sql title=Query
SELECT dumpColumnStructure(CAST('2018-01-01 01:02:03', 'DateTime'));
response title=Response
ββdumpColumnStructure(CAST('2018-01-01 01:02:03', 'DateTime'))ββ
β DateTime, Const(size = 1, UInt32(size = 1)) β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
enabledProfiles {#enabledProfiles}
Introduced in: v21.9
Returns an array of setting profile names which are enabled for the current user.
Syntax
sql
enabledProfiles()
Arguments
None.
Returned value
Returns an array of setting profile names which are enabled for the current user.
Array(String)
Examples
Usage example
sql title=Query
SELECT enabledProfiles();
response title=Response
ββenabledProfiles()ββββββββββββββββββββββββββββββββββββββββββββββββββ
β ['default', 'readonly_user', 'web_analytics', 'batch_processing'] β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
enabledRoles {#enabledRoles} | {"source_file": "other-functions.md"} | [
-0.012767400592565536,
-0.014639840461313725,
-0.052918437868356705,
0.0445159412920475,
-0.09923303127288818,
-0.00023653141397517174,
0.08998048305511475,
0.0839243158698082,
-0.05066072195768356,
-0.08976906538009644,
-0.009878790937364101,
-0.048302434384822845,
-0.003012831322848797,
... |
62e6e5a6-0da6-4c31-aee0-33915aeff0b9 | enabledRoles {#enabledRoles}
Introduced in: v21.9
Returns an array of the roles which are enabled for the current user.
Syntax
sql
enabledRoles()
Arguments
None.
Returned value
Returns an array of role names which are enabled for the current user.
Array(String)
Examples
Usage example
sql title=Query
SELECT enabledRoles();
response title=Response
ββenabledRoles()ββββββββββββββββββββββββββββββββββββββββββββββββββ
β ['general_data', 'sql-console-role:jane.smith@clickhouse.com'] β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
errorCodeToName {#errorCodeToName}
Introduced in: v20.12
Returns the textual name of a numeric ClickHouse error code.
The mapping from numeric error codes to error names is available
here
.
Syntax
sql
errorCodeToName(error_code)
Arguments
error_code
β ClickHouse error code.
(U)Int*
or
Float*
or
Decimal
Returned value
Returns the textual name of
error_code
.
String
Examples
Usage example
sql title=Query
SELECT errorCodeToName(252);
response title=Response
ββerrorCodeToName(252)ββ
β TOO_MANY_PARTS β
ββββββββββββββββββββββββ
file {#file}
Introduced in: v21.3
Reads a file as a string and loads the data into the specified column.
The file content is not interpreted.
Also see the
file
table function.
Syntax
sql
file(path[, default])
Arguments
path
β The path of the file relative to the
user_files_path
. Supports wildcards
*
,
**
,
?
,
{abc,def}
and
{N..M}
where
N
,
M
are numbers and
'abc', 'def'
are strings.
String
default
β The value returned if the file does not exist or cannot be accessed.
String
or
NULL
Returned value
Returns the file content as a string.
String
Examples
Insert files into a table
sql title=Query
INSERT INTO table SELECT file('a.txt'), file('b.txt');
```response title=Response
```
filesystemAvailable {#filesystemAvailable}
Introduced in: v20.1
Returns the amount of free space in the filesystem hosting the database persistence.
The returned value is always smaller than the total free space (
filesystemUnreserved
) because some space is reserved for the operating system.
Syntax
sql
filesystemAvailable([disk_name])
Arguments
disk_name
β Optional. The disk name to find the amount of free space for. If omitted, uses the default disk.
String
or
FixedString
Returned value
Returns the amount of remaining space available in bytes.
UInt64
Examples
Usage example
sql title=Query
SELECT formatReadableSize(filesystemAvailable()) AS "Available space";
response title=Response
ββAvailable spaceββ
β 30.75 GiB β
βββββββββββββββββββ
filesystemCapacity {#filesystemCapacity}
Introduced in: v20.1
Returns the capacity of the filesystem in bytes.
Needs the
path
to the data directory to be configured.
Syntax
sql
filesystemCapacity([disk_name])
Arguments | {"source_file": "other-functions.md"} | [
0.0050421180203557014,
-0.037919607013463974,
-0.01867084577679634,
0.06965891271829605,
-0.07076183706521988,
-0.013818583451211452,
0.08373311907052994,
0.0534735731780529,
-0.14180736243724823,
-0.07453007251024246,
0.028031667694449425,
0.030511867254972458,
0.07649502158164978,
-0.025... |
f29607e6-0362-4f24-b6ce-25f824c55508 | Introduced in: v20.1
Returns the capacity of the filesystem in bytes.
Needs the
path
to the data directory to be configured.
Syntax
sql
filesystemCapacity([disk_name])
Arguments
disk_name
β Optional. The disk name to get the capacity for. If omitted, uses the default disk.
String
or
FixedString
Returned value
Returns the capacity of the filesystem in bytes.
UInt64
Examples
Usage example
sql title=Query
SELECT formatReadableSize(filesystemCapacity()) AS "Capacity";
response title=Response
ββCapacityβββ
β 39.32 GiB β
βββββββββββββ
filesystemUnreserved {#filesystemUnreserved}
Introduced in: v22.12
Returns the total amount of free space on the filesystem hosting the database persistence (previously
filesystemFree
).
See also
filesystemAvailable
.
Syntax
sql
filesystemUnreserved([disk_name])
Arguments
disk_name
β Optional. The disk name for which to find the total amount of free space. If omitted, uses the default disk.
String
or
FixedString
Returned value
Returns the amount of free space in bytes.
UInt64
Examples
Usage example
sql title=Query
SELECT formatReadableSize(filesystemUnreserved()) AS "Free space";
response title=Response
ββFree spaceββ
β 32.39 GiB β
ββββββββββββββ
finalizeAggregation {#finalizeAggregation}
Introduced in: v1.1
Given an aggregation state, this function returns the result of aggregation (or the finalized state when using a
-State
combinator).
Syntax
sql
finalizeAggregation(state)
Arguments
state
β State of aggregation.
AggregateFunction
Returned value
Returns the finalized result of aggregation.
Any
Examples
Usage example
sql title=Query
SELECT finalizeAggregation(arrayReduce('maxState', [1, 2, 3]));
response title=Response
ββfinalizeAggregation(arrayReduce('maxState', [1, 2, 3]))ββ
β 3 β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Combined with initializeAggregation
sql title=Query
WITH initializeAggregation('sumState', number) AS one_row_sum_state
SELECT
number,
finalizeAggregation(one_row_sum_state) AS one_row_sum,
runningAccumulate(one_row_sum_state) AS cumulative_sum
FROM numbers(5);
response title=Response
ββnumberββ¬βone_row_sumββ¬βcumulative_sumββ
β 0 β 0 β 0 β
β 1 β 1 β 1 β
β 2 β 2 β 3 β
β 3 β 3 β 6 β
β 4 β 4 β 10 β
ββββββββββ΄ββββββββββββββ΄βββββββββββββββββ
formatQuery {#formatQuery}
Introduced in: v
Returns a formatted, possibly multi-line, version of the given SQL query. Throws in case of a parsing error.
[example:multiline]
Syntax
sql
formatQuery(query)
Arguments
query
β The SQL query to be formatted.
String
Returned value
The formatted query
String
Examples
multiline
sql title=Query
SELECT formatQuery('select a, b FRom tab WHERE a > 3 and b < 3'); | {"source_file": "other-functions.md"} | [
-0.019967006519436836,
-0.030332930386066437,
-0.09265045076608658,
0.1253328174352646,
0.031825922429561615,
-0.023078477010130882,
0.05526620149612427,
0.11547640711069107,
0.011876774951815605,
0.04794822260737419,
0.018235739320516586,
0.033976390957832336,
0.08901840448379517,
-0.0504... |
eba2fd6d-b6f4-4e91-8613-3e913eb36ed1 | Returned value
The formatted query
String
Examples
multiline
sql title=Query
SELECT formatQuery('select a, b FRom tab WHERE a > 3 and b < 3');
response title=Response
SELECT
a,
b
FROM tab
WHERE (a > 3) AND (b < 3)
formatQueryOrNull {#formatQueryOrNull}
Introduced in: v
Returns a formatted, possibly multi-line, version of the given SQL query. Returns NULL in case of a parsing error.
[example:multiline]
Syntax
sql
formatQueryOrNull(query)
Arguments
query
β The SQL query to be formatted.
String
Returned value
The formatted query
String
Examples
multiline
sql title=Query
SELECT formatQuery('select a, b FRom tab WHERE a > 3 and b < 3');
response title=Response
SELECT
a,
b
FROM tab
WHERE (a > 3) AND (b < 3)
formatQuerySingleLine {#formatQuerySingleLine}
Introduced in: v
Like formatQuery() but the returned formatted string contains no line breaks. Throws in case of a parsing error.
[example:multiline]
Syntax
sql
formatQuerySingleLine(query)
Arguments
query
β The SQL query to be formatted.
String
Returned value
The formatted query
String
Examples
multiline
sql title=Query
SELECT formatQuerySingleLine('select a, b FRom tab WHERE a > 3 and b < 3');
response title=Response
SELECT a, b FROM tab WHERE (a > 3) AND (b < 3)
formatQuerySingleLineOrNull {#formatQuerySingleLineOrNull}
Introduced in: v
Like formatQuery() but the returned formatted string contains no line breaks. Returns NULL in case of a parsing error.
[example:multiline]
Syntax
sql
formatQuerySingleLineOrNull(query)
Arguments
query
β The SQL query to be formatted.
String
Returned value
The formatted query
String
Examples
multiline
sql title=Query
SELECT formatQuerySingleLine('select a, b FRom tab WHERE a > 3 and b < 3');
response title=Response
SELECT a, b FROM tab WHERE (a > 3) AND (b < 3)
formatReadableDecimalSize {#formatReadableDecimalSize}
Introduced in: v22.11
Given a size (number of bytes), this function returns a readable, rounded size with suffix (KB, MB, etc.) as a string.
The opposite operations of this function are
parseReadableSize
.
Syntax
sql
formatReadableDecimalSize(x)
Arguments
x
β Size in bytes.
UInt64
Returned value
Returns a readable, rounded size with suffix as a string.
String
Examples
Format file sizes
sql title=Query
SELECT
arrayJoin([1, 1024, 1024*1024, 192851925]) AS filesize_bytes,
formatReadableDecimalSize(filesize_bytes) AS filesize
response title=Response
ββfilesize_bytesββ¬βfilesizeββββ
β 1 β 1.00 B β
β 1024 β 1.02 KB β
β 1048576 β 1.05 MB β
β 192851925 β 192.85 MB β
ββββββββββββββββββ΄βββββββββββββ
formatReadableQuantity {#formatReadableQuantity}
Introduced in: v20.10
Given a number, this function returns a rounded number with suffix (thousand, million, billion, etc.) as a string. | {"source_file": "other-functions.md"} | [
0.0018495031399652362,
-0.0029012630693614483,
-0.01949838548898697,
-0.03834626078605652,
-0.14179225265979767,
0.03385476768016815,
0.008161218836903572,
0.003344824770465493,
-0.0066230325028300285,
0.015814337879419327,
-0.04975482076406479,
-0.045598242431879044,
0.05221741273999214,
... |
08c29bd7-71d2-4ff0-96e3-ba2ac462a1f6 | formatReadableQuantity {#formatReadableQuantity}
Introduced in: v20.10
Given a number, this function returns a rounded number with suffix (thousand, million, billion, etc.) as a string.
This function accepts any numeric type as input, but internally it casts them to
Float64
.
Results might be suboptimal with large values.
Syntax
sql
formatReadableQuantity(x)
Arguments
x
β A number to format.
UInt64
Returned value
Returns a rounded number with suffix as a string.
String
Examples
Format numbers with suffixes
sql title=Query
SELECT
arrayJoin([1024, 1234 * 1000, (4567 * 1000) * 1000, 98765432101234]) AS number,
formatReadableQuantity(number) AS number_for_humans
response title=Response
ββββββββββnumberββ¬βnumber_for_humansββ
β 1024 β 1.02 thousand β
β 1234000 β 1.23 million β
β 4567000000 β 4.57 billion β
β 98765432101234 β 98.77 trillion β
ββββββββββββββββββ΄ββββββββββββββββββββ
formatReadableSize {#formatReadableSize}
Introduced in: v1.1
Given a size (number of bytes), this function returns a readable, rounded size with suffix (KiB, MiB, etc.) as string.
The opposite operations of this function are
parseReadableSize
,
parseReadableSizeOrZero
, and
parseReadableSizeOrNull
.
This function accepts any numeric type as input, but internally it casts them to
Float64
. Results might be suboptimal with large values.
Syntax
sql
formatReadableSize(x)
Aliases
:
FORMAT_BYTES
Arguments
x
β Size in bytes.
UInt64
Returned value
Returns a readable, rounded size with suffix as a string.
String
Examples
Format file sizes
sql title=Query
SELECT
arrayJoin([1, 1024, 1024*1024, 192851925]) AS filesize_bytes,
formatReadableSize(filesize_bytes) AS filesize
response title=Response
ββfilesize_bytesββ¬βfilesizeββββ
β 1 β 1.00 B β
β 1024 β 1.00 KiB β
β 1048576 β 1.00 MiB β
β 192851925 β 183.92 MiB β
ββββββββββββββββββ΄βββββββββββββ
formatReadableTimeDelta {#formatReadableTimeDelta}
Introduced in: v20.12
Given a time interval (delta) in seconds, this function returns a time delta with year/month/day/hour/minute/second/millisecond/microsecond/nanosecond as a string.
This function accepts any numeric type as input, but internally it casts them to
Float64
. Results might be suboptimal with large values.
Syntax
sql
formatReadableTimeDelta(column[, maximum_unit, minimum_unit])
Arguments
column
β A column with a numeric time delta.
Float64
maximum_unit
β Optional. Maximum unit to show. Acceptable values:
nanoseconds
,
microseconds
,
milliseconds
,
seconds
,
minutes
,
hours
,
days
,
months
,
years
. Default value:
years
.
const String | {"source_file": "other-functions.md"} | [
0.01947125419974327,
0.024428920820355415,
-0.07492413371801376,
0.03342749550938606,
-0.11718031018972397,
-0.054073452949523926,
0.0018010055646300316,
0.06464012712240219,
-0.041802745312452316,
0.011415805667638779,
-0.03759888932108879,
-0.041790928691625595,
-0.005467667244374752,
-0... |
a641e5b0-eda9-4a87-b610-281c81a3dd59 | minimum_unit
β Optional. Minimum unit to show. All smaller units are truncated. Acceptable values:
nanoseconds
,
microseconds
,
milliseconds
,
seconds
,
minutes
,
hours
,
days
,
months
,
years
. If explicitly specified value is bigger than
maximum_unit
, an exception will be thrown. Default value:
seconds
if
maximum_unit
is
seconds
or bigger,
nanoseconds
otherwise.
const String
Returned value
Returns a time delta as a string.
String
Examples
Usage example
sql title=Query
SELECT
arrayJoin([100, 12345, 432546534]) AS elapsed,
formatReadableTimeDelta(elapsed) AS time_delta
response title=Response
βββββelapsedββ¬βtime_deltaββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 100 β 1 minute and 40 seconds β
β 12345 β 3 hours, 25 minutes and 45 seconds β
β 432546534 β 13 years, 8 months, 17 days, 7 hours, 48 minutes and 54 secondsβ
ββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
With maximum unit
sql title=Query
SELECT
arrayJoin([100, 12345, 432546534]) AS elapsed,
formatReadableTimeDelta(elapsed, 'minutes') AS time_delta
response title=Response
βββββelapsedββ¬βtime_deltaββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 100 β 1 minute and 40 seconds β
β 12345 β 205 minutes and 45 seconds β
β 432546534 β 7209108 minutes and 54 seconds β
ββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
generateRandomStructure {#generateRandomStructure}
Introduced in: v23.5
Generates random table structure in the format
column1_name column1_type, column2_name column2_type, ...
.
Syntax
sql
generateRandomStructure([number_of_columns, seed])
Arguments
number_of_columns
β The desired number of columns in the resultant table structure. If set to 0 or
Null
, the number of columns will be random from 1 to 128. Default value:
Null
.
UInt64
seed
β Random seed to produce stable results. If seed is not specified or set to
Null
, it is randomly generated.
UInt64
Returned value
Randomly generated table structure.
String
Examples
Usage example
sql title=Query
SELECT generateRandomStructure()
response title=Response
c1 Decimal32(5), c2 Date, c3 Tuple(LowCardinality(String), Int128, UInt64, UInt16, UInt8, IPv6), c4 Array(UInt128), c5 UInt32, c6 IPv4, c7 Decimal256(64), c8 Decimal128(3), c9 UInt256, c10 UInt64, c11 DateTime
with specified number of columns
sql title=Query
SELECT generateRandomStructure(1)
response title=Response
c1 Map(UInt256, UInt16)
with specified seed
sql title=Query
SELECT generateRandomStructure(NULL, 33) | {"source_file": "other-functions.md"} | [
0.02629680372774601,
0.04045272246003151,
-0.012701748870313168,
0.017159227281808853,
-0.07703161984682083,
-0.027547594159841537,
0.007657153531908989,
0.02339625544846058,
-0.02781345136463642,
-0.03734815865755081,
-0.026508169248700142,
-0.07373753190040588,
-0.06626980751752853,
-0.0... |
a9ccb239-2be6-4c7c-abee-50c415715e17 | sql title=Query
SELECT generateRandomStructure(1)
response title=Response
c1 Map(UInt256, UInt16)
with specified seed
sql title=Query
SELECT generateRandomStructure(NULL, 33)
response title=Response
c1 DateTime, c2 Enum8('c2V0' = 0, 'c2V1' = 1, 'c2V2' = 2, 'c2V3' = 3), c3 LowCardinality(Nullable(FixedString(30))), c4 Int16, c5 Enum8('c5V0' = 0, 'c5V1' = 1, 'c5V2' = 2, 'c5V3' = 3), c6 Nullable(UInt8), c7 String, c8 Nested(e1 IPv4, e2 UInt8, e3 UInt16, e4 UInt16, e5 Int32, e6 Map(Date, Decimal256(70)))
generateSerialID {#generateSerialID}
Introduced in: v25.1
Generates and returns sequential numbers starting from the previous counter value.
This function takes a string argument - a series identifier, and an optional starting value.
The server should be configured with Keeper.
The series are stored in Keeper nodes under the path, which can be configured in
series_keeper_path
in the server configuration.
Syntax
sql
generateSerialID(series_identifier[, start_value])
Arguments
series_identifier
β Series identifier
const String
start_value
β Optional. Starting value for the counter. Defaults to 0. Note: this value is only used when creating a new series and is ignored if the series already exists
UInt*
Returned value
Returns sequential numbers starting from the previous counter value.
UInt64
Examples
first call
sql title=Query
SELECT generateSerialID('id1')
response title=Response
ββgenerateSerialID('id1')βββ
β 1 β
ββββββββββββββββββββββββββββ
second call
sql title=Query
SELECT generateSerialID('id1')
response title=Response
ββgenerateSerialID('id1')βββ
β 2 β
ββββββββββββββββββββββββββββ
column call
sql title=Query
SELECT *, generateSerialID('id1') FROM test_table
response title=Response
ββCounterIDββ¬βUserIDββ¬βverββ¬βgenerateSerialID('id1')βββ
β 1 β 3 β 3 β 3 β
β 1 β 1 β 1 β 4 β
β 1 β 2 β 2 β 5 β
β 1 β 5 β 5 β 6 β
β 1 β 4 β 4 β 7 β
βββββββββββββ΄βββββββββ΄ββββββ΄βββββββββββββββββββββββββββ
with start value
sql title=Query
SELECT generateSerialID('id2', 100)
response title=Response
ββgenerateSerialID('id2', 100)βββ
β 100 β
βββββββββββββββββββββββββββββββββ
with start value second call
sql title=Query
SELECT generateSerialID('id2', 100)
response title=Response
ββgenerateSerialID('id2', 100)βββ
β 101 β
βββββββββββββββββββββββββββββββββ
getClientHTTPHeader {#getClientHTTPHeader}
Introduced in: v24.5
Gets the value of an HTTP header.
If there is no such header or the current request is not performed via the HTTP interface, the function returns an empty string.
Certain HTTP headers (e.g.,
Authentication
and
X-ClickHouse-*
) are restricted. | {"source_file": "other-functions.md"} | [
-0.05019240826368332,
0.061830345541238785,
-0.03440600633621216,
0.0075532724149525166,
-0.07535961270332336,
0.0261941347271204,
0.010140406899154186,
0.011463582515716553,
-0.028176292777061462,
0.025553463026881218,
0.03907514736056328,
-0.15109248459339142,
0.001424945192411542,
-0.09... |
adc16173-adf5-4961-86e7-1ecd784e10f6 | :::note Setting
allow_get_client_http_header
is required
The function requires the setting
allow_get_client_http_header
to be enabled.
The setting is not enabled by default for security reasons, because some headers, such as
Cookie
, could contain sensitive info.
:::
HTTP headers are case sensitive for this function.
If the function is used in the context of a distributed query, it returns non-empty result only on the initiator node.
Syntax
sql
getClientHTTPHeader(name)
Arguments
name
β The HTTP header name.
String
Returned value
Returns the value of the header.
String
Examples
Usage example
sql title=Query
SELECT getClientHTTPHeader('Content-Type');
response title=Response
ββgetClientHTTPHeader('Content-Type')ββ
β application/x-www-form-urlencoded β
βββββββββββββββββββββββββββββββββββββββ
getMacro {#getMacro}
Introduced in: v20.1
Returns the value of a macro from the server configuration file.
Macros are defined in the
<macros>
section of the configuration file and can be used to distinguish servers by convenient names even if they have complicated hostnames.
If the function is executed in the context of a distributed table, it generates a normal column with values relevant to each shard.
Syntax
sql
getMacro(name)
Arguments
name
β The name of the macro to retrieve.
const String
Returned value
Returns the value of the specified macro.
String
Examples
Basic usage
sql title=Query
SELECT getMacro('test');
response title=Response
ββgetMacro('test')ββ
β Value β
ββββββββββββββββββββ
getMaxTableNameLengthForDatabase {#getMaxTableNameLengthForDatabase}
Introduced in: v
Returns the maximum table name length in a specified database.
Syntax
sql
getMaxTableNameLengthForDatabase(database_name)
Arguments
database_name
β The name of the specified database.
String
Returned value
Returns the length of the maximum table name, an Integer
Examples
typical
sql title=Query
SELECT getMaxTableNameLengthForDatabase('default');
response title=Response
ββgetMaxTableNameLengthForDatabase('default')ββ
β 206 β
βββββββββββββββββββββββββββββββββββββββββββββββ
getMergeTreeSetting {#getMergeTreeSetting}
Introduced in: v25.6
Returns the current value of a MergeTree setting.
Syntax
sql
getMergeTreeSetting(setting_name)
Arguments
setting_name
β The setting name.
String
Returned value
Returns the merge tree setting's current value.
Examples
Usage example
sql title=Query
SELECT getMergeTreeSetting('index_granularity');
response title=Response
ββgetMergeTreeSetting('index_granularity')ββ
β 8192 β
ββββββββββββββββββββββββββββββββββββββββββββ
getOSKernelVersion {#getOSKernelVersion}
Introduced in: v21.11
Returns a string with the OS kernel version.
Syntax
sql
getOSKernelVersion()
Arguments
None.
Returned value | {"source_file": "other-functions.md"} | [
-0.03492220491170883,
0.06625164300203323,
-0.01801961287856102,
0.0339820496737957,
-0.012772205285727978,
-0.04956834763288498,
0.029046671465039253,
0.020731471478939056,
0.00735040009021759,
-0.008988688699901104,
0.005862764082849026,
-0.07795125991106033,
0.06784965842962265,
-0.0590... |
3470214b-29b1-45c8-a2fd-70e382d81dd8 | getOSKernelVersion {#getOSKernelVersion}
Introduced in: v21.11
Returns a string with the OS kernel version.
Syntax
sql
getOSKernelVersion()
Arguments
None.
Returned value
Returns the current OS kernel version.
String
Examples
Usage example
sql title=Query
SELECT getOSKernelVersion();
response title=Response
ββgetOSKernelVersion()βββββ
β Linux 4.15.0-55-generic β
βββββββββββββββββββββββββββ
getServerPort {#getServerPort}
Introduced in: v21.10
Returns the server's port number for a given protocol.
Syntax
sql
getServerPort(port_name)
Arguments
port_name
β The name of the port.
String
Returned value
Returns the server port number.
UInt16
Examples
Usage example
sql title=Query
SELECT getServerPort('tcp_port');
response title=Response
ββgetServerPort('tcp_port')ββ
β 9000 β
βββββββββββββββββββββββββββββ
getServerSetting {#getServerSetting}
Introduced in: v25.6
Returns the currently set value, given a server setting name.
Syntax
sql
getServerSetting(setting_name')
Arguments
setting_name
β The server setting name.
String
Returned value
Returns the server setting's current value.
Any
Examples
Usage example
sql title=Query
SELECT getServerSetting('allow_use_jemalloc_memory');
response title=Response
ββgetServerSetting('allow_use_jemalloc_memory')ββ
β true β
βββββββββββββββββββββββββββββββββββββββββββββββββ
getSetting {#getSetting}
Introduced in: v20.7
Returns the current value of a setting.
Syntax
sql
getSetting(setting_name)
Arguments
setting_Name
β The setting name.
const String
Returned value
Returns the setting's current value.
Any
Examples
Usage example
sql title=Query
SELECT getSetting('enable_analyzer');
SET enable_analyzer = false;
SELECT getSetting('enable_analyzer');
response title=Response
ββgetSetting('β―_analyzer')ββ
β true β
ββββββββββββββββββββββββββββ
ββgetSetting('β―_analyzer')ββ
β false β
ββββββββββββββββββββββββββββ
getSettingOrDefault {#getSettingOrDefault}
Introduced in: v24.10
Returns the current value of a setting or returns the default value specified in the second argument if the setting is not set in the current profile.
Syntax
sql
getSettingOrDefault(setting_name, default_value)
Arguments
setting_name
β The setting name.
String
default_value
β Value to return if custom_setting is not set. Value may be of any data type or Null.
Returned value
Returns the current value of the specified setting or
default_value
if the setting is not set.
Examples
Usage example
sql title=Query
SELECT getSettingOrDefault('custom_undef1', 'my_value');
SELECT getSettingOrDefault('custom_undef2', 100);
SELECT getSettingOrDefault('custom_undef3', NULL);
response title=Response
my_value
100
NULL
getSizeOfEnumType {#getSizeOfEnumType}
Introduced in: v1.1 | {"source_file": "other-functions.md"} | [
0.014506089501082897,
0.008089935407042503,
-0.05466531589627266,
-0.028002535924315453,
-0.012168544344604015,
-0.04491180181503296,
0.011364037171006203,
0.03498684614896774,
-0.053914282470941544,
-0.04609603062272072,
-0.00020745658548548818,
-0.003718008054420352,
-0.02938912808895111,
... |
841fef34-aa00-4421-8c84-e79ac1b3ccae | response title=Response
my_value
100
NULL
getSizeOfEnumType {#getSizeOfEnumType}
Introduced in: v1.1
Returns the number of fields in the given
Enum
.
Syntax
sql
getSizeOfEnumType(x)
Arguments
x
β Value of type
Enum
.
Enum
Returned value
Returns the number of fields with
Enum
input values.
UInt8/16
Examples
Usage example
sql title=Query
SELECT getSizeOfEnumType(CAST('a' AS Enum8('a' = 1, 'b' = 2))) AS x;
response title=Response
ββxββ
β 2 β
βββββ
getSubcolumn {#getSubcolumn}
Introduced in: v
Receives the expression or identifier and constant string with the name of subcolumn.
Returns requested subcolumn extracted from the expression.
Syntax
```sql
```
Arguments
None.
Returned value
Examples
getSubcolumn
sql title=Query
SELECT getSubcolumn(array_col, 'size0'), getSubcolumn(tuple_col, 'elem_name')
```response title=Response
```
getTypeSerializationStreams {#getTypeSerializationStreams}
Introduced in: v22.6
Enumerates stream paths of a data type.
This function is intended for developmental use.
Syntax
sql
getTypeSerializationStreams(col)
Arguments
col
β Column or string representation of a data-type from which the data type will be detected.
Any
Returned value
Returns an array with all the serialization sub-stream paths.
Array(String)
Examples
tuple
sql title=Query
SELECT getTypeSerializationStreams(tuple('a', 1, 'b', 2))
response title=Response
['{TupleElement(1), Regular}','{TupleElement(2), Regular}','{TupleElement(3), Regular}','{TupleElement(4), Regular}']
map
sql title=Query
SELECT getTypeSerializationStreams('Map(String, Int64)')
response title=Response
['{ArraySizes}','{ArrayElements, TupleElement(keys), Regular}','{ArrayElements, TupleElement(values), Regular}']
globalVariable {#globalVariable}
Introduced in: v20.5
Takes a constant string argument and returns the value of the global variable with that name. This function is intended for compatibility with MySQL and not needed or useful for normal operation of ClickHouse. Only few dummy global variables are defined.
Syntax
sql
globalVariable(name)
Arguments
name
β Global variable name.
String
Returned value
Returns the value of variable
name
.
Any
Examples
globalVariable
sql title=Query
SELECT globalVariable('max_allowed_packet')
response title=Response
67108864
hasColumnInTable {#hasColumnInTable}
Introduced in: v1.1
Checks if a specific column exists in a database table.
For elements in a nested data structure, the function checks for the existence of a column.
For the nested data structure itself, the function returns
0
.
Syntax
sql
hasColumnInTable([hostname[, username[, password]],]database, table, column)
Arguments
database
β Name of the database.
const String
table
β Name of the table.
const String
column
β Name of the column.
const String | {"source_file": "other-functions.md"} | [
0.035991016775369644,
-0.005554076284170151,
-0.06263509392738342,
0.039627447724342346,
-0.04843716323375702,
0.001737968297675252,
0.06029673293232918,
0.05619550123810768,
-0.09375129640102386,
-0.007316248957067728,
-0.0048202695325016975,
-0.09594354778528214,
0.030869023874402046,
-0... |
cd9470ed-7360-4dc0-aa2e-e193fcd638b0 | Arguments
database
β Name of the database.
const String
table
β Name of the table.
const String
column
β Name of the column.
const String
hostname
β Optional. Remote server name to perform the check on.
const String
username
β Optional. Username for remote server.
const String
password
β Optional. Password for remote server.
const String
Returned value
Returns
1
if the given column exists,
0
otherwise.
UInt8
Examples
Check an existing column
sql title=Query
SELECT hasColumnInTable('system','metrics','metric')
response title=Response
1
Check a non-existing column
sql title=Query
SELECT hasColumnInTable('system','metrics','non-existing_column')
response title=Response
0
hasThreadFuzzer {#hasThreadFuzzer}
Introduced in: v20.6
Returns whether the thread fuzzer is enabled.
THis function is only useful for testing and debugging.
Syntax
sql
hasThreadFuzzer()
Arguments
None.
Returned value
Returns whether Thread Fuzzer is effective.
UInt8
Examples
Check Thread Fuzzer status
sql title=Query
SELECT hasThreadFuzzer()
response title=Response
ββhasThreadFuzzer()ββ
β 0 β
βββββββββββββββββββββ
hostName {#hostName}
Introduced in: v20.5
Returns the name of the host on which this function was executed.
If the function executes on a remote server (distributed processing), the remote server name is returned.
If the function executes in the context of a distributed table, it generates a normal column with values relevant to each shard.
Otherwise it produces a constant value.
Syntax
sql
hostName()
Aliases
:
hostname
Arguments
None.
Returned value
Returns the host name.
String
Examples
Usage example
sql title=Query
SELECT hostName()
response title=Response
ββhostName()ββ
β clickhouse β
ββββββββββββββ
icebergBucket {#icebergBucket}
Introduced in: v25.5
Implements logic of iceberg bucket transform: https://iceberg.apache.org/spec/#bucket-transform-details.
Syntax
sql
icebergBucket(N, value)
Arguments
N
β modulo, positive integer, always constant. -
value
β Integer, bool, decimal, float, string, fixed_string, uuid, date, time or datetime value.
Returned value
Int32
Examples
Example
sql title=Query
SELECT icebergBucket(5, 1.0 :: Float32)
response title=Response
4
icebergHash {#icebergHash}
Introduced in: v25.5
Implements logic of iceberg hashing transform: https://iceberg.apache.org/spec/#appendix-b-32-bit-hash-requirements.
Syntax
sql
icebergHash(N, value)
Arguments
value
β Integer, bool, decimal, float, string, fixed_string, uuid, date, time, datetime.
Returned value
Int32
Examples
Example
sql title=Query
SELECT icebergHash(1.0 :: Float32)
response title=Response
-142385009
icebergTruncate {#icebergTruncate}
Introduced in: v25.3
Implements logic of iceberg truncate transform: https://iceberg.apache.org/spec/#truncate-transform-details.
Syntax | {"source_file": "other-functions.md"} | [
0.021588170900940895,
-0.012177354656159878,
-0.08256233483552933,
0.0705428421497345,
-0.05138804763555527,
-0.033544883131980896,
0.05269200727343559,
0.03753179311752319,
-0.0022005813661962748,
0.05670559033751488,
-0.01878475956618786,
-0.07084435969591141,
0.01149645633995533,
-0.078... |
90042ade-fd47-452e-b34e-1b466339111f | icebergTruncate {#icebergTruncate}
Introduced in: v25.3
Implements logic of iceberg truncate transform: https://iceberg.apache.org/spec/#truncate-transform-details.
Syntax
sql
icebergTruncate(N, value)
Arguments
value
β The value to transform.
String
or
(U)Int*
or
Decimal
Returned value
The same type as the argument
Examples
Example
sql title=Query
SELECT icebergTruncate(3, 'iceberg')
response title=Response
ice
identity {#identity}
Introduced in: v1.1
This function returns the argument you pass to it, which is useful for debugging and testing. It lets you bypass index usage to see full scan performance instead. The query analyzer ignores anything inside identity functions when looking for indexes to use, and it also disables constant folding.
Syntax
sql
identity(x)
Arguments
x
β Input value.
Any
Returned value
Returns the input value unchanged.
Any
Examples
Usage example
sql title=Query
SELECT identity(42)
response title=Response
42
ignore {#ignore}
Introduced in: v1.1
Accepts arbitrary arguments and unconditionally returns
0
.
Syntax
sql
ignore(x)
Arguments
x
β An input value which is unused and passed only so as to avoid a syntax error.
Any
Returned value
Always returns
0
.
UInt8
Examples
Usage example
sql title=Query
SELECT ignore(0, 'ClickHouse', NULL)
response title=Response
ββignore(0, 'ClickHouse', NULL)ββ
β 0 β
βββββββββββββββββββββββββββββββββ
indexHint {#indexHint}
Introduced in: v1.1
This function is intended for debugging and introspection.
It ignores its argument and always returns 1.
The arguments are not evaluated.
But during index analysis, the argument of this function is assumed to be not wrapped in
indexHint
.
This allows to select data in index ranges by the corresponding condition but without further filtering by this condition.
The index in ClickHouse is sparse and using
indexHint
will yield more data than specifying the same condition directly.
Syntax
sql
indexHint(expression)
Arguments
expression
β Any expression for index range selection.
Expression
Returned value
Returns
1
in all cases.
UInt8
Examples
Usage example with date filtering
sql title=Query
SELECT FlightDate AS k, count() FROM ontime WHERE indexHint(k = '2025-09-15') GROUP BY k ORDER BY k ASC;
response title=Response
βββββββββββkββ¬βcount()ββ
β 2025-09-14 β 7071 β
β 2025-09-15 β 16428 β
β 2025-09-16 β 1077 β
β 2025-09-30 β 8167 β
ββββββββββββββ΄ββββββββββ
initialQueryID {#initialQueryID}
Introduced in: v1.1
Returns the ID of the initial current query.
Other parameters of a query can be extracted from field
initial_query_id
in
system.query_log
.
In contrast to
queryID
function,
initialQueryID
returns the same results on different shards.
Syntax
sql
initialQueryID()
Aliases
:
initial_query_id
Arguments
None.
Returned value | {"source_file": "other-functions.md"} | [
-0.07976435124874115,
0.02771863155066967,
-0.05361754074692726,
0.09403012692928314,
-0.0007212163764052093,
-0.06278873234987259,
0.03882912918925285,
0.04910089448094368,
-0.01924346759915352,
-0.04207950457930565,
-0.0022347138728946447,
0.05589626356959343,
-0.010387592948973179,
-0.0... |
cb0f87fd-158a-43ea-9f0a-1d3eeff06be4 | Syntax
sql
initialQueryID()
Aliases
:
initial_query_id
Arguments
None.
Returned value
Returns the ID of the initial current query.
String
Examples
Usage example
sql title=Query
CREATE TABLE tmp (str String) ENGINE = Log;
INSERT INTO tmp (*) VALUES ('a');
SELECT count(DISTINCT t) FROM (SELECT initialQueryID() AS t FROM remote('127.0.0.{1..3}', currentDatabase(), 'tmp') GROUP BY queryID());
response title=Response
ββcount(DISTINCT t)ββ
β 1 β
βββββββββββββββββββββ
initialQueryStartTime {#initialQueryStartTime}
Introduced in: v25.4
Returns the start time of the initial current query.
initialQueryStartTime
returns the same results on different shards.
Syntax
sql
initialQueryStartTime()
Aliases
:
initial_query_start_time
Arguments
None.
Returned value
Returns the start time of the initial current query.
DateTime
Examples
Usage example
sql title=Query
CREATE TABLE tmp (str String) ENGINE = Log;
INSERT INTO tmp (*) VALUES ('a');
SELECT count(DISTINCT t) FROM (SELECT initialQueryStartTime() AS t FROM remote('127.0.0.{1..3}', currentDatabase(), 'tmp') GROUP BY queryID());
response title=Response
ββcount(DISTINCT t)ββ
β 1 β
βββββββββββββββββββββ
initializeAggregation {#initializeAggregation}
Introduced in: v20.6
Calculates the result of an aggregate function based on a single value.
This function can be used to initialize aggregate functions with combinator
-State
.
You can create states of aggregate functions and insert them to columns of type
AggregateFunction
or use initialized aggregates as default values.
Syntax
sql
initializeAggregation(aggregate_function, arg1[, arg2, ...])
Arguments
aggregate_function
β Name of the aggregation function to initialize.
String
arg1[, arg2, ...]
β Arguments of the aggregate function.
Any
Returned value
Returns the result of aggregation for every row passed to the function. The return type is the same as the return type of the function that
initializeAggregation
takes as a first argument.
Any
Examples
Basic usage with uniqState
sql title=Query
SELECT uniqMerge(state) FROM (SELECT initializeAggregation('uniqState', number % 3) AS state FROM numbers(10000));
response title=Response
ββuniqMerge(state)ββ
β 3 β
ββββββββββββββββββββ
Usage with sumState and finalizeAggregation
sql title=Query
SELECT finalizeAggregation(state), toTypeName(state) FROM (SELECT initializeAggregation('sumState', number % 3) AS state FROM numbers(5)); | {"source_file": "other-functions.md"} | [
-0.021832015365362167,
-0.01923026517033577,
-0.028679130598902702,
0.0933210626244545,
-0.09529438614845276,
-0.0252340417355299,
0.031102381646633148,
0.025249315425753593,
0.09345003217458725,
-0.024745365604758263,
0.033292870968580246,
-0.017127981409430504,
0.051133789122104645,
-0.0... |
789e785f-19fe-48bf-8794-7251bd47c27b | sql title=Query
SELECT finalizeAggregation(state), toTypeName(state) FROM (SELECT initializeAggregation('sumState', number % 3) AS state FROM numbers(5));
response title=Response
ββfinalizeAggregation(state)ββ¬βtoTypeName(state)ββββββββββββββ
β 0 β AggregateFunction(sum, UInt8) β
β 1 β AggregateFunction(sum, UInt8) β
β 2 β AggregateFunction(sum, UInt8) β
β 0 β AggregateFunction(sum, UInt8) β
β 1 β AggregateFunction(sum, UInt8) β
ββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ
isConstant {#isConstant}
Introduced in: v20.3
Returns whether the argument is a constant expression.
A constant expression is an expression whose result is known during query analysis, i.e. before execution.
For example, expressions over
literals
are constant expressions.
This function is mostly intended for development, debugging and demonstration.
Syntax
sql
isConstant(x)
Arguments
x
β An expression to check.
Any
Returned value
Returns
1
if
x
is constant,
0
if
x
is non-constant.
UInt8
Examples
Constant expression
sql title=Query
SELECT isConstant(x + 1)
FROM (SELECT 43 AS x)
response title=Response
ββisConstant(plus(x, 1))ββ
β 1 β
ββββββββββββββββββββββββββ
Constant with function
sql title=Query
WITH 3.14 AS pi
SELECT isConstant(cos(pi))
response title=Response
ββisConstant(cos(pi))ββ
β 1 β
βββββββββββββββββββββββ
Non-constant expression
sql title=Query
SELECT isConstant(number)
FROM numbers(1)
response title=Response
ββisConstant(number)ββ
β 0 β
ββββββββββββββββββββββ
Behavior of the now() function
sql title=Query
SELECT isConstant(now())
response title=Response
ββisConstant(now())ββ
β 1 β
βββββββββββββββββββββ
isDecimalOverflow {#isDecimalOverflow}
Introduced in: v20.8
Checks if a decimal number has too many digits to fit properly in a Decimal data type with given precision.
Syntax
sql
isDecimalOverflow(value[, precision])
Arguments
value
β Decimal value to check.
Decimal
precision
β Optional. The precision of the Decimal type. If omitted, the initial precision of the first argument is used.
UInt8
Returned value
Returns
1
if the decimal value has more digits than allowed by its precision,
0
if the decimal value satisfies the specified precision.
UInt8
Examples
Usage example
sql title=Query
SELECT isDecimalOverflow(toDecimal32(1000000000, 0), 9),
isDecimalOverflow(toDecimal32(1000000000, 0)),
isDecimalOverflow(toDecimal32(-1000000000, 0), 9),
isDecimalOverflow(toDecimal32(-1000000000, 0)); | {"source_file": "other-functions.md"} | [
-0.0711829736828804,
-0.023594340309500694,
0.025116844102740288,
0.08564156293869019,
-0.05912493169307709,
0.014227843843400478,
0.08884958922863007,
0.021505774930119514,
-0.021170319989323616,
-0.010499793104827404,
-0.046765245497226715,
-0.08845183998346329,
0.0209727194160223,
-0.06... |
9ab0dc29-5021-4d3a-a2b9-3c3d0a8d40bb | response title=Response
ββisDecimalOverflow(toDecimal32(1000000000, 0), 9)ββ¬βisDecimalOverflow(toDecimal32(1000000000, 0))ββ¬βisDecimalOverflow(toDecimal32(-1000000000, 0), 9)ββ¬βisDecimalOverflow(toDecimal32(-1000000000, 0))ββ
β 1 β 1 β 1 β 1 β
ββββββββββββββββββββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββββββ
joinGet {#joinGet}
Introduced in: v18.16
Allows you to extract data from a table the same way as from a dictionary.
Gets data from Join tables using the specified join key.
:::note
Only supports tables created with the
ENGINE = Join(ANY, LEFT, <join_keys>)
statement
.
:::
Syntax
sql
joinGet(join_storage_table_name, value_column, join_keys)
Arguments
join_storage_table_name
β An identifier which indicates where to perform the search. The identifier is searched in the default database (see parameter
default_database
in the config file). To override the default database, use the
USE database_name
query or specify the database and the table through a dot, like
database_name.table_name
.
String
value_column
β The name of the column of the table that contains required data.
const String
join_keys
β A list of join keys.
Any
Returned value
Returns list of values corresponded to list of keys.
Any
Examples
Usage example
``sql title=Query
CREATE TABLE db_test.id_val(
id
UInt32,
val` UInt32) ENGINE = Join(ANY, LEFT, id);
INSERT INTO db_test.id_val VALUES (1,11)(2,12)(4,13);
SELECT joinGet(db_test.id_val, 'val', toUInt32(1));
```
response title=Response
ββjoinGet(db_test.id_val, 'val', toUInt32(1))ββ
β 11 β
βββββββββββββββββββββββββββββββββββββββββββββββ
Usage with table from current database
sql title=Query
USE db_test;
SELECT joinGet(id_val, 'val', toUInt32(2));
response title=Response
ββjoinGet(id_val, 'val', toUInt32(2))ββ
β 12 β
βββββββββββββββββββββββββββββββββββββββ
Using arrays as join keys
```sql title=Query
CREATE TABLE some_table (id1 UInt32, id2 UInt32, name String) ENGINE = Join(ANY, LEFT, id1, id2);
INSERT INTO some_table VALUES (1, 11, 'a') (2, 12, 'b') (3, 13, 'c');
SELECT joinGet(some_table, 'name', 1, 11);
```
response title=Response
ββjoinGet(some_table, 'name', 1, 11)ββ
β a β
ββββββββββββββββββββββββββββββββββββββ
joinGetOrNull {#joinGetOrNull}
Introduced in: v20.4
Allows you to extract data from a table the same way as from a dictionary.
Gets data from Join tables using the specified join key.
Unlike
joinGet
it returns
NULL
when the key is missing. | {"source_file": "other-functions.md"} | [
-0.0029281191527843475,
0.05878686532378197,
-0.08018134534358978,
0.07898121327161789,
-0.04365461319684982,
-0.06615616381168365,
0.03952384740114212,
0.09656618535518646,
-0.05321192368865013,
0.002634357428178191,
0.05526310205459595,
-0.05466744303703308,
0.1013464480638504,
-0.062905... |
765c9c5d-f26e-4310-ac9b-30514b71d415 | Allows you to extract data from a table the same way as from a dictionary.
Gets data from Join tables using the specified join key.
Unlike
joinGet
it returns
NULL
when the key is missing.
:::note
Only supports tables created with the
ENGINE = Join(ANY, LEFT, <join_keys>)
statement
.
:::
Syntax
sql
joinGetOrNull(join_storage_table_name, value_column, join_keys)
Arguments
join_storage_table_name
β An identifier which indicates where to perform the search. The identifier is searched in the default database (see parameter default_database in the config file). To override the default database, use the
USE database_name
query or specify the database and the table through a dot, like
database_name.table_name
.
String
value_column
β The name of the column of the table that contains required data.
const String
join_keys
β A list of join keys.
Any
Returned value
Returns a list of values corresponding to the list of keys, or
NULL
if a key is not found.
Any
Examples
Usage example
``sql title=Query
CREATE TABLE db_test.id_val(
id
UInt32,
val` UInt32) ENGINE = Join(ANY, LEFT, id);
INSERT INTO db_test.id_val VALUES (1,11)(2,12)(4,13);
SELECT joinGetOrNull(db_test.id_val, 'val', toUInt32(1)), joinGetOrNull(db_test.id_val, 'val', toUInt32(999));
```
response title=Response
ββjoinGetOrNull(db_test.id_val, 'val', toUInt32(1))ββ¬βjoinGetOrNull(db_test.id_val, 'val', toUInt32(999))ββ
β 11 β α΄Ία΅α΄Έα΄Έ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
lowCardinalityIndices {#lowCardinalityIndices}
Introduced in: v18.12
Returns the position of a value in the dictionary of a
LowCardinality
column. Positions start at 1. Since LowCardinality have per-part dictionaries, this function may return different positions for the same value in different parts.
Syntax
sql
lowCardinalityIndices(col)
Arguments
col
β A low cardinality column.
LowCardinality
Returned value
The position of the value in the dictionary of the current part.
UInt64
Examples
Usage examples
```sql title=Query
DROP TABLE IF EXISTS test;
CREATE TABLE test (s LowCardinality(String)) ENGINE = Memory;
-- create two parts:
INSERT INTO test VALUES ('ab'), ('cd'), ('ab'), ('ab'), ('df');
INSERT INTO test VALUES ('ef'), ('cd'), ('ab'), ('cd'), ('ef');
SELECT s, lowCardinalityIndices(s) FROM test;
``` | {"source_file": "other-functions.md"} | [
-0.014205853454768658,
0.0381561703979969,
-0.10138014703989029,
0.10257048904895782,
-0.05640358105301857,
-0.03897852823138237,
0.07277756929397583,
0.09890223294496536,
-0.09660236537456512,
-0.003472878597676754,
0.048072732985019684,
0.007109359838068485,
0.10382039844989777,
-0.08905... |
1e943aac-5236-4fcb-87b6-045be64d8bc4 | INSERT INTO test VALUES ('ab'), ('cd'), ('ab'), ('ab'), ('df');
INSERT INTO test VALUES ('ef'), ('cd'), ('ab'), ('cd'), ('ef');
SELECT s, lowCardinalityIndices(s) FROM test;
```
response title=Response
ββsβββ¬βlowCardinalityIndices(s)ββ
β ab β 1 β
β cd β 2 β
β ab β 1 β
β ab β 1 β
β df β 3 β
ββββββ΄βββββββββββββββββββββββββββ
ββsβββ¬βlowCardinalityIndices(s)ββ
β ef β 1 β
β cd β 2 β
β ab β 3 β
β cd β 2 β
β ef β 1 β
ββββββ΄βββββββββββββββββββββββββββ
lowCardinalityKeys {#lowCardinalityKeys}
Introduced in: v18.12
Returns the dictionary values of a
LowCardinality
column.
If the block is smaller or larger than the dictionary size, the result will be truncated or extended with default values.
Since LowCardinality have per-part dictionaries, this function may return different dictionary values in different parts.
Syntax
sql
lowCardinalityKeys(col)
Arguments
col
β A low cardinality column.
LowCardinality
Returned value
Returns the dictionary keys.
UInt64
Examples
lowCardinalityKeys
```sql title=Query
DROP TABLE IF EXISTS test;
CREATE TABLE test (s LowCardinality(String)) ENGINE = Memory;
-- create two parts:
INSERT INTO test VALUES ('ab'), ('cd'), ('ab'), ('ab'), ('df');
INSERT INTO test VALUES ('ef'), ('cd'), ('ab'), ('cd'), ('ef');
SELECT s, lowCardinalityKeys(s) FROM test;
```
response title=Response
ββsβββ¬βlowCardinalityKeys(s)ββ
β ef β β
β cd β ef β
β ab β cd β
β cd β ab β
β ef β β
ββββββ΄ββββββββββββββββββββββββ
ββsβββ¬βlowCardinalityKeys(s)ββ
β ab β β
β cd β ab β
β ab β cd β
β ab β df β
β df β β
ββββββ΄ββββββββββββββββββββββββ
materialize {#materialize}
Introduced in: v1.1
Turns a constant into a full column containing a single value.
Full columns and constants are represented differently in memory.
Functions usually execute different code for normal and constant arguments, although the result should typically be the same.
This function can be used to debug this behavior.
Syntax
sql
materialize(x)
Arguments
x
β A constant.
Any
Returned value
Returns a full column containing the constant value.
Any
Examples
Usage example
``sql title=Query
-- In the example below the
countMatches
function expects a constant second argument.
-- This behaviour can be debugged by using the
materialize` function to turn a constant into a full column,
-- verifying that the function throws an error for a non-constant argument.
SELECT countMatches('foobarfoo', 'foo');
SELECT countMatches('foobarfoo', materialize('foo'));
``` | {"source_file": "other-functions.md"} | [
0.05166691914200783,
0.0288395918905735,
-0.02893870882689953,
0.0003904630139004439,
-0.07101603597402573,
-0.08070604503154755,
0.04793672263622284,
0.02031616121530533,
-0.00815058033913374,
0.021016642451286316,
0.11363483220338821,
-0.06602926552295685,
0.03415462002158165,
-0.0124442... |
73bba5fa-40b8-43e8-a411-553e07c8f016 | SELECT countMatches('foobarfoo', 'foo');
SELECT countMatches('foobarfoo', materialize('foo'));
```
response title=Response
2
Code: 44. DB::Exception: Received from localhost:9000. DB::Exception: Illegal type of argument #2 'pattern' of function countMatches, expected constant String, got String
minSampleSizeContinuous {#minSampleSizeContinuous}
Introduced in: v23.10
Calculates the minimum required sample size for an A/B test comparing means of a continuous metric in two samples.
Uses the formula described in
this article
.
Assumes equal sizes of treatment and control groups.
Returns the required sample size for one group (i.e. the sample size required for the whole experiment is twice the returned value).
Also assumes equal variance of the test metric in treatment and control groups.
Syntax
sql
minSampleSizeContinuous(baseline, sigma, mde, power, alpha)
Aliases
:
minSampleSizeContinous
Arguments
baseline
β Baseline value of a metric.
(U)Int*
or
Float*
sigma
β Baseline standard deviation of a metric.
(U)Int*
or
Float*
mde
β Minimum detectable effect (MDE) as percentage of the baseline value (e.g. for a baseline value 112.25 the MDE 0.03 means an expected change to 112.25 Β± 112.25*0.03).
(U)Int*
or
Float*
power
β Required statistical power of a test (1 - probability of Type II error).
(U)Int*
or
Float*
alpha
β Required significance level of a test (probability of Type I error).
(U)Int*
or
Float*
Returned value
Returns a named Tuple with 3 elements:
minimum_sample_size
,
detect_range_lower
and
detect_range_upper
. These are respectively: the required sample size, the lower bound of the range of values not detectable with the returned required sample size, calculated as
baseline * (1 - mde)
, and the upper bound of the range of values not detectable with the returned required sample size, calculated as
baseline * (1 + mde)
(Float64).
Tuple(Float64, Float64, Float64)
Examples
minSampleSizeContinuous
sql title=Query
SELECT minSampleSizeContinuous(112.25, 21.1, 0.03, 0.80, 0.05) AS sample_size
response title=Response
(616.2931945826209,108.8825,115.6175)
minSampleSizeConversion {#minSampleSizeConversion}
Introduced in: v22.6
Calculates minimum required sample size for an A/B test comparing conversions (proportions) in two samples.
Uses the formula described in
this article
. Assumes equal sizes of treatment and control groups. Returns the sample size required for one group (i.e. the sample size required for the whole experiment is twice the returned value).
Syntax
sql
minSampleSizeConversion(baseline, mde, power, alpha)
Arguments
baseline
β Baseline conversion.
Float*
mde
β Minimum detectable effect (MDE) as percentage points (e.g. for a baseline conversion 0.25 the MDE 0.03 means an expected change to 0.25 Β± 0.03).
Float*
power
β Required statistical power of a test (1 - probability of Type II error).
Float* | {"source_file": "other-functions.md"} | [
0.05340809002518654,
-0.011254839599132538,
0.005241414997726679,
0.06129120662808418,
-0.11447650194168091,
0.015630632638931274,
-0.008008860051631927,
0.12463837116956711,
-0.02937854826450348,
-0.028589775785803795,
-0.008801458403468132,
-0.13581885397434235,
0.051307275891304016,
-0.... |
2ebf62e0-de62-40ab-b2cd-2715197bd27b | power
β Required statistical power of a test (1 - probability of Type II error).
Float*
alpha
β Required significance level of a test (probability of Type I error).
Float*
Returned value
Returns a named Tuple with 3 elements:
minimum_sample_size
,
detect_range_lower
,
detect_range_upper
. These are, respectively: the required sample size, the lower bound of the range of values not detectable with the returned required sample size, calculated as
baseline - mde
, the upper bound of the range of values not detectable with the returned required sample size, calculated as
baseline + mde
.
Tuple(Float64, Float64, Float64)
Examples
minSampleSizeConversion
sql title=Query
SELECT minSampleSizeConversion(0.25, 0.03, 0.80, 0.05) AS sample_size
response title=Response
(3396.077603219163,0.22,0.28)
neighbor {#neighbor}
Introduced in: v20.1
Returns a value from a column at a specified offset from the current row.
This function is deprecated and error-prone because it operates on the physical order of data blocks which may not correspond to the logical order expected by users.
Consider using proper window functions instead.
The function can be enabled by setting
allow_deprecated_error_prone_window_functions = 1
.
Syntax
sql
neighbor(column, offset[, default_value])
Arguments
column
β The source column.
Any
offset
β The offset from the current row. Positive values look forward, negative values look backward.
Integer
default_value
β Optional. The value to return if the offset goes beyond the data bounds. If not specified, uses the default value for the column type.
Any
Returned value
Returns a value from the specified offset, or default if out of bounds.
Any
Examples
Usage example
sql title=Query
SELECT number, neighbor(number, 2) FROM system.numbers LIMIT 10;
response title=Response
ββnumberββ¬βneighbor(number, 2)ββ
β 0 β 2 β
β 1 β 3 β
β 2 β 4 β
β 3 β 5 β
β 4 β 6 β
β 5 β 7 β
β 6 β 8 β
β 7 β 9 β
β 8 β 0 β
β 9 β 0 β
ββββββββββ΄ββββββββββββββββββββββ
With default value
sql title=Query
SELECT number, neighbor(number, 2, 999) FROM system.numbers LIMIT 10;
response title=Response
ββnumberββ¬βneighbor(number, 2, 999)ββ
β 0 β 2 β
β 1 β 3 β
β 2 β 4 β
β 3 β 5 β
β 4 β 6 β
β 5 β 7 β
β 6 β 8 β
β 7 β 9 β
β 8 β 999 β
β 9 β 999 β
ββββββββββ΄βββββββββββββββββββββββββββ
nested {#nested}
Introduced in: v
This is a function used internally by the ClickHouse engine and not meant to be used directly. | {"source_file": "other-functions.md"} | [
0.049230027943849564,
0.042397987097501755,
-0.05140641704201698,
0.04262088984251022,
0.04879752919077873,
-0.06100461632013321,
-0.027952291071414948,
0.053933754563331604,
-0.03797640651464462,
0.025257796049118042,
-0.02679067850112915,
-0.051340725272893906,
0.05068853124976158,
-0.04... |
c5888e40-b74c-4b69-80e3-1caf4124f569 | nested {#nested}
Introduced in: v
This is a function used internally by the ClickHouse engine and not meant to be used directly.
Returns the array of tuples from multiple arrays.
The first argument must be a constant array of Strings determining the names of the resulting Tuple.
The other arguments must be arrays of the same size.
Syntax
```sql
```
Arguments
None.
Returned value
Examples
nested
sql title=Query
SELECT nested(['keys', 'values'], ['key_1', 'key_2'], ['value_1','value_2'])
```response title=Response
```
normalizeQuery {#normalizeQuery}
Introduced in: v20.8
Replaces literals, sequences of literals and complex aliases (containing whitespace, more than two digits or at least 36 bytes long such as UUIDs) with placeholder
?
.
Syntax
sql
normalizeQuery(x)
Arguments
x
β Sequence of characters.
String
Returned value
Returns the given sequence of characters with placeholders.
String
Examples
Usage example
sql title=Query
SELECT normalizeQuery('[1, 2, 3, x]') AS query
response title=Response
ββqueryβββββ
β [?.., x] β
ββββββββββββ
normalizeQueryKeepNames {#normalizeQueryKeepNames}
Introduced in: v21.2
Replaces literals and sequences of literals with placeholder
?
but does not replace complex aliases (containing whitespace, more than two digits or at least 36 bytes long such as UUIDs).
This helps better analyze complex query logs.
Syntax
sql
normalizeQueryKeepNames(x)
Arguments
x
β Sequence of characters.
String
Returned value
Returns the given sequence of characters with placeholders.
String
Examples
Usage example
sql title=Query
SELECT normalizeQuery('SELECT 1 AS aComplexName123'), normalizeQueryKeepNames('SELECT 1 AS aComplexName123')
response title=Response
ββnormalizeQuery('SELECT 1 AS aComplexName123')ββ¬βnormalizeQueryKeepNames('SELECT 1 AS aComplexName123')ββ
β SELECT ? AS `?` β SELECT ? AS aComplexName123 β
βββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
normalizedQueryHash {#normalizedQueryHash}
Introduced in: v20.8
Returns identical 64 bit hash values without the values of literals for similar queries.
Can be helpful in analyzing query logs.
Syntax
sql
normalizedQueryHash(x)
Arguments
x
β Sequence of characters.
String
Returned value
Returns a 64 bit hash value.
UInt64
Examples
Usage example
sql title=Query
SELECT normalizedQueryHash('SELECT 1 AS `xyz`') != normalizedQueryHash('SELECT 1 AS `abc`') AS res
response title=Response
ββresββ
β 1 β
βββββββ
normalizedQueryHashKeepNames {#normalizedQueryHashKeepNames}
Introduced in: v21.2 | {"source_file": "other-functions.md"} | [
-0.003234041156247258,
-0.008396467193961143,
0.008680774830281734,
0.05961279943585396,
-0.12175378203392029,
-0.06779848039150238,
0.07499866187572479,
0.017172563821077347,
-0.08239810913801193,
-0.02071135863661766,
0.00025750542408786714,
0.020466553047299385,
0.08662097901105881,
-0.... |
93ae8cd9-c528-43fb-8bbe-9c9e88effdef | response title=Response
ββresββ
β 1 β
βββββββ
normalizedQueryHashKeepNames {#normalizedQueryHashKeepNames}
Introduced in: v21.2
Like
normalizedQueryHash
it returns identical 64 bit hash values without the values of literals for similar queries, but it does not replace complex aliases (containing whitespace, more than two digits or at least 36 bytes long such as UUIDs) with a placeholder before hashing.
Can be helpful in analyzing query logs.
Syntax
sql
normalizedQueryHashKeepNames(x)
Arguments
x
β Sequence of characters.
String
Returned value
Returns a 64 bit hash value.
UInt64
Examples
Usage example
sql title=Query
SELECT normalizedQueryHash('SELECT 1 AS `xyz123`') != normalizedQueryHash('SELECT 1 AS `abc123`') AS normalizedQueryHash;
SELECT normalizedQueryHashKeepNames('SELECT 1 AS `xyz123`') != normalizedQueryHashKeepNames('SELECT 1 AS `abc123`') AS normalizedQueryHashKeepNames;
response title=Response
ββnormalizedQueryHashββ
β 0 β
βββββββββββββββββββββββ
ββnormalizedQueryHashKeepNamesββ
β 1 β
ββββββββββββββββββββββββββββββββ
parseReadableSize {#parseReadableSize}
Introduced in: v24.6
Given a string containing a byte size and
B
,
KiB
,
KB
,
MiB
,
MB
, etc. as a unit (i.e.
ISO/IEC 80000-13
or decimal byte unit), this function returns the corresponding number of bytes.
If the function is unable to parse the input value, it throws an exception.
The inverse operations of this function are
formatReadableSize
and
formatReadableDecimalSize
.
Syntax
sql
parseReadableSize(x)
Arguments
x
β Readable size with ISO/IEC 80000-13 or decimal byte unit.
String
Returned value
Returns the number of bytes, rounded up to the nearest integer.
UInt64
Examples
Usage example
sql title=Query
SELECT arrayJoin(['1 B', '1 KiB', '3 MB', '5.314 KiB']) AS readable_sizes, parseReadableSize(readable_sizes) AS sizes;
response title=Response
ββreadable_sizesββ¬βββsizesββ
β 1 B β 1 β
β 1 KiB β 1024 β
β 3 MB β 3000000 β
β 5.314 KiB β 5442 β
ββββββββββββββββββ΄ββββββββββ
parseReadableSizeOrNull {#parseReadableSizeOrNull}
Introduced in: v24.6
Given a string containing a byte size and
B
,
KiB
,
KB
,
MiB
,
MB
, etc. as a unit (i.e.
ISO/IEC 80000-13
or decimal byte unit), this function returns the corresponding number of bytes.
If the function is unable to parse the input value, it returns
NULL
.
The inverse operations of this function are
formatReadableSize
and
formatReadableDecimalSize
.
Syntax
sql
parseReadableSizeOrNull(x)
Arguments
x
β Readable size with ISO/IEC 80000-13 or decimal byte unit.
String
Returned value
Returns the number of bytes, rounded up to the nearest integer, or
NULL
if unable to parse the input
Nullable(UInt64)
Examples
Usage example | {"source_file": "other-functions.md"} | [
0.053161878138780594,
0.03340715914964676,
0.018857533112168312,
-0.009152024984359741,
-0.11067059636116028,
-0.05871563404798508,
0.046201441437006,
-0.048973169177770615,
0.023821605369448662,
-0.012217958457767963,
-0.02809084579348564,
-0.025587288662791252,
0.059661105275154114,
-0.0... |
fa561f82-90d7-489d-8790-a3226bf77788 | Returned value
Returns the number of bytes, rounded up to the nearest integer, or
NULL
if unable to parse the input
Nullable(UInt64)
Examples
Usage example
sql title=Query
SELECT arrayJoin(['1 B', '1 KiB', '3 MB', '5.314 KiB', 'invalid']) AS readable_sizes, parseReadableSizeOrNull(readable_sizes) AS sizes;
response title=Response
ββreadable_sizesββ¬βββsizesββ
β 1 B β 1 β
β 1 KiB β 1024 β
β 3 MB β 3000000 β
β 5.314 KiB β 5442 β
β invalid β α΄Ία΅α΄Έα΄Έ β
ββββββββββββββββββ΄ββββββββββ
parseReadableSizeOrZero {#parseReadableSizeOrZero}
Introduced in: v24.6
Given a string containing a byte size and
B
,
KiB
,
KB
,
MiB
,
MB
, etc. as a unit (i.e.
ISO/IEC 80000-13
or decimal byte unit), this function returns the corresponding number of bytes.
If the function is unable to parse the input value, it returns
0
.
The inverse operations of this function are
formatReadableSize
and
formatReadableDecimalSize
.
Syntax
sql
parseReadableSizeOrZero(x)
Arguments
x
β Readable size with ISO/IEC 80000-13 or decimal byte unit.
String
Returned value
Returns the number of bytes, rounded up to the nearest integer, or
0
if unable to parse the input.
UInt64
Examples
Usage example
sql title=Query
SELECT arrayJoin(['1 B', '1 KiB', '3 MB', '5.314 KiB', 'invalid']) AS readable_sizes, parseReadableSizeOrZero(readable_sizes) AS sizes;
response title=Response
ββreadable_sizesββ¬βββsizesββ
β 1 B β 1 β
β 1 KiB β 1024 β
β 3 MB β 3000000 β
β 5.314 KiB β 5442 β
β invalid β 0 β
ββββββββββββββββββ΄ββββββββββ
parseTimeDelta {#parseTimeDelta}
Introduced in: v22.7
Parse a sequence of numbers followed by something resembling a time unit.
The time delta string uses these time unit specifications:
-
years
,
year
,
yr
,
y
-
months
,
month
,
mo
-
weeks
,
week
,
w
-
days
,
day
,
d
-
hours
,
hour
,
hr
,
h
-
minutes
,
minute
,
min
,
m
-
seconds
,
second
,
sec
,
s
-
milliseconds
,
millisecond
,
millisec
,
ms
-
microseconds
,
microsecond
,
microsec
,
ΞΌs
,
Β΅s
,
us
-
nanoseconds
,
nanosecond
,
nanosec
,
ns
Multiple time units can be combined with separators (space,
;
,
-
,
+
,
,
,
:
).
The length of years and months are approximations: year is 365 days, month is 30.5 days.
Syntax
sql
parseTimeDelta(timestr)
Arguments
timestr
β A sequence of numbers followed by something resembling a time unit.
String
Returned value
The number of seconds.
Float64
Examples
Usage example
sql title=Query
SELECT parseTimeDelta('11s+22min')
response title=Response
ββparseTimeDelta('11s+22min')ββ
β 1331 β
βββββββββββββββββββββββββββββββ
Complex time units
sql title=Query
SELECT parseTimeDelta('1yr2mo')
response title=Response
ββparseTimeDelta('1yr2mo')ββ
β 36806400 β
ββββββββββββββββββββββββββββ
partitionId {#partitionId} | {"source_file": "other-functions.md"} | [
0.010236036032438278,
0.02453939989209175,
-0.07912776619195938,
0.05271587893366814,
-0.10916189104318619,
-0.012447595596313477,
0.0669863373041153,
0.04372544586658478,
-0.0426427386701107,
-0.013595235534012318,
-0.04629340022802353,
-0.04928375780582428,
0.0447552427649498,
-0.0608319... |
9176bff7-e8b9-4b84-bafd-a53142396ccd | sql title=Query
SELECT parseTimeDelta('1yr2mo')
response title=Response
ββparseTimeDelta('1yr2mo')ββ
β 36806400 β
ββββββββββββββββββββββββββββ
partitionId {#partitionId}
Introduced in: v21.4
Computes the
partition ID
.
:::note
This function is slow and should not be called for large numbers of rows.
:::
Syntax
sql
partitionId(column1[, column2, ...])
Aliases
:
partitionID
Arguments
column1, column2, ...
β Column for which to return the partition ID.
Returned value
Returns the partition ID that the row belongs to.
String
Examples
Usage example
```sql title=Query
DROP TABLE IF EXISTS tab;
CREATE TABLE tab
(
i int,
j int
)
ENGINE = MergeTree
PARTITION BY i
ORDER BY tuple();
INSERT INTO tab VALUES (1, 1), (1, 2), (1, 3), (2, 4), (2, 5), (2, 6);
SELECT i, j, partitionId(i), _partition_id FROM tab ORDER BY i, j;
```
response title=Response
ββiββ¬βjββ¬βpartitionId(i)ββ¬β_partition_idββ
β 1 β 1 β 1 β 1 β
β 1 β 2 β 1 β 1 β
β 1 β 3 β 1 β 1 β
β 2 β 4 β 2 β 2 β
β 2 β 5 β 2 β 2 β
β 2 β 6 β 2 β 2 β
βββββ΄ββββ΄βββββββββββββββββ΄ββββββββββββββββ
queryID {#queryID}
Introduced in: v21.9
Returns the ID of the current query.
Other parameters of a query can be extracted from field
query_id
in the
system.query_log
table.
In contrast to
initialQueryID
function,
queryID
can return different results on different shards.
Syntax
sql
queryID()
Aliases
:
query_id
Arguments
None.
Returned value
Returns the ID of the current query.
String
Examples
Usage example
sql title=Query
CREATE TABLE tmp (str String) ENGINE = Log;
INSERT INTO tmp (*) VALUES ('a');
SELECT count(DISTINCT t) FROM (SELECT queryID() AS t FROM remote('127.0.0.{1..3}', currentDatabase(), 'tmp') GROUP BY queryID());
response title=Response
ββcount(DISTINCT t)ββ
β 3 β
βββββββββββββββββββββ
revision {#revision}
Introduced in: v22.7
Returns the current ClickHouse server revision.
Syntax
sql
revision()
Arguments
None.
Returned value
Returns the current ClickHouse server revision.
UInt32
Examples
Usage example
sql title=Query
SELECT revision()
response title=Response
ββrevision()ββ
β 54485 β
ββββββββββββββ
rowNumberInAllBlocks {#rowNumberInAllBlocks}
Introduced in: v1.1
Returns a unique row number for each row processed.
Syntax
sql
rowNumberInAllBlocks()
Arguments
None.
Returned value
Returns the ordinal number of the row in the data block starting from
0
.
UInt64
Examples
Usage example
sql title=Query
SELECT rowNumberInAllBlocks()
FROM
(
SELECT *
FROM system.numbers_mt
LIMIT 10
)
SETTINGS max_block_size = 2 | {"source_file": "other-functions.md"} | [
-0.021148597821593285,
0.000231345315114595,
0.04701998829841614,
-0.005784383974969387,
-0.032282449305057526,
-0.06291268765926361,
0.07686913758516312,
0.054525621235370636,
-0.002020507585257292,
-0.04970630258321762,
0.003409670665860176,
-0.03149450942873955,
-0.006763855926692486,
-... |
6069d191-aebd-40a7-82f8-82243361dfee | Examples
Usage example
sql title=Query
SELECT rowNumberInAllBlocks()
FROM
(
SELECT *
FROM system.numbers_mt
LIMIT 10
)
SETTINGS max_block_size = 2
response title=Response
ββrowNumberInAllBlocks()ββ
β 0 β
β 1 β
ββββββββββββββββββββββββββ
ββrowNumberInAllBlocks()ββ
β 4 β
β 5 β
ββββββββββββββββββββββββββ
ββrowNumberInAllBlocks()ββ
β 2 β
β 3 β
ββββββββββββββββββββββββββ
ββrowNumberInAllBlocks()ββ
β 6 β
β 7 β
ββββββββββββββββββββββββββ
ββrowNumberInAllBlocks()ββ
β 8 β
β 9 β
ββββββββββββββββββββββββββ
rowNumberInBlock {#rowNumberInBlock}
Introduced in: v1.1
For each
block
processed by
rowNumberInBlock
, returns the number of the current row.
The returned number starts from 0 for each block.
Syntax
sql
rowNumberInBlock()
Arguments
None.
Returned value
Returns the ordinal number of the row in the data block starting from
0
.
UInt64
Examples
Usage example
sql title=Query
SELECT rowNumberInBlock()
FROM
(
SELECT *
FROM system.numbers_mt
LIMIT 10
) SETTINGS max_block_size = 2
response title=Response
ββrowNumberInBlock()ββ
β 0 β
β 1 β
ββββββββββββββββββββββ
ββrowNumberInBlock()ββ
β 0 β
β 1 β
ββββββββββββββββββββββ
ββrowNumberInBlock()ββ
β 0 β
β 1 β
ββββββββββββββββββββββ
ββrowNumberInBlock()ββ
β 0 β
β 1 β
ββββββββββββββββββββββ
ββrowNumberInBlock()ββ
β 0 β
β 1 β
ββββββββββββββββββββββ
runningAccumulate {#runningAccumulate}
Introduced in: v1.1
Accumulates the states of an aggregate function for each row of a data block.
:::warning Deprecated
The state is reset for each new block of data.
Due to this error-prone behavior the function has been deprecated, and you are advised to use
window functions
instead.
You can use setting
allow_deprecated_error_prone_window_functions
to allow usage of this function.
:::
Syntax
sql
runningAccumulate(agg_state[, grouping])
Arguments
agg_state
β State of the aggregate function.
AggregateFunction
grouping
β Optional. Grouping key. The state of the function is reset if the
grouping
value is changed. It can be any of the supported data types for which the equality operator is defined.
Any
Returned value
Returns the accumulated result for each row.
Any
Examples
Usage example with initializeAggregation
sql title=Query
WITH initializeAggregation('sumState', number) AS one_row_sum_state
SELECT
number,
finalizeAggregation(one_row_sum_state) AS one_row_sum,
runningAccumulate(one_row_sum_state) AS cumulative_sum
FROM numbers(5); | {"source_file": "other-functions.md"} | [
-0.08028263598680496,
-0.024341970682144165,
-0.038813233375549316,
-0.0107577508315444,
-0.05763332173228264,
-0.015038833022117615,
0.0119194770231843,
0.028116948902606964,
-0.03266375511884689,
-0.010164350271224976,
-0.022563401609659195,
0.0068043069913983345,
0.003953215200453997,
-... |
b1c19436-129c-4c07-8bc0-6e3adc3ea4c6 | response title=Response
ββnumberββ¬βone_row_sumββ¬βcumulative_sumββ
β 0 β 0 β 0 β
β 1 β 1 β 1 β
β 2 β 2 β 3 β
β 3 β 3 β 6 β
β 4 β 4 β 10 β
ββββββββββ΄ββββββββββββββ΄βββββββββββββββββ
runningConcurrency {#runningConcurrency}
Introduced in: v21.3
Calculates the number of concurrent events.
Each event has a start time and an end time.
The start time is included in the event, while the end time is excluded.
Columns with a start time and an end time must be of the same data type.
The function calculates the total number of active (concurrent) events for each event start time.
:::tip Requirements
Events must be ordered by the start time in ascending order.
If this requirement is violated the function raises an exception.
Every data block is processed separately.
If events from different data blocks overlap then they can not be processed correctly.
:::
:::warning Deprecated
It is advised to use
window functions
instead.
:::
Syntax
sql
runningConcurrency(start, end)
Arguments
start
β A column with the start time of events.
Date
or
DateTime
or
DateTime64
end
β A column with the end time of events.
Date
or
DateTime
or
DateTime64
Returned value
Returns the number of concurrent events at each event start time.
UInt32
Examples
Usage example
sql title=Query
SELECT start, runningConcurrency(start, end) FROM example_table;
response title=Response
βββββββstartββ¬βrunningConcurrency(start, end)ββ
β 2025-03-03 β 1 β
β 2025-03-06 β 2 β
β 2025-03-07 β 3 β
β 2025-03-11 β 2 β
ββββββββββββββ΄βββββββββββββββββββββββββββββββββ
runningDifference {#runningDifference}
Introduced in: v1.1
Calculates the difference between two consecutive row values in the data block.
Returns
0
for the first row, and for subsequent rows the difference to the previous row.
:::warning Deprecated
Only returns differences inside the currently processed data block.
Because of this error-prone behavior, the function is deprecated.
It is advised to use
window functions
instead.
You can use setting
allow_deprecated_error_prone_window_functions
to allow usage of this function.
:::
The result of the function depends on the affected data blocks and the order of data in the block.
The order of rows during calculation of
runningDifference()
can differ from the order of rows returned to the user.
To prevent that you can create a subquery with
ORDER BY
and call the function from outside the subquery.
Please note that the block size affects the result.
The internal state of
runningDifference
state is reset for each new block.
Syntax
sql
runningDifference(x)
Arguments
x
β Column for which to calculate the running difference.
Any
Returned value | {"source_file": "other-functions.md"} | [
-0.027601728215813637,
-0.06886226683855057,
-0.04060085490345955,
0.04051213711500168,
-0.05431830883026123,
0.006695093121379614,
-0.018764056265354156,
-0.004698551259934902,
0.028341669589281082,
0.021928150206804276,
0.041354719549417496,
-0.09136991947889328,
-0.02383209578692913,
-0... |
f1c04a93-f12b-456b-822d-7e6d8fbfa56a | Syntax
sql
runningDifference(x)
Arguments
x
β Column for which to calculate the running difference.
Any
Returned value
Returns the difference between consecutive values, with 0 for the first row.
Examples
Usage example
sql title=Query
SELECT
EventID,
EventTime,
runningDifference(EventTime) AS delta
FROM
(
SELECT
EventID,
EventTime
FROM events
WHERE EventDate = '2025-11-24'
ORDER BY EventTime ASC
LIMIT 5
);
response title=Response
ββEventIDββ¬βββββββββββEventTimeββ¬βdeltaββ
β 1106 β 2025-11-24 00:00:04 β 0 β
β 1107 β 2025-11-24 00:00:05 β 1 β
β 1108 β 2025-11-24 00:00:05 β 0 β
β 1109 β 2025-11-24 00:00:09 β 4 β
β 1110 β 2025-11-24 00:00:10 β 1 β
βββββββββββ΄ββββββββββββββββββββββ΄ββββββββ
Block size impact example
sql title=Query
SELECT
number,
runningDifference(number + 1) AS diff
FROM numbers(100000)
WHERE diff != 1;
response title=Response
ββnumberββ¬βdiffββ
β 0 β 0 β
ββββββββββ΄βββββββ
ββnumberββ¬βdiffββ
β 65536 β 0 β
ββββββββββ΄βββββββ
runningDifferenceStartingWithFirstValue {#runningDifferenceStartingWithFirstValue}
Introduced in: v1.1
Calculates the difference between consecutive row values in a data block, but unlike
runningDifference
, it returns the actual value of the first row instead of
0
.
:::warning Deprecated
Only returns differences inside the currently processed data block.
Because of this error-prone behavior, the function is deprecated.
It is advised to use
window functions
instead.
You can use setting
allow_deprecated_error_prone_window_functions
to allow usage of this function.
:::
Syntax
sql
runningDifferenceStartingWithFirstValue(x)
Arguments
x
β Column for which to calculate the running difference.
Any
Returned value
Returns the difference between consecutive values, with the first row's value for the first row.
Any
Examples
Usage example
sql title=Query
SELECT
number,
runningDifferenceStartingWithFirstValue(number) AS diff
FROM numbers(5);
response title=Response
ββnumberββ¬βdiffββ
β 0 β 0 β
β 1 β 1 β
β 2 β 1 β
β 3 β 1 β
β 4 β 1 β
ββββββββββ΄βββββββ
serverUUID {#serverUUID}
Introduced in: v20.1
Returns the random and unique UUID (v4) generated when the server is first started.
The UUID is persisted, i.e. the second, third, etc. server start return the same UUID.
Syntax
sql
serverUUID()
Arguments
None.
Returned value
Returns the random UUID of the server.
UUID
Examples
Usage example
sql title=Query
SELECT serverUUID();
response title=Response
ββserverUUID()ββββββββββββββββββββββββββββββ
β 7ccc9260-000d-4d5c-a843-5459abaabb5f β
ββββββββββββββββββββββββββββββββββββββββββββ
shardCount {#shardCount}
Introduced in: v21.9
Returns the total number of shards for a distributed query.
If a query is not distributed then constant value
0
is returned.
Syntax
sql
shardCount() | {"source_file": "other-functions.md"} | [
-0.01623208448290825,
-0.00007350810483330861,
0.0035730840172618628,
-0.01030436996370554,
-0.02291635051369667,
-0.04658134654164314,
0.03547393158078194,
0.0008797834161669016,
0.03902420401573181,
0.0008242317126132548,
-0.019074609503149986,
-0.046904340386390686,
-0.07414205372333527,
... |
7eafe64e-8ddd-4221-ac86-eaba07615122 | Introduced in: v21.9
Returns the total number of shards for a distributed query.
If a query is not distributed then constant value
0
is returned.
Syntax
sql
shardCount()
Arguments
None.
Returned value
Returns the total number of shards or
0
.
UInt32
Examples
Usage example
sql title=Query
-- See shardNum() example above which also demonstrates shardCount()
CREATE TABLE shard_count_example (dummy UInt8)
ENGINE=Distributed(test_cluster_two_shards_localhost, system, one, dummy);
SELECT shardCount() FROM shard_count_example;
response title=Response
ββshardCount()ββ
β 2 β
β 2 β
ββββββββββββββββ
shardNum {#shardNum}
Introduced in: v21.9
Returns the index of a shard which processes a part of data in a distributed query.
Indices begin from
1
.
If a query is not distributed then a constant value
0
is returned.
Syntax
sql
shardNum()
Arguments
None.
Returned value
Returns the shard index or a constant
0
.
UInt32
Examples
Usage example
sql title=Query
CREATE TABLE shard_num_example (dummy UInt8)
ENGINE=Distributed(test_cluster_two_shards_localhost, system, one, dummy);
SELECT dummy, shardNum(), shardCount() FROM shard_num_example;
response title=Response
ββdummyββ¬βshardNum()ββ¬βshardCount()ββ
β 0 β 1 β 2 β
β 0 β 2 β 2 β
βββββββββ΄βββββββββββββ΄βββββββββββββββ
showCertificate {#showCertificate}
Introduced in: v22.6
Shows information about the current server's Secure Sockets Layer (SSL) certificate if it has been configured.
See
Configuring SSL-TLS
for more information on how to configure ClickHouse to use OpenSSL certificates to validate connections.
Syntax
sql
showCertificate()
Arguments
None.
Returned value
Returns map of key-value pairs relating to the configured SSL certificate.
Map(String, String)
Examples
Usage example
sql title=Query
SELECT showCertificate() FORMAT LineAsString;
response title=Response
{'version':'1','serial_number':'2D9071D64530052D48308473922C7ADAFA85D6C5','signature_algo':'sha256WithRSAEncryption','issuer':'/CN=marsnet.local CA','not_before':'May 7 17:01:21 2024 GMT','not_after':'May 7 17:01:21 2025 GMT','subject':'/CN=chnode1','pkey_algo':'rsaEncryption'}
sleep {#sleep}
Introduced in: v1.1
Pauses the execution of a query by the specified number of seconds.
The function is primarily used for testing and debugging purposes.
The
sleep()
function should generally not be used in production environments, as it can negatively impact query performance and system responsiveness.
However, it can be useful in the following scenarios:
Testing
: When testing or benchmarking ClickHouse, you may want to simulate delays or introduce pauses to observe how the system behaves under certain conditions. | {"source_file": "other-functions.md"} | [
0.07398514449596405,
-0.06357374042272568,
-0.01685524359345436,
0.07232260704040527,
-0.049440689384937286,
-0.011903746984899044,
-0.01899501495063305,
-0.023001449182629585,
0.06856793165206909,
-0.009615328162908554,
0.029753118753433228,
-0.020820798352360725,
0.0553583949804306,
-0.0... |
41227203-1113-439d-ba79-7bd147fd9a69 | Testing
: When testing or benchmarking ClickHouse, you may want to simulate delays or introduce pauses to observe how the system behaves under certain conditions.
Debugging
: If you need to examine the state of the system or the execution of a query at a specific point in time, you can use
sleep()
to introduce a pause, allowing you to inspect or collect relevant information.
Simulation
: In some cases, you may want to simulate real-world scenarios where delays or pauses occur, such as network latency or external system dependencies.
:::warning
It's important to use the
sleep()
function judiciously and only when necessary, as it can potentially impact the overall performance and responsiveness of your ClickHouse system.
:::
For security reasons, the function can only be executed in the default user profile (with
allow_sleep
enabled).
Syntax
sql
sleep(seconds)
Arguments
seconds
β The number of seconds to pause the query execution to a maximum of 3 seconds. It can be a floating-point value to specify fractional seconds.
const UInt*
or
const Float*
Returned value
Returns
0
.
UInt8
Examples
Usage example
sql title=Query
-- This query will pause for 2 seconds before completing.
-- During this time, no results will be returned, and the query will appear to be hanging or unresponsive.
SELECT sleep(2);
response title=Response
ββsleep(2)ββ
β 0 β
ββββββββββββ
1 row in set. Elapsed: 2.012 sec.
sleepEachRow {#sleepEachRow}
Introduced in: v1.1
Pauses the execution of a query for a specified number of seconds for each row in the result set.
The
sleepEachRow()
function is primarily used for testing and debugging purposes, similar to the
sleep()
function.
It allows you to simulate delays or introduce pauses in the processing of each row, which can be useful in scenarios such as:
Testing
: When testing or benchmarking ClickHouse's performance under specific conditions, you can use
sleepEachRow()
to simulate delays or introduce pauses for each row processed.
Debugging
: If you need to examine the state of the system or the execution of a query for each row processed, you can use
sleepEachRow()
to introduce pauses, allowing you to inspect or collect relevant information.
Simulation
: In some cases, you may want to simulate real-world scenarios where delays or pauses occur for each row processed, such as when dealing with external systems or network latencies.
:::warning
Like the
sleep()
function, it's important to use
sleepEachRow()
judiciously and only when necessary, as it can significantly impact the overall performance and responsiveness of your ClickHouse system, especially when dealing with large result sets.
:::
Syntax
sql
sleepEachRow(seconds)
Arguments | {"source_file": "other-functions.md"} | [
-0.04390041157603264,
-0.0743931233882904,
-0.09817603975534439,
0.06926333159208298,
-0.035038743168115616,
-0.06276629120111465,
0.03154131397604942,
-0.036164090037345886,
-0.028481248766183853,
-0.0331881046295166,
0.008682552725076675,
-0.01637507975101471,
0.0028539220802485943,
-0.0... |
1203cba5-3d67-4385-9c9d-7934e95d1231 | Syntax
sql
sleepEachRow(seconds)
Arguments
seconds
β The number of seconds to pause the query execution for each row in the result set to a maximum of 3 seconds. It can be a floating-point value to specify fractional seconds.
const UInt*
or
const Float*
Returned value
Returns
0
for each row.
UInt8
Examples
Usage example
sql title=Query
-- The output will be delayed, with a 0.5-second pause between each row.
SELECT number, sleepEachRow(0.5) FROM system.numbers LIMIT 5;
response title=Response
ββnumberββ¬βsleepEachRow(0.5)ββ
β 0 β 0 β
β 1 β 0 β
β 2 β 0 β
β 3 β 0 β
β 4 β 0 β
ββββββββββ΄ββββββββββββββββββββ
structureToCapnProtoSchema {#structureToCapnProtoSchema}
Introduced in: v
Function that converts ClickHouse table structure to CapnProto format schema
Syntax
```sql
```
Arguments
None.
Returned value
Examples
random
sql title=Query
SELECT structureToCapnProtoSchema('s String, x UInt32', 'MessageName') format TSVRaw
response title=Response
struct MessageName
{
s @0 : Data;
x @1 : UInt32;
}
structureToProtobufSchema {#structureToProtobufSchema}
Introduced in: v23.8
Converts a ClickHouse table structure to Protobuf format schema.
This function takes a ClickHouse table structure definition and converts it into a Protocol Buffers (Protobuf)
schema definition in proto3 syntax. This is useful for generating Protobuf schemas that match your ClickHouse
table structures for data interchange.
Syntax
sql
structureToProtobufSchema(structure, message_name)
Arguments
structure
β ClickHouse table structure definition as a string (e.g., 'column1 Type1, column2 Type2').
String
message_name
β Name for the Protobuf message type in the generated schema.
String
Returned value
Returns a Protobuf schema definition in proto3 syntax that corresponds to the input ClickHouse structure.
String
Examples
Converting ClickHouse structure to Protobuf schema
sql title=Query
SELECT structureToProtobufSchema('s String, x UInt32', 'MessageName') FORMAT TSVRaw;
```response title=Response
syntax = "proto3";
message MessageName
{
bytes s = 1;
uint32 x = 2;
}
```
tcpPort {#tcpPort}
Introduced in: v20.12
Returns the
native interface
TCP port number listened to by the server.
If executed in the context of a distributed table, this function generates a normal column with values relevant to each shard.
Otherwise it produces a constant value.
Syntax
sql
tcpPort()
Arguments
None.
Returned value
Returns the TCP port number.
UInt16
Examples
Usage example
sql title=Query
SELECT tcpPort()
response title=Response
ββtcpPort()ββ
β 9000 β
βββββββββββββ
throwIf {#throwIf}
Introduced in: v1.1
Throw an exception if argument x is true.
To use the
error_code
argument, configuration parameter
allow_custom_error_code_in_throw
must be enabled. | {"source_file": "other-functions.md"} | [
-0.008616884239017963,
-0.022453488782048225,
-0.07565426826477051,
0.07196702063083649,
-0.027250532060861588,
-0.03068586066365242,
0.07592014968395233,
-0.03545067086815834,
0.03869376704096794,
-0.002793962834402919,
0.000414715294027701,
-0.06608826667070389,
-0.04986156150698662,
-0.... |
8f1df287-4c2e-460a-a21d-9b32b2be7b07 | throwIf {#throwIf}
Introduced in: v1.1
Throw an exception if argument x is true.
To use the
error_code
argument, configuration parameter
allow_custom_error_code_in_throw
must be enabled.
Syntax
sql
throwIf(x[, message[, error_code]])
Arguments
x
β The condition to check.
Any
message
β Optional. Custom error message.
const String
error_code
β Optional. Custom error code.
const Int8/16/32
Returned value
Returns
0
if the condition is false, throws an exception if the condition is true.
UInt8
Examples
Usage example
sql title=Query
SELECT throwIf(number = 3, 'Too many') FROM numbers(10);
response title=Response
β Progress: 0.00 rows, 0.00 B (0.00 rows/s., 0.00 B/s.) Received exception from server (version 19.14.1):
Code: 395. DB::Exception: Received from localhost:9000. DB::Exception: Too many.
toColumnTypeName {#toColumnTypeName}
Introduced in: v1.1
Returns the internal name of the data type of the given value.
Unlike function
toTypeName
, the returned data type potentially includes internal wrapper columns like
Const
and
LowCardinality
.
Syntax
sql
toColumnTypeName(value)
Arguments
value
β Value for which to return the internal data type.
Any
Returned value
Returns the internal data type used to represent the value.
String
Examples
Usage example
sql title=Query
SELECT toColumnTypeName(CAST('2025-01-01 01:02:03' AS DateTime));
response title=Response
ββtoColumnTypeName(CAST('2025-01-01 01:02:03', 'DateTime'))ββ
β Const(UInt32) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
toTypeName {#toTypeName}
Introduced in: v1.1
Returns the type name of the passed argument.
If
NULL
is passed, the function returns type
Nullable(Nothing)
, which corresponds to ClickHouse's internal
NULL
representation.
Syntax
sql
toTypeName(x)
Arguments
x
β A value of arbitrary type.
Any
Returned value
Returns the data type name of the input value.
String
Examples
Usage example
sql title=Query
SELECT toTypeName(123)
response title=Response
ββtoTypeName(123)ββ
β UInt8 β
βββββββββββββββββββ
transactionID {#transactionID}
Introduced in: v22.6
Returns the ID of a transaction.
:::note
This function is part of an experimental feature set.
Enable experimental transaction support by adding this setting to your
configuration
:
xml
<clickhouse>
<allow_experimental_transactions>1</allow_experimental_transactions>
</clickhouse>
For more information see the page
Transactional (ACID) support
.
:::
Syntax
sql
transactionID()
Arguments
None.
Returned value | {"source_file": "other-functions.md"} | [
0.056988559663295746,
0.017696095630526543,
-0.0438944511115551,
0.03779119998216629,
-0.0035682108718901873,
0.038606662303209305,
0.05471086502075195,
0.09324057400226593,
-0.028272032737731934,
0.019958755001425743,
0.046722933650016785,
-0.07633545994758606,
0.06648501008749008,
-0.032... |
5282900d-abdf-4097-9d8f-eba49e7c8a31 | For more information see the page
Transactional (ACID) support
.
:::
Syntax
sql
transactionID()
Arguments
None.
Returned value
Returns a tuple consisting of
start_csn
,
local_tid
and
host_id
.
-
start_csn
: Global sequential number, the newest commit timestamp that was seen when this transaction began.
-
local_tid
: Local sequential number that is unique for each transaction started by this host within a specific start_csn.
-
host_id
: UUID of the host that has started this transaction.
Tuple(UInt64, UInt64, UUID)
Examples
Usage example
sql title=Query
BEGIN TRANSACTION;
SELECT transactionID();
ROLLBACK;
response title=Response
ββtransactionID()βββββββββββββββββββββββββββββββββ
β (32,34,'0ee8b069-f2bb-4748-9eae-069c85b5252b') β
ββββββββββββββββββββββββββββββββββββββββββββββββββ
transactionLatestSnapshot {#transactionLatestSnapshot}
Introduced in: v22.6
Returns the newest snapshot (Commit Sequence Number) of a
transaction
that is available for reading.
:::note
This function is part of an experimental feature set. Enable experimental transaction support by adding this setting to your configuration:
xml
<clickhouse>
<allow_experimental_transactions>1</allow_experimental_transactions>
</clickhouse>
For more information see the page
Transactional (ACID) support
.
:::
Syntax
sql
transactionLatestSnapshot()
Arguments
None.
Returned value
Returns the latest snapshot (CSN) of a transaction.
UInt64
Examples
Usage example
sql title=Query
BEGIN TRANSACTION;
SELECT transactionLatestSnapshot();
ROLLBACK;
response title=Response
ββtransactionLatestSnapshot()ββ
β 32 β
βββββββββββββββββββββββββββββββ
transactionOldestSnapshot {#transactionOldestSnapshot}
Introduced in: v22.6
Returns the oldest snapshot (Commit Sequence Number) that is visible for some running
transaction
.
:::note
This function is part of an experimental feature set. Enable experimental transaction support by adding this setting to your configuration:
xml
<clickhouse>
<allow_experimental_transactions>1</allow_experimental_transactions>
</clickhouse>
For more information see the page
Transactional (ACID) support
.
:::
Syntax
sql
transactionOldestSnapshot()
Arguments
None.
Returned value
Returns the oldest snapshot (CSN) of a transaction.
UInt64
Examples
Usage example
sql title=Query
BEGIN TRANSACTION;
SELECT transactionOldestSnapshot();
ROLLBACK;
response title=Response
ββtransactionOldestSnapshot()ββ
β 32 β
βββββββββββββββββββββββββββββββ
transform {#transform}
Introduced in: v1.1
Transforms a value according to the explicitly defined mapping of some elements to other elements. | {"source_file": "other-functions.md"} | [
-0.05709048733115196,
-0.023723818361759186,
-0.094562828540802,
0.027590081095695496,
-0.03376691788434982,
0.025469722226262093,
0.06774485111236572,
-0.02847016043961048,
0.07927986234426498,
-0.030222967267036438,
0.06775632500648499,
0.03471486642956734,
0.0018577591981738806,
-0.0898... |
ecbf736a-d784-4b42-a967-e597fde0ed83 | transform {#transform}
Introduced in: v1.1
Transforms a value according to the explicitly defined mapping of some elements to other elements.
There are two variations of this function:
-
transform(x, array_from, array_to, default)
- transforms
x
using mapping arrays with a default value for unmatched elements
-
transform(x, array_from, array_to)
- same transformation but returns the original
x
if no match is found
The function searches for
x
in
array_from
and returns the corresponding element from
array_to
at the same index.
If
x
is not found in
array_from
, it returns either the
default
value (4-parameter version) or the original
x
(3-parameter version).
If multiple matching elements exist in
array_from
, it returns the element corresponding to the first match.
Requirements:
-
array_from
and
array_to
must have the same number of elements
- For 4-parameter version:
transform(T, Array(T), Array(U), U) -> U
where
T
and
U
can be different compatible types
- For 3-parameter version:
transform(T, Array(T), Array(T)) -> T
where all types must be the same
Syntax
sql
transform(x, array_from, array_to[, default])
Arguments
x
β Value to transform.
(U)Int*
or
Decimal
or
Float*
or
String
or
Date
or
DateTime
array_from
β Constant array of values to search for matches.
Array((U)Int*)
or
Array(Decimal)
or
Array(Float*)
or
Array(String)
or
Array(Date)
or
Array(DateTime)
array_to
β Constant array of values to return for corresponding matches in
array_from
.
Array((U)Int*)
or
Array(Decimal)
or
Array(Float*)
or
Array(String)
or
Array(Date)
or
Array(DateTime)
default
β Optional. Value to return if
x
is not found in
array_from
. If omitted, returns x unchanged.
(U)Int*
or
Decimal
or
Float*
or
String
or
Date
or
DateTime
Returned value
Returns the corresponding value from
array_to
if x matches an element in
array_from
, otherwise returns default (if provided) or x (if default not provided).
Any
Examples
transform(T, Array(T), Array(U), U) -> U
sql title=Query
SELECT
transform(SearchEngineID, [2, 3], ['Yandex', 'Google'], 'Other') AS title,
count() AS c
FROM test.hits
WHERE SearchEngineID != 0
GROUP BY title
ORDER BY c DESC
response title=Response
ββtitleββββββ¬ββββββcββ
β Yandex β 498635 β
β Google β 229872 β
β Other β 104472 β
βββββββββββββ΄βββββββββ
transform(T, Array(T), Array(T)) -> T
sql title=Query
SELECT
transform(domain(Referer), ['yandex.ru', 'google.ru', 'vkontakte.ru'], ['www.yandex', 'example.com', 'vk.com']) AS s, count() AS c
FROM test.hits
GROUP BY domain(Referer)
ORDER BY count() DESC
LIMIT 10 | {"source_file": "other-functions.md"} | [
0.019958680495619774,
0.01627594232559204,
-0.00826269295066595,
-0.04910941794514656,
0.005055942106992006,
-0.06812307983636856,
0.039984509348869324,
-0.08926647156476974,
-0.014312569983303547,
-0.054130423814058304,
0.0035106800496578217,
0.0060724555514752865,
0.007072984240949154,
-... |
73fd3d06-839e-48d7-9cd5-fb519209a61e | response title=Response
ββsβββββββββββββββ¬βββββββcββ
β β 2906259 β
β www.yandex β 867767 β
β βββββββ.ru β 313599 β
β mail.yandex.ru β 107147 β
β ββββββ.ru β 100355 β
β βββββββββ.ru β 65040 β
β news.yandex.ru β 64515 β
β ββββββ.net β 59141 β
β example.com β 57316 β
ββββββββββββββββββ΄ββββββββββ
uniqThetaIntersect {#uniqThetaIntersect}
Introduced in: v22.9
Two uniqThetaSketch objects to do intersect calculation(set operation β©), the result is a new uniqThetaSketch.
Syntax
sql
uniqThetaIntersect(uniqThetaSketch,uniqThetaSketch)
Arguments
uniqThetaSketch
β uniqThetaSketch object.
Tuple
or
Array
or
Date
or
DateTime
or
String
or
(U)Int*
or
Float*
or
Decimal
Returned value
A new uniqThetaSketch containing the intersect result.
UInt64
Examples
Usage example
sql title=Query
SELECT finalizeAggregation(uniqThetaIntersect(a, b)) AS a_intersect_b, finalizeAggregation(a) AS a_cardinality, finalizeAggregation(b) AS b_cardinality
FROM
(SELECT arrayReduce('uniqThetaState', [1, 2]) AS a, arrayReduce('uniqThetaState', [2, 3, 4]) AS b);
response title=Response
ββa_intersect_bββ¬βa_cardinalityββ¬βb_cardinalityββ
β 1 β 2 β 3 β
βββββββββββββββββ΄ββββββββββββββββ΄ββββββββββββββββ
uniqThetaNot {#uniqThetaNot}
Introduced in: v22.9
Two uniqThetaSketch objects to do a_not_b calculation(set operation Γ), the result is a new uniqThetaSketch.
Syntax
sql
uniqThetaNot(uniqThetaSketch,uniqThetaSketch)
Arguments
uniqThetaSketch
β uniqThetaSketch object.
Tuple
or
Array
or
Date
or
DateTime
or
String
or
(U)Int*
or
Float*
or
Decimal
Returned value
Returns a new uniqThetaSketch containing the a_not_b result.
UInt64
Examples
Usage example
sql title=Query
SELECT finalizeAggregation(uniqThetaNot(a, b)) AS a_not_b, finalizeAggregation(a) AS a_cardinality, finalizeAggregation(b) AS b_cardinality
FROM
(SELECT arrayReduce('uniqThetaState', [2, 3, 4]) AS a, arrayReduce('uniqThetaState', [1, 2]) AS b);
response title=Response
ββa_not_bββ¬βa_cardinalityββ¬βb_cardinalityββ
β 2 β 3 β 2 β
βββββββββββ΄ββββββββββββββββ΄ββββββββββββββββ
uniqThetaUnion {#uniqThetaUnion}
Introduced in: v22.9
Two uniqThetaSketch objects to do union calculation(set operation βͺ), the result is a new uniqThetaSketch.
Syntax
sql
uniqThetaUnion(uniqThetaSketch,uniqThetaSketch)
Arguments
uniqThetaSketch
β uniqThetaSketch object.
Tuple
or
Array
or
Date
or
DateTime
or
String
or
(U)Int*
or
Float*
or
Decimal
Returned value
Returns a new uniqThetaSketch containing the union result.
UInt64
Examples
Usage example
sql title=Query
SELECT finalizeAggregation(uniqThetaUnion(a, b)) AS a_union_b, finalizeAggregation(a) AS a_cardinality, finalizeAggregation(b) AS b_cardinality
FROM
(SELECT arrayReduce('uniqThetaState', [1, 2]) AS a, arrayReduce('uniqThetaState', [2, 3, 4]) AS b); | {"source_file": "other-functions.md"} | [
0.016171589493751526,
-0.06339989602565765,
0.007817618548870087,
0.079646535217762,
-0.023572219535708427,
-0.026334771886467934,
0.15784819424152374,
-0.042742062360048294,
-0.01679311878979206,
0.0208742618560791,
-0.0047363294288516045,
-0.058561887592077255,
0.08013410121202469,
-0.07... |
81473682-e8ac-44fb-a0de-0f5f002eaa15 | response title=Response
ββa_union_bββ¬βa_cardinalityββ¬βb_cardinalityββ
β 4 β 2 β 3 β
βββββββββββββ΄ββββββββββββββββ΄ββββββββββββββββ
uptime {#uptime}
Introduced in: v1.1
Returns the server's uptime in seconds.
If executed in the context of a distributed table, this function generates a normal column with values relevant to each shard.
Otherwise it produces a constant value.
Syntax
sql
uptime()
Arguments
None.
Returned value
Returns the server uptime in seconds.
UInt32
Examples
Usage example
sql title=Query
SELECT uptime() AS Uptime
response title=Response
ββUptimeββ
β 55867 β
ββββββββββ
variantElement {#variantElement}
Introduced in: v25.2
Extracts a column with specified type from a
Variant
column.
Syntax
sql
variantElement(variant, type_name[, default_value])
Arguments
variant
β Variant column.
Variant
type_name
β The name of the variant type to extract.
String
default_value
β The default value that will be used if variant doesn't have variant with specified type. Can be any type. Optional.
Any
Returned value
Returns a column with the specified variant type extracted from the Variant column.
Any
Examples
Usage example
sql title=Query
CREATE TABLE test (v Variant(UInt64, String, Array(UInt64))) ENGINE = Memory;
INSERT INTO test VALUES (NULL), (42), ('Hello, World!'), ([1, 2, 3]);
SELECT v, variantElement(v, 'String'), variantElement(v, 'UInt64'), variantElement(v, 'Array(UInt64)') FROM test;
response title=Response
ββvββββββββββββββ¬βvariantElement(v, 'String')ββ¬βvariantElement(v, 'UInt64')ββ¬βvariantElement(v, 'Array(UInt64)')ββ
β α΄Ία΅α΄Έα΄Έ β α΄Ία΅α΄Έα΄Έ β α΄Ία΅α΄Έα΄Έ β [] β
β 42 β α΄Ία΅α΄Έα΄Έ β 42 β [] β
β Hello, World! β Hello, World! β α΄Ία΅α΄Έα΄Έ β [] β
β [1,2,3] β α΄Ία΅α΄Έα΄Έ β α΄Ία΅α΄Έα΄Έ β [1,2,3] β
βββββββββββββββββ΄ββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββ
variantType {#variantType}
Introduced in: v24.2
Returns the variant type name for each row of
Variant
column. If row contains NULL, it returns 'None' for it.
Syntax
sql
variantType(variant)
Arguments
variant
β Variant column.
Variant
Returned value
Returns an Enum column with variant type name for each row.
Enum
Examples
Usage example
sql title=Query
CREATE TABLE test (v Variant(UInt64, String, Array(UInt64))) ENGINE = Memory;
INSERT INTO test VALUES (NULL), (42), ('Hello, World!'), ([1, 2, 3]);
SELECT variantType(v) FROM test;
response title=Response
ββvariantType(v)ββ
β None β
β UInt64 β
β String β
β Array(UInt64) β
ββββββββββββββββββ
version {#version}
Introduced in: v1.1 | {"source_file": "other-functions.md"} | [
-0.03478710725903511,
0.021840615198016167,
-0.048809200525283813,
0.07326848804950714,
-0.033821772783994675,
-0.008180259726941586,
0.020038625225424767,
0.02150631882250309,
0.015795135870575905,
0.016530834138393402,
0.0038311397656798363,
-0.05990653485059738,
-0.0349750816822052,
-0.... |
48d96c32-094c-471c-8850-3a57d7bba978 | response title=Response
ββvariantType(v)ββ
β None β
β UInt64 β
β String β
β Array(UInt64) β
ββββββββββββββββββ
version {#version}
Introduced in: v1.1
Returns the current version of ClickHouse as a string in the form:
major_version.minor_version.patch_version.number_of_commits_since_the_previous_stable_release
.
If executed in the context of a distributed table, this function generates a normal column with values relevant to each shard.
Otherwise, it produces a constant value.
Syntax
sql
version()
Arguments
None.
Returned value
Returns the current version of ClickHouse.
String
Examples
Usage example
sql title=Query
SELECT version()
response title=Response
ββversion()ββ
β 24.2.1.1 β
βββββββββββββ
visibleWidth {#visibleWidth}
Introduced in: v1.1
Calculates the approximate width when outputting values to the console in text format (tab-separated).
This function is used by the system to implement Pretty formats.
NULL
is represented as a string corresponding to
NULL
in Pretty formats.
Syntax
sql
visibleWidth(x)
Arguments
x
β A value of any data type.
Any
Returned value
Returns the approximate width of the value when displayed in text format.
UInt64
Examples
Calculate visible width of NULL
sql title=Query
SELECT visibleWidth(NULL)
response title=Response
ββvisibleWidth(NULL)ββ
β 4 β
ββββββββββββββββββββββ
zookeeperSessionUptime {#zookeeperSessionUptime}
Introduced in: v21.11
Returns the uptime of the current ZooKeeper session in seconds.
Syntax
sql
zookeeperSessionUptime()
Arguments
None.
Returned value
Returns the uptime of the current ZooKeeper session in seconds.
UInt32
Examples
Usage example
sql title=Query
SELECT zookeeperSessionUptime();
response title=Response
ββzookeeperSessionUptime()ββ
β 286 β
ββββββββββββββββββββββββββββ | {"source_file": "other-functions.md"} | [
0.03651052713394165,
-0.004941627383232117,
-0.03733937442302704,
0.05498012155294418,
-0.029756104573607445,
-0.04897685721516609,
-0.004665188957005739,
-0.013728780671954155,
-0.03118627518415451,
0.028144966810941696,
0.06135944277048111,
-0.013354463502764702,
0.021038005128502846,
-0... |
dc8caef7-2d2b-478c-846b-8fcd7e4aade7 | description: 'Documentation for Json Functions'
sidebar_label: 'JSON'
slug: /sql-reference/functions/json-functions
title: 'JSON Functions'
doc_type: 'reference'
Types of JSON functions {#types-of-functions}
There are two sets of functions to parse JSON:
-
simpleJSON*
(
visitParam*
)
which is made for parsing a limited subset of JSON extremely fast.
-
JSONExtract*
which is made for parsing ordinary JSON.
simpleJSON (visitParam) functions {#simplejson-visitparam-functions}
ClickHouse has special functions for working with simplified JSON. All these JSON functions are based on strong assumptions about what the JSON can be. They try to do as little as possible to get the job done as quickly as possible.
The following assumptions are made:
The field name (function argument) must be a constant.
The field name is somehow canonically encoded in JSON. For example:
simpleJSONHas('{"abc":"def"}', 'abc') = 1
, but
simpleJSONHas('{"\\u0061\\u0062\\u0063":"def"}', 'abc') = 0
Fields are searched for on any nesting level, indiscriminately. If there are multiple matching fields, the first occurrence is used.
The JSON does not have space characters outside of string literals.
JSONExtract functions {#jsonextract-functions}
These functions are based on
simdjson
, and designed for more complex JSON parsing requirements.
Case-Insensitive JSONExtract Functions {#case-insensitive-jsonextract-functions}
These functions perform ASCII case-insensitive key matching when extracting values from JSON objects.
They work identically to their case-sensitive counterparts, except that object keys are matched without regard to case.
When multiple keys match with different cases, the first match is returned.
:::note
These functions may be less performant than their case-sensitive counterparts, so use the regular JSONExtract functions if possible.
:::
JSONAllPaths {#JSONAllPaths}
Introduced in: v24.8
Returns the list of all paths stored in each row in JSON column.
Syntax
sql
JSONAllPaths(json)
Arguments
json
β JSON column.
JSON
Returned value
Returns an array of all paths in the JSON column.
Array(String)
Examples
Usage example
sql title=Query
CREATE TABLE test (json JSON(max_dynamic_paths=1)) ENGINE = Memory;
INSERT INTO test FORMAT JSONEachRow {"json" : {"a" : 42}}, {"json" : {"b" : "Hello"}}, {"json" : {"a" : [1, 2, 3], "c" : "2020-01-01"}}
SELECT json, JSONAllPaths(json) FROM test;
response title=Response
ββjsonββββββββββββββββββββββββββββββββββ¬βJSONAllPaths(json)ββ
β {"a":"42"} β ['a'] β
β {"b":"Hello"} β ['b'] β
β {"a":["1","2","3"],"c":"2020-01-01"} β ['a','c'] β
ββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββ
JSONAllPathsWithTypes {#JSONAllPathsWithTypes}
Introduced in: v24.8
Returns the list of all paths and their data types stored in each row in JSON column.
Syntax | {"source_file": "json-functions.md"} | [
-0.06949818879365921,
0.022027993574738503,
-0.019771326333284378,
0.001794022275134921,
-0.07199224829673767,
-0.048478368669748306,
-0.030054472386837006,
0.020059529691934586,
-0.04333706572651863,
-0.09002312272787094,
0.05594927817583084,
-0.015175734646618366,
-0.029871702194213867,
... |
31518d77-fa76-49d7-b780-c15a1667a8b3 | JSONAllPathsWithTypes {#JSONAllPathsWithTypes}
Introduced in: v24.8
Returns the list of all paths and their data types stored in each row in JSON column.
Syntax
sql
JSONAllPathsWithTypes(json)
Arguments
json
β JSON column.
JSON
Returned value
Returns a map of all paths and their data types in the JSON column.
Map(String, String)
Examples
Usage example
sql title=Query
CREATE TABLE test (json JSON(max_dynamic_paths=1)) ENGINE = Memory;
INSERT INTO test FORMAT JSONEachRow {"json" : {"a" : 42}}, {"json" : {"b" : "Hello"}}, {"json" : {"a" : [1, 2, 3], "c" : "2020-01-01"}}
SELECT json, JSONAllPathsWithTypes(json) FROM test;
response title=Response
ββjsonββββββββββββββββββββββββββββββββββ¬βJSONAllPathsWithTypes(json)ββββββββββββββββ
β {"a":"42"} β {'a':'Int64'} β
β {"b":"Hello"} β {'b':'String'} β
β {"a":["1","2","3"],"c":"2020-01-01"} β {'a':'Array(Nullable(Int64))','c':'Date'} β
ββββββββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββ
JSONArrayLength {#JSONArrayLength}
Introduced in: v23.2
Returns the number of elements in the outermost JSON array.
The function returns
NULL
if input JSON string is invalid.
Syntax
sql
JSONArrayLength(json)
Aliases
:
JSON_ARRAY_LENGTH
Arguments
json
β String with valid JSON.
String
Returned value
Returns the number of array elements if
json
is a valid JSON array string, otherwise returns
NULL
.
Nullable(UInt64)
Examples
Usage example
sql title=Query
SELECT
JSONArrayLength(''),
JSONArrayLength('[1,2,3]');
response title=Response
ββJSONArrayLength('')ββ¬βJSONArrayLength('[1,2,3]')ββ
β α΄Ία΅α΄Έα΄Έ β 3 β
βββββββββββββββββββββββ΄βββββββββββββββββββββββββββββ
JSONDynamicPaths {#JSONDynamicPaths}
Introduced in: v24.8
Returns the list of dynamic paths that are stored as separate subcolumns in JSON column.
Syntax
sql
JSONDynamicPaths(json)
Arguments
json
β JSON column.
JSON
Returned value
Returns an array of dynamic paths in the JSON column.
Array(String)
Examples
Usage example
sql title=Query
CREATE TABLE test (json JSON(max_dynamic_paths=1)) ENGINE = Memory;
INSERT INTO test FORMAT JSONEachRow {"json" : {"a" : 42}}, {"json" : {"b" : "Hello"}}, {"json" : {"a" : [1, 2, 3], "c" : "2020-01-01"}}
SELECT json, JSONDynamicPaths(json) FROM test;
response title=Response
ββjsonββββββββββββββββββββββββββββββββββ¬βJSONDynamicPaths(json)ββ
β {"a":"42"} β ['a'] β
β {"b":"Hello"} β [] β
β {"a":["1","2","3"],"c":"2020-01-01"} β ['a'] β
ββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββ
JSONDynamicPathsWithTypes {#JSONDynamicPathsWithTypes}
Introduced in: v24.8 | {"source_file": "json-functions.md"} | [
0.020696628838777542,
-0.01759178936481476,
0.041409920901060104,
0.06085548922419548,
-0.0803975760936737,
-0.00593690387904644,
-0.03679423779249191,
0.0163527000695467,
-0.037877462804317474,
-0.017712263390421867,
0.016058476641774178,
0.008679434657096863,
-0.03311695531010628,
0.0602... |
f0ec51ad-d202-4e90-8635-c42089949528 | JSONDynamicPathsWithTypes {#JSONDynamicPathsWithTypes}
Introduced in: v24.8
Returns the list of dynamic paths that are stored as separate subcolumns and their types in each row in JSON column.
Syntax
sql
JSONDynamicPathsWithTypes(json)
Arguments
json
β JSON column.
JSON
Returned value
Returns a map of dynamic paths and their data types in the JSON column.
Map(String, String)
Examples
Usage example
sql title=Query
CREATE TABLE test (json JSON(max_dynamic_paths=1)) ENGINE = Memory;
INSERT INTO test FORMAT JSONEachRow {"json" : {"a" : 42}}, {"json" : {"b" : "Hello"}}, {"json" : {"a" : [1, 2, 3], "c" : "2020-01-01"}}
SELECT json, JSONDynamicPathsWithTypes(json) FROM test;
response title=Response
ββjsonββββββββββββββββββββββββββββββββββ¬βJSONDynamicPathsWithTypes(json)ββ
β {"a":"42"} β {'a':'Int64'} β
β {"b":"Hello"} β {} β
β {"a":["1","2","3"],"c":"2020-01-01"} β {'a':'Array(Nullable(Int64))'} β
ββββββββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββ
JSONExtract {#JSONExtract}
Introduced in: v19.14
Parses JSON and extracts a value with given ClickHouse data type.
Syntax
sql
JSONExtract(json, return_type[, indices_or_keys, ...])
Arguments
json
β JSON string to parse.
String
return_type
β ClickHouse data type to return.
String
indices_or_keys
β A list of zero or more arguments each of which can be either string or integer.
String
or
(U)Int*
Returned value
Returns a value of specified ClickHouse data type if possible, otherwise returns the default value for that type.
Examples
Usage example
sql title=Query
SELECT JSONExtract('{"a": "hello", "b": [-100, 200.0, 300]}', 'Tuple(String, Array(Float64))') AS res;
response title=Response
ββresβββββββββββββββββββββββββββββββ
β ('hello',[-100,200,300]) β
ββββββββββββββββββββββββββββββββββββ
JSONExtractArrayRaw {#JSONExtractArrayRaw}
Introduced in: v20.1
Returns an array with elements of JSON array, each represented as unparsed string.
Syntax
sql
JSONExtractArrayRaw(json[, indices_or_keys, ...])
Arguments
json
β JSON string to parse.
String
indices_or_keys
β A list of zero or more arguments each of which can be either string or integer.
String
or
(U)Int*
Returned value
Returns an array of strings with JSON array elements. If the part is not an array or does not exist, an empty array will be returned.
Array(String)
Examples
Usage example
sql title=Query
SELECT JSONExtractArrayRaw('{"a": "hello", "b": [-100, 200.0, "hello"]}', 'b') AS res;
response title=Response
ββresβββββββββββββββββββββββββββ
β ['-100','200.0','"hello"'] β
ββββββββββββββββββββββββββββββββ
JSONExtractArrayRawCaseInsensitive {#JSONExtractArrayRawCaseInsensitive}
Introduced in: v25.8 | {"source_file": "json-functions.md"} | [
0.01149396225810051,
-0.01891183853149414,
0.04246492311358452,
0.06296315789222717,
-0.09565231204032898,
-0.0026270104572176933,
-0.04977522790431976,
0.012149871326982975,
-0.03861216455698013,
-0.030887838453054428,
0.022973408922553062,
-0.020572131499648094,
-0.020518597215414047,
0.... |
2a51d924-87d4-479d-8ab8-5d6c13cc04bd | JSONExtractArrayRawCaseInsensitive {#JSONExtractArrayRawCaseInsensitive}
Introduced in: v25.8
Returns an array with elements of JSON array, each represented as unparsed string, using case-insensitive key matching. This function is similar to
JSONExtractArrayRaw
.
Syntax
sql
JSONExtractArrayRawCaseInsensitive(json [, indices_or_keys]...)
Arguments
json
β JSON string to parse
String
indices_or_keys
β Optional. Indices or keys to navigate to the array. Keys use case-insensitive matching
String
or
(U)Int*
Returned value
Returns an array of raw JSON strings.
Array(String)
Examples
basic
sql title=Query
SELECT JSONExtractArrayRawCaseInsensitive('{"Items": [1, 2, 3]}', 'ITEMS')
response title=Response
['1','2','3']
JSONExtractBool {#JSONExtractBool}
Introduced in: v20.1
Parses JSON and extracts a value of Bool type.
Syntax
sql
JSONExtractBool(json[, indices_or_keys, ...])
Arguments
json
β JSON string to parse.
String
indices_or_keys
β A list of zero or more arguments each of which can be either string or integer.
String
or
(U)Int*
Returned value
Returns a Bool value if it exists, otherwise returns
0
.
Bool
Examples
Usage example
sql title=Query
SELECT JSONExtractBool('{"passed": true}', 'passed') AS res;
response title=Response
ββresββ
β 1 β
βββββββ
JSONExtractBoolCaseInsensitive {#JSONExtractBoolCaseInsensitive}
Introduced in: v25.8
Parses JSON and extracts a boolean value using case-insensitive key matching. This function is similar to
JSONExtractBool
.
Syntax
sql
JSONExtractBoolCaseInsensitive(json [, indices_or_keys]...)
Arguments
json
β JSON string to parse
String
indices_or_keys
β Optional. Indices or keys to navigate to the field. Keys use case-insensitive matching
String
or
(U)Int*
Returned value
Returns the extracted boolean value (1 for true, 0 for false), 0 if not found.
UInt8
Examples
basic
sql title=Query
SELECT JSONExtractBoolCaseInsensitive('{"IsActive": true}', 'isactive')
response title=Response
1
JSONExtractCaseInsensitive {#JSONExtractCaseInsensitive}
Introduced in: v25.8
Parses JSON and extracts a value of the given ClickHouse data type using case-insensitive key matching. This function is similar to
JSONExtract
.
Syntax
sql
JSONExtractCaseInsensitive(json [, indices_or_keys...], return_type)
Arguments
json
β JSON string to parse
String
indices_or_keys
β Optional. Indices or keys to navigate to the field. Keys use case-insensitive matching
String
or
(U)Int*
return_type
β The ClickHouse data type to extract
String
Returned value
Returns the extracted value in the specified data type.
Any
Examples
int_type
sql title=Query
SELECT JSONExtractCaseInsensitive('{"Number": 123}', 'number', 'Int32')
response title=Response
123
array_type
sql title=Query
SELECT JSONExtractCaseInsensitive('{"List": [1, 2, 3]}', 'list', 'Array(Int32)')
response title=Response
[1,2,3] | {"source_file": "json-functions.md"} | [
0.019895270466804504,
0.013644673861563206,
0.006030367687344551,
0.02573857456445694,
-0.07193788141012192,
-0.04318000748753548,
0.05603222921490669,
-0.03577817231416702,
-0.05127879977226257,
-0.050145942717790604,
-0.015404889360070229,
-0.007942832075059414,
0.025586020201444626,
0.0... |
cc2ed5a1-c3c1-400c-9923-7f5b91018df3 | response title=Response
123
array_type
sql title=Query
SELECT JSONExtractCaseInsensitive('{"List": [1, 2, 3]}', 'list', 'Array(Int32)')
response title=Response
[1,2,3]
JSONExtractFloat {#JSONExtractFloat}
Introduced in: v20.1
Parses JSON and extracts a value of Float type.
Syntax
sql
JSONExtractFloat(json[, indices_or_keys, ...])
Arguments
json
β JSON string to parse.
String
indices_or_keys
β A list of zero or more arguments each of which can be either string or integer.
String
or
(U)Int*
Returned value
Returns a Float value if it exists, otherwise returns
0
.
Float64
Examples
Usage example
sql title=Query
SELECT JSONExtractFloat('{"a": "hello", "b": [-100, 200.0, 300]}', 'b', 2) AS res;
response title=Response
ββresββ
β 200 β
βββββββ
JSONExtractFloatCaseInsensitive {#JSONExtractFloatCaseInsensitive}
Introduced in: v25.8
Parses JSON and extracts a value of Float type using case-insensitive key matching. This function is similar to
JSONExtractFloat
.
Syntax
sql
JSONExtractFloatCaseInsensitive(json [, indices_or_keys]...)
Arguments
json
β JSON string to parse
String
indices_or_keys
β Optional. Indices or keys to navigate to the field. Keys use case-insensitive matching
String
or
(U)Int*
Returned value
Returns the extracted Float value, 0 if not found or cannot be converted.
Float64
Examples
basic
sql title=Query
SELECT JSONExtractFloatCaseInsensitive('{"Price": 12.34}', 'PRICE')
response title=Response
12.34
JSONExtractInt {#JSONExtractInt}
Introduced in: v20.1
Parses JSON and extracts a value of Int type.
Syntax
sql
JSONExtractInt(json[, indices_or_keys, ...])
Arguments
json
β JSON string to parse.
String
indices_or_keys
β A list of zero or more arguments each of which can be either string or integer.
String
or
(U)Int*
Returned value
Returns an Int value if it exists, otherwise returns
0
.
Int64
Examples
Usage example
sql title=Query
SELECT JSONExtractInt('{"a": "hello", "b": [-100, 200.0, 300]}', 'b', 1) AS res;
response title=Response
ββresββ
β 200 β
βββββββ
JSONExtractIntCaseInsensitive {#JSONExtractIntCaseInsensitive}
Introduced in: v25.8
Parses JSON and extracts a value of Int type using case-insensitive key matching. This function is similar to
JSONExtractInt
.
Syntax
sql
JSONExtractIntCaseInsensitive(json [, indices_or_keys]...)
Arguments
json
β JSON string to parse
String
indices_or_keys
β Optional. Indices or keys to navigate to the field. Keys use case-insensitive matching
String
or
(U)Int*
Returned value
Returns the extracted Int value, 0 if not found or cannot be converted.
Int64
Examples
basic
sql title=Query
SELECT JSONExtractIntCaseInsensitive('{"Value": 123}', 'value')
response title=Response
123
nested
sql title=Query
SELECT JSONExtractIntCaseInsensitive('{"DATA": {"COUNT": 42}}', 'data', 'Count')
response title=Response
42 | {"source_file": "json-functions.md"} | [
-0.00156906817574054,
0.054262612015008926,
-0.004288982134312391,
0.032675229012966156,
-0.046205054968595505,
-0.0453639030456543,
0.09649836272001266,
0.0280435923486948,
-0.03847789019346237,
-0.04828817769885063,
-0.009510677307844162,
-0.08606623858213425,
-0.0017495248466730118,
0.0... |
a84a136c-8667-4850-b032-c3a9b1a354a7 | response title=Response
123
nested
sql title=Query
SELECT JSONExtractIntCaseInsensitive('{"DATA": {"COUNT": 42}}', 'data', 'Count')
response title=Response
42
JSONExtractKeys {#JSONExtractKeys}
Introduced in: v21.11
Parses a JSON string and extracts the keys.
Syntax
sql
JSONExtractKeys(json[, indices_or_keys, ...])
Arguments
json
β JSON string to parse.
String
indices_or_keys
β A list of zero or more arguments each of which can be either string or integer.
String
or
(U)Int*
Returned value
Returns an array with the keys of the JSON object.
Array(String)
Examples
Usage example
sql title=Query
SELECT JSONExtractKeys('{"a": "hello", "b": [-100, 200.0, 300]}') AS res;
response title=Response
ββresββββββββββ
β ['a','b'] β
βββββββββββββββ
JSONExtractKeysAndValues {#JSONExtractKeysAndValues}
Introduced in: v20.1
Parses key-value pairs from a JSON where the values are of the given ClickHouse data type.
Syntax
sql
JSONExtractKeysAndValues(json, value_type[, indices_or_keys, ...])
Arguments
json
β JSON string to parse.
String
value_type
β ClickHouse data type of the values.
String
indices_or_keys
β A list of zero or more arguments each of which can be either string or integer.
String
or
(U)Int*
Returned value
Returns an array of tuples with the parsed key-value pairs.
Array(Tuple(String, value_type))
Examples
Usage example
sql title=Query
SELECT JSONExtractKeysAndValues('{"x": {"a": 5, "b": 7, "c": 11}}', 'Int8', 'x') AS res;
response title=Response
ββresβββββββββββββββββββββ
β [('a',5),('b',7),('c',11)] β
ββββββββββββββββββββββββββ
JSONExtractKeysAndValuesCaseInsensitive {#JSONExtractKeysAndValuesCaseInsensitive}
Introduced in: v25.8
Parses key-value pairs from JSON using case-insensitive key matching. This function is similar to
JSONExtractKeysAndValues
.
Syntax
sql
JSONExtractKeysAndValuesCaseInsensitive(json [, indices_or_keys...], value_type)
Arguments
json
β JSON string to parse
String
indices_or_keys
β Optional. Indices or keys to navigate to the object. Keys use case-insensitive matching
String
or
(U)Int*
value_type
β The ClickHouse data type of the values
String
Returned value
Returns an array of tuples containing key-value pairs.
Array(Tuple(String, T))
Examples
basic
sql title=Query
SELECT JSONExtractKeysAndValuesCaseInsensitive('{"Name": "Alice", "AGE": 30}', 'String')
response title=Response
[('Name','Alice'),('AGE','30')]
JSONExtractKeysAndValuesRaw {#JSONExtractKeysAndValuesRaw}
Introduced in: v20.4
Returns an array of tuples with keys and values from a JSON object. All values are represented as unparsed strings.
Syntax
sql
JSONExtractKeysAndValuesRaw(json[, indices_or_keys, ...])
Arguments
json
β JSON string to parse.
String
indices_or_keys
β A list of zero or more arguments each of which can be either string or integer.
String
or
(U)Int*
Returned value | {"source_file": "json-functions.md"} | [
0.00007005590305197984,
0.03546833246946335,
0.029581943526864052,
0.024232909083366394,
-0.11062260717153549,
-0.021895699203014374,
0.05437019094824791,
0.02489471063017845,
0.005869484972208738,
-0.06251818686723709,
0.022631177678704262,
-0.0004008839896414429,
0.06406236439943314,
-0.... |
91209145-1bff-408e-94d7-b2b11cafabb6 | Arguments
json
β JSON string to parse.
String
indices_or_keys
β A list of zero or more arguments each of which can be either string or integer.
String
or
(U)Int*
Returned value
Returns an array of tuples with parsed key-value pairs where values are unparsed strings.
Array(Tuple(String, String))
Examples
Usage example
sql title=Query
SELECT JSONExtractKeysAndValuesRaw('{"a": [-100, 200.0], "b": "hello"}') AS res;
response title=Response
ββresβββββββββββββββββββββββββββββββββββ
β [('a','[-100,200.0]'),('b','"hello"')] β
ββββββββββββββββββββββββββββββββββββββββ
JSONExtractKeysAndValuesRawCaseInsensitive {#JSONExtractKeysAndValuesRawCaseInsensitive}
Introduced in: v25.8
Extracts raw key-value pairs from JSON using case-insensitive key matching. This function is similar to
JSONExtractKeysAndValuesRaw
.
Syntax
sql
JSONExtractKeysAndValuesRawCaseInsensitive(json [, indices_or_keys]...)
Arguments
json
β JSON string to parse
String
indices_or_keys
β Optional. Indices or keys to navigate to the object. Keys use case-insensitive matching
String
or
(U)Int*
Returned value
Returns an array of tuples containing key-value pairs as raw strings.
Array(Tuple(String, String))
Examples
basic
sql title=Query
SELECT JSONExtractKeysAndValuesRawCaseInsensitive('{"Name": "Alice", "AGE": 30}')
response title=Response
[('Name','"Alice"'),('AGE','30')]
JSONExtractKeysCaseInsensitive {#JSONExtractKeysCaseInsensitive}
Introduced in: v25.8
Parses a JSON string and extracts the keys using case-insensitive key matching to navigate to nested objects. This function is similar to
JSONExtractKeys
.
Syntax
sql
JSONExtractKeysCaseInsensitive(json [, indices_or_keys]...)
Arguments
json
β JSON string to parse
String
indices_or_keys
β Optional. Indices or keys to navigate to the object. Keys use case-insensitive matching
String
or
(U)Int*
Returned value
Returns an array of keys from the JSON object.
Array(String)
Examples
basic
sql title=Query
SELECT JSONExtractKeysCaseInsensitive('{"Name": "Alice", "AGE": 30}')
response title=Response
['Name','AGE']
nested
sql title=Query
SELECT JSONExtractKeysCaseInsensitive('{"User": {"name": "John", "AGE": 25}}', 'user')
response title=Response
['name','AGE']
JSONExtractRaw {#JSONExtractRaw}
Introduced in: v20.1
Returns a part of JSON as unparsed string.
Syntax
sql
JSONExtractRaw(json[, indices_or_keys, ...])
Arguments
json
β JSON string to parse.
String
indices_or_keys
β A list of zero or more arguments each of which can be either string or integer.
String
or
(U)Int*
Returned value
Returns the part of JSON as an unparsed string. If the part does not exist or has a wrong type, an empty string will be returned.
String
Examples
Usage example
sql title=Query
SELECT JSONExtractRaw('{"a": "hello", "b": [-100, 200.0, 300]}', 'b') AS res; | {"source_file": "json-functions.md"} | [
-0.008119462989270687,
0.06007228046655655,
0.005510185845196247,
0.006716901436448097,
-0.07790334522724152,
-0.0308331660926342,
0.05004703626036644,
0.005876477342098951,
-0.030153600499033928,
-0.06615598499774933,
0.00835954025387764,
-0.011738771572709084,
0.038239315152168274,
-0.02... |
3f8492a1-f11b-4c0a-b81d-9d3b16f9af8f | Examples
Usage example
sql title=Query
SELECT JSONExtractRaw('{"a": "hello", "b": [-100, 200.0, 300]}', 'b') AS res;
response title=Response
ββresβββββββββββββββ
β [-100,200.0,300] β
ββββββββββββββββββββ
JSONExtractRawCaseInsensitive {#JSONExtractRawCaseInsensitive}
Introduced in: v25.8
Returns part of the JSON as an unparsed string using case-insensitive key matching. This function is similar to
JSONExtractRaw
.
Syntax
sql
JSONExtractRawCaseInsensitive(json [, indices_or_keys]...)
Arguments
json
β JSON string to parse
String
indices_or_keys
β Optional. Indices or keys to navigate to the field. Keys use case-insensitive matching
String
or
(U)Int*
Returned value
Returns the raw JSON string of the extracted element.
String
Examples
object
sql title=Query
SELECT JSONExtractRawCaseInsensitive('{"Object": {"key": "value"}}', 'OBJECT')
response title=Response
{"key":"value"}
JSONExtractString {#JSONExtractString}
Introduced in: v20.1
Parses JSON and extracts a value of String type.
Syntax
sql
JSONExtractString(json[, indices_or_keys, ...])
Arguments
json
β JSON string to parse.
String
indices_or_keys
β A list of zero or more arguments each of which can be either string or integer.
String
or
(U)Int*
Returned value
Returns a String value if it exists, otherwise returns an empty string.
String
Examples
Usage example
sql title=Query
SELECT JSONExtractString('{"a": "hello", "b": [-100, 200.0, 300]}', 'a') AS res;
response title=Response
ββresββββ
β hello β
βββββββββ
JSONExtractStringCaseInsensitive {#JSONExtractStringCaseInsensitive}
Introduced in: v25.8
Parses JSON and extracts a string using case-insensitive key matching. This function is similar to
JSONExtractString
.
Syntax
sql
JSONExtractStringCaseInsensitive(json [, indices_or_keys]...)
Arguments
json
β JSON string to parse
String
indices_or_keys
β Optional. Indices or keys to navigate to the field. Keys use case-insensitive matching
String
or
(U)Int*
Returned value
Returns the extracted string value, empty string if not found.
String
Examples
basic
sql title=Query
SELECT JSONExtractStringCaseInsensitive('{"ABC": "def"}', 'abc')
response title=Response
def
nested
sql title=Query
SELECT JSONExtractStringCaseInsensitive('{"User": {"Name": "John"}}', 'user', 'name')
response title=Response
John
JSONExtractUInt {#JSONExtractUInt}
Introduced in: v20.1
Parses JSON and extracts a value of UInt type.
Syntax
sql
JSONExtractUInt(json [, indices_or_keys, ...])
Arguments
json
β JSON string to parse.
String
indices_or_keys
β A list of zero or more arguments each of which can be either string or integer.
String
or
(U)Int*
Returned value
Returns a UInt value if it exists, otherwise returns
0
.
UInt64
Examples
Usage example
sql title=Query
SELECT JSONExtractUInt('{"a": "hello", "b": [-100, 200.0, 300]}', 'b', -1) AS res; | {"source_file": "json-functions.md"} | [
-0.01686728186905384,
0.05920249596238136,
0.030114002525806427,
0.0474851168692112,
-0.0624091662466526,
-0.038188934326171875,
0.0434306375682354,
0.03701462596654892,
-0.032637231051921844,
-0.04114706814289093,
-0.021825013682246208,
-0.04082394018769264,
0.037089210003614426,
0.031100... |
5fdbb5d9-6ed3-45d9-a243-90fd8a886b45 | Returns a UInt value if it exists, otherwise returns
0
.
UInt64
Examples
Usage example
sql title=Query
SELECT JSONExtractUInt('{"a": "hello", "b": [-100, 200.0, 300]}', 'b', -1) AS res;
response title=Response
ββresββ
β 300 β
βββββββ
JSONExtractUIntCaseInsensitive {#JSONExtractUIntCaseInsensitive}
Introduced in: v25.8
Parses JSON and extracts a value of UInt type using case-insensitive key matching. This function is similar to
JSONExtractUInt
.
Syntax
sql
JSONExtractUIntCaseInsensitive(json [, indices_or_keys]...)
Arguments
json
β JSON string to parse
String
indices_or_keys
β Optional. Indices or keys to navigate to the field. Keys use case-insensitive matching
String
or
(U)Int*
Returned value
Returns the extracted UInt value, 0 if not found or cannot be converted.
UInt64
Examples
basic
sql title=Query
SELECT JSONExtractUIntCaseInsensitive('{"COUNT": 789}', 'count')
response title=Response
789
JSONHas {#JSONHas}
Introduced in: v20.1
Checks for the existence of the provided value(s) in the JSON document.
Syntax
sql
JSONHas(json[ ,indices_or_keys, ...])
Arguments
json
β JSON string to parse
String
[ ,indices_or_keys, ...]
β A list of zero or more arguments.
String
or
(U)Int*
Returned value
Returns
1
if the value exists in
json
, otherwise
0
UInt8
Examples
Usage example
sql title=Query
SELECT JSONHas('{"a": "hello", "b": [-100, 200.0, 300]}', 'b') = 1;
SELECT JSONHas('{"a": "hello", "b": [-100, 200.0, 300]}', 'b', 4) = 0;
response title=Response
1
0
JSONLength {#JSONLength}
Introduced in: v20.1
Return the length of a JSON array or a JSON object.
If the value does not exist or has the wrong type,
0
will be returned.
Syntax
sql
JSONLength(json [, indices_or_keys, ...])
Arguments
json
β JSON string to parse
String
[, indices_or_keys, ...]
β Optional. A list of zero or more arguments.
String
or
(U)Int8/16/32/64
Returned value
Returns the length of the JSON array or JSON object, otherwise returns
0
if the value does not exist or has the wrong type.
UInt64
Examples
Usage example
sql title=Query
SELECT JSONLength('{"a": "hello", "b": [-100, 200.0, 300]}', 'b') = 3;
SELECT JSONLength('{"a": "hello", "b": [-100, 200.0, 300]}') = 2;
response title=Response
1
1
JSONMergePatch {#JSONMergePatch}
Introduced in: v23.10
Returns the merged JSON object string which is formed by merging multiple JSON objects.
Syntax
sql
jsonMergePatch(json1[, json2, ...])
Aliases
:
jsonMergePatch
Arguments
json1[, json2, ...]
β One or more strings with valid JSON.
String
Returned value
Returns the merged JSON object string, if the JSON object strings are valid.
String
Examples
Usage example
sql title=Query
SELECT jsonMergePatch('{"a":1}', '{"name": "joey"}', '{"name": "tom"}', '{"name": "zoey"}') AS res;
response title=Response
ββresββββββββββββββββββββ
β {"a":1,"name":"zoey"} β
βββββββββββββββββββββββββ | {"source_file": "json-functions.md"} | [
-0.022876281291246414,
0.03912338614463806,
-0.0013780088629573584,
0.03619023412466049,
-0.08243948221206665,
-0.03133546933531761,
0.04008011147379875,
0.02603774145245552,
-0.017265353351831436,
-0.06935770809650421,
0.040015920996665955,
-0.0727870762348175,
0.03525201231241226,
0.0048... |
4deea189-b428-4f9c-b8fa-3b66e5818355 | response title=Response
ββresββββββββββββββββββββ
β {"a":1,"name":"zoey"} β
βββββββββββββββββββββββββ
JSONSharedDataPaths {#JSONSharedDataPaths}
Introduced in: v24.8
Returns the list of paths that are stored in shared data structure in JSON column.
Syntax
sql
JSONSharedDataPaths(json)
Arguments
json
β JSON column.
JSON
Returned value
Returns an array of paths stored in shared data structure in the JSON column.
Array(String)
Examples
Usage example
sql title=Query
CREATE TABLE test (json JSON(max_dynamic_paths=1)) ENGINE = Memory;
INSERT INTO test FORMAT JSONEachRow {"json" : {"a" : 42}}, {"json" : {"b" : "Hello"}}, {"json" : {"a" : [1, 2, 3], "c" : "2020-01-01"}}
SELECT json, JSONSharedDataPaths(json) FROM test;
response title=Response
ββjsonββββββββββββββββββββββββββββββββββ¬βJSONSharedDataPaths(json)ββ
β {"a":"42"} β [] β
β {"b":"Hello"} β ['b'] β
β {"a":["1","2","3"],"c":"2020-01-01"} β ['c'] β
ββββββββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββ
JSONSharedDataPathsWithTypes {#JSONSharedDataPathsWithTypes}
Introduced in: v24.8
Returns the list of paths that are stored in shared data structure and their types in each row in JSON column.
Syntax
sql
JSONSharedDataPathsWithTypes(json)
Arguments
json
β JSON column.
JSON
Returned value
Returns a map of paths stored in shared data structure and their data types in the JSON column.
Map(String, String)
Examples
Usage example
sql title=Query
CREATE TABLE test (json JSON(max_dynamic_paths=1)) ENGINE = Memory;
INSERT INTO test FORMAT JSONEachRow {"json" : {"a" : 42}}, {"json" : {"b" : "Hello"}}, {"json" : {"a" : [1, 2, 3], "c" : "2020-01-01"}}
SELECT json, JSONSharedDataPathsWithTypes(json) FROM test;
response title=Response
ββjsonββββββββββββββββββββββββββββββββββ¬βJSONSharedDataPathsWithTypes(json)ββ
β {"a":"42"} β {} β
β {"b":"Hello"} β {'b':'String'} β
β {"a":["1","2","3"],"c":"2020-01-01"} β {'c':'Date'} β
ββββββββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββ
JSONType {#JSONType}
Introduced in: v20.1
Return the type of a JSON value. If the value does not exist,
Null=0
will be returned.
Syntax
sql
JSONType(json[, indices_or_keys, ...])
Arguments
json
β JSON string to parse
String
json[, indices_or_keys, ...]
β A list of zero or more arguments, each of which can be either string or integer.
String
or
(U)Int8/16/32/64
Returned value
Returns the type of a JSON value as a string, otherwise if the value doesn't exist it returns
Null=0
Enum
Examples
Usage example | {"source_file": "json-functions.md"} | [
0.0014574667438864708,
-0.010046589188277721,
0.008241458795964718,
0.07563621550798416,
-0.09175442904233932,
-0.01468564197421074,
-0.03210015594959259,
0.009201445616781712,
-0.009203780442476273,
-0.020689064636826515,
0.02260446362197399,
-0.0008841096423566341,
0.01691964454948902,
0... |
41504b27-f4b9-428b-919c-b9dbaaecec76 | Returned value
Returns the type of a JSON value as a string, otherwise if the value doesn't exist it returns
Null=0
Enum
Examples
Usage example
sql title=Query
SELECT JSONType('{"a": "hello", "b": [-100, 200.0, 300]}') = 'Object';
SELECT JSONType('{"a": "hello", "b": [-100, 200.0, 300]}', 'a') = 'String';
SELECT JSONType('{"a": "hello", "b": [-100, 200.0, 300]}', 'b') = 'Array';
response title=Response
1
1
1
JSON_EXISTS {#JSON_EXISTS}
Introduced in: v21.8
If the value exists in the JSON document,
1
will be returned.
If the value does not exist,
0
will be returned.
Syntax
sql
JSON_EXISTS(json, path)
Arguments
json
β A string with valid JSON.
String
path
β A string representing the path.
String
Returned value
Returns
1
if the value exists in the JSON document, otherwise
0
.
UInt8
Examples
Usage example
sql title=Query
SELECT JSON_EXISTS('{"hello":1}', '$.hello');
SELECT JSON_EXISTS('{"hello":{"world":1}}', '$.hello.world');
SELECT JSON_EXISTS('{"hello":["world"]}', '$.hello[*]');
SELECT JSON_EXISTS('{"hello":["world"]}', '$.hello[0]');
response title=Response
ββJSON_EXISTS(β― '$.hello')ββ
β 1 β
ββββββββββββββββββββββββββββ
ββJSON_EXISTS(β―llo.world')ββ
β 1 β
ββββββββββββββββββββββββββββ
ββJSON_EXISTS(β―.hello[*]')ββ
β 1 β
ββββββββββββββββββββββββββββ
ββJSON_EXISTS(β―.hello[0]')ββ
β 1 β
ββββββββββββββββββββββββββββ
JSON_QUERY {#JSON_QUERY}
Introduced in: v21.8
Parses a JSON and extract a value as a JSON array or JSON object.
If the value does not exist, an empty string will be returned.
Syntax
sql
JSON_QUERY(json, path)
Arguments
json
β A string with valid JSON.
String
path
β A string representing the path.
String
Returned value
Returns the extracted JSON array or JSON object as a string, or an empty string if the value does not exist.
String
Examples
Usage example
sql title=Query
SELECT JSON_QUERY('{"hello":"world"}', '$.hello');
SELECT JSON_QUERY('{"array":[[0, 1, 2, 3, 4, 5], [0, -1, -2, -3, -4, -5]]}', '$.array[*][0 to 2, 4]');
SELECT JSON_QUERY('{"hello":2}', '$.hello');
SELECT toTypeName(JSON_QUERY('{"hello":2}', '$.hello'));
response title=Response
["world"]
[0, 1, 4, 0, -1, -4]
[2]
String
JSON_VALUE {#JSON_VALUE}
Introduced in: v21.11
Parses a JSON and extract a value as a JSON scalar. If the value does not exist, an empty string will be returned by default.
This function is controlled by the following settings:
- by SET
function_json_value_return_type_allow_nullable
=
true
,
NULL
will be returned. If the value is complex type (such as: struct, array, map), an empty string will be returned by default.
- by SET
function_json_value_return_type_allow_complex
=
true
, the complex value will be returned.
Syntax
sql
JSON_VALUE(json, path)
Arguments
json
β A string with valid JSON.
String
path
β A string representing the path.
String | {"source_file": "json-functions.md"} | [
-0.02358173578977585,
-0.0030703935772180557,
-0.005794175900518894,
0.013263637199997902,
-0.07261928170919418,
-0.04540321230888367,
0.019832322373986244,
0.022517366334795952,
0.010466599836945534,
-0.0623907595872879,
0.05186204984784126,
-0.04639586806297302,
0.0034543336369097233,
0.... |
5715baf1-2b96-4100-8817-ade5ef1ae2b8 | Syntax
sql
JSON_VALUE(json, path)
Arguments
json
β A string with valid JSON.
String
path
β A string representing the path.
String
Returned value
Returns the extracted JSON scalar as a string, or an empty string if the value does not exist.
String
Examples
Usage example
sql title=Query
SELECT JSON_VALUE('{"hello":"world"}', '$.hello');
SELECT JSON_VALUE('{"array":[[0, 1, 2, 3, 4, 5], [0, -1, -2, -3, -4, -5]]}', '$.array[*][0 to 2, 4]');
SELECT JSON_VALUE('{"hello":2}', '$.hello');
SELECT JSON_VALUE('{"hello":"world"}', '$.b') settings function_json_value_return_type_allow_nullable=true;
response title=Response
world
0
2
α΄Ία΅α΄Έα΄Έ
dynamicElement {#dynamicElement}
Introduced in: v24.1
Extracts a column with specified type from a
Dynamic
column.
This function allows you to extract values of a specific type from a Dynamic column. If a row contains a value
of the requested type, it returns that value. If the row contains a different type or NULL, it returns NULL
for scalar types or an empty array for array types.
Syntax
sql
dynamicElement(dynamic, type_name)
Arguments
dynamic
β Dynamic column to extract from.
Dynamic
type_name
β The name of the variant type to extract (e.g., 'String', 'Int64', 'Array(Int64)').
Returned value
Returns values of the specified type from the Dynamic column. Returns NULL for non-matching types (or empty array for array types).
Any
Examples
Extracting different types from Dynamic column
sql title=Query
CREATE TABLE test (d Dynamic) ENGINE = Memory;
INSERT INTO test VALUES (NULL), (42), ('Hello, World!'), ([1, 2, 3]);
SELECT d, dynamicType(d), dynamicElement(d, 'String'), dynamicElement(d, 'Int64'), dynamicElement(d, 'Array(Int64)'), dynamicElement(d, 'Date'), dynamicElement(d, 'Array(String)') FROM test | {"source_file": "json-functions.md"} | [
0.02102174237370491,
0.042351916432380676,
0.010788297280669212,
0.058091018348932266,
-0.07590038329362869,
-0.04034337028861046,
0.02702518180012703,
0.020525041967630386,
0.014147985726594925,
-0.08202805370092392,
0.008642164058983326,
-0.029643911868333817,
-0.0442788228392601,
0.0041... |
c9decf93-271c-455b-af21-87d0a15daecc | response title=Response
ββdββββββββββββββ¬βdynamicType(d)ββ¬βdynamicElement(d, 'String')ββ¬βdynamicElement(d, 'Int64')ββ¬βdynamicElement(d, 'Array(Int64)')ββ¬βdynamicElement(d, 'Date')ββ¬βdynamicElement(d, 'Array(String)')ββ
β α΄Ία΅α΄Έα΄Έ β None β α΄Ία΅α΄Έα΄Έ β α΄Ία΅α΄Έα΄Έ β [] β α΄Ία΅α΄Έα΄Έ β [] β
β 42 β Int64 β α΄Ία΅α΄Έα΄Έ β 42 β [] β α΄Ία΅α΄Έα΄Έ β [] β
β Hello, World! β String β Hello, World! β α΄Ία΅α΄Έα΄Έ β [] β α΄Ία΅α΄Έα΄Έ β [] β
β [1,2,3] β Array(Int64) β α΄Ία΅α΄Έα΄Έ β α΄Ία΅α΄Έα΄Έ β [1,2,3] β α΄Ία΅α΄Έα΄Έ β [] β
βββββββββββββββββ΄βββββββββββββββββ΄ββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββ
dynamicType {#dynamicType}
Introduced in: v24.1
Returns the variant type name for each row of a
Dynamic
column.
For rows containing NULL, the function returns 'None'. For all other rows, it returns the actual data type
stored in that row of the Dynamic column (e.g., 'Int64', 'String', 'Array(Int64)').
Syntax
sql
dynamicType(dynamic)
Arguments
dynamic
β Dynamic column to inspect.
Dynamic
Returned value
Returns the type name of the value stored in each row, or 'None' for NULL values.
String
Examples
Inspecting types in Dynamic column
sql title=Query
CREATE TABLE test (d Dynamic) ENGINE = Memory;
INSERT INTO test VALUES (NULL), (42), ('Hello, World!'), ([1, 2, 3]);
SELECT d, dynamicType(d) FROM test;
response title=Response
ββdββββββββββββββ¬βdynamicType(d)ββ
β α΄Ία΅α΄Έα΄Έ β None β
β 42 β Int64 β
β Hello, World! β String β
β [1,2,3] β Array(Int64) β
βββββββββββββββββ΄βββββββββββββββββ
isDynamicElementInSharedData {#isDynamicElementInSharedData}
Introduced in: v24.1
Returns true for rows in a Dynamic column that are stored in shared variant format rather than as separate subcolumns.
When a Dynamic column has a
max_types
limit, values that exceed this limit are stored in a shared binary format
instead of being separated into individual typed subcolumns. This function identifies which rows are stored in this shared format.
Syntax
sql
isDynamicElementInSharedData(dynamic)
Arguments
dynamic
β Dynamic column to inspect.
Dynamic
Returned value
Returns true if the value is stored in shared variant format, false if stored as a separate subcolumn or is NULL.
Bool
Examples
Checking storage format in Dynamic column with max_types limit | {"source_file": "json-functions.md"} | [
0.03755713254213333,
0.008738632313907146,
-0.016065793111920357,
0.09241428226232529,
-0.08021054416894913,
-0.0384586825966835,
0.0500776581466198,
0.025529300794005394,
-0.06742867082357407,
-0.016163822263479233,
0.005441389977931976,
-0.02323155850172043,
-0.02485743910074234,
-0.0399... |
101c9a9a-f409-4ed0-9e5b-9e39b57496e7 | Returns true if the value is stored in shared variant format, false if stored as a separate subcolumn or is NULL.
Bool
Examples
Checking storage format in Dynamic column with max_types limit
sql title=Query
CREATE TABLE test (d Dynamic(max_types=2)) ENGINE = Memory;
INSERT INTO test VALUES (NULL), (42), ('Hello, World!'), ([1, 2, 3]);
SELECT d, isDynamicElementInSharedData(d) FROM test;
response title=Response
ββdββββββββββββββ¬βisDynamicElementInSharedData(d)ββ
β α΄Ία΅α΄Έα΄Έ β false β
β 42 β false β
β Hello, World! β true β
β [1,2,3] β true β
βββββββββββββββββ΄ββββββββββββββββββββββββββββββββββ
isValidJSON {#isValidJSON}
Introduced in: v20.1
Checks that the string passed is valid JSON.
Syntax
sql
isValidJSON(json)
Arguments
json
β JSON string to validate
String
Returned value
Returns
1
if the string is valid JSON, otherwise
0
.
UInt8
Examples
Usage example
sql title=Query
SELECT isValidJSON('{"a": "hello", "b": [-100, 200.0, 300]}') = 1;
SELECT isValidJSON('not JSON') = 0;
response title=Response
1
0
Using integers to access both JSON arrays and JSON objects
sql title=Query
SELECT JSONHas('{"a": "hello", "b": [-100, 200.0, 300]}', 0);
SELECT JSONHas('{"a": "hello", "b": [-100, 200.0, 300]}', 1);
SELECT JSONHas('{"a": "hello", "b": [-100, 200.0, 300]}', 2);
SELECT JSONHas('{"a": "hello", "b": [-100, 200.0, 300]}', -1);
SELECT JSONHas('{"a": "hello", "b": [-100, 200.0, 300]}', -2);
SELECT JSONHas('{"a": "hello", "b": [-100, 200.0, 300]}', 3);
response title=Response
0
1
1
1
1
1
0
simpleJSONExtractBool {#simpleJSONExtractBool}
Introduced in: v21.4
Parses a true/false value from the value of the field named
field_name
.
The result is
UInt8
.
Syntax
sql
simpleJSONExtractBool(json, field_name)
Aliases
:
visitParamExtractBool
Arguments
json
β The JSON in which the field is searched for.
String
field_name
β The name of the field to search for.
const String
Returned value
Returns
1
if the value of the field is
true
,
0
otherwise. This means this function will return
0
including (and not only) in the following cases:
- If the field doesn't exists.
- If the field contains
true
as a string, e.g.:
{"field":"true"}
.
- If the field contains
1
as a numerical value.
UInt8
Examples
Usage example
``sql title=Query
CREATE TABLE jsons
(
json` String
)
ENGINE = MergeTree
ORDER BY tuple();
INSERT INTO jsons VALUES ('{"foo":false,"bar":true}');
INSERT INTO jsons VALUES ('{"foo":"true","qux":1}');
SELECT simpleJSONExtractBool(json, 'bar') FROM jsons ORDER BY json;
SELECT simpleJSONExtractBool(json, 'foo') FROM jsons ORDER BY json;
```
response title=Response
0
1
0
0
simpleJSONExtractFloat {#simpleJSONExtractFloat}
Introduced in: v21.4 | {"source_file": "json-functions.md"} | [
-0.009254737757146358,
0.016527336090803146,
-0.02383931167423725,
0.035886768251657486,
-0.06420782953500748,
-0.024179603904485703,
0.013912123627960682,
0.017611496150493622,
-0.006405623164027929,
-0.011427796445786953,
-0.0038807657547295094,
-0.04520934075117111,
-0.01610003225505352,
... |
eabe24ab-d6ac-4a8b-91ec-a850c381a2a2 | response title=Response
0
1
0
0
simpleJSONExtractFloat {#simpleJSONExtractFloat}
Introduced in: v21.4
Parses
Float64
from the value of the field named
field_name
.
If
field_name
is a string field, it tries to parse a number from the beginning of the string.
If the field does not exist, or it exists but does not contain a number, it returns
0
.
Syntax
sql
simpleJSONExtractFloat(json, field_name)
Aliases
:
visitParamExtractFloat
Arguments
json
β The JSON in which the field is searched for.
String
field_name
β The name of the field to search for.
const String
Returned value
Returns the number parsed from the field if the field exists and contains a number, otherwise
0
.
Float64
Examples
Usage example
``sql title=Query
CREATE TABLE jsons
(
json` String
)
ENGINE = MergeTree
ORDER BY tuple();
INSERT INTO jsons VALUES ('{"foo":"-4e3"}');
INSERT INTO jsons VALUES ('{"foo":-3.4}');
INSERT INTO jsons VALUES ('{"foo":5}');
INSERT INTO jsons VALUES ('{"foo":"not1number"}');
INSERT INTO jsons VALUES ('{"baz":2}');
SELECT simpleJSONExtractFloat(json, 'foo') FROM jsons ORDER BY json;
```
response title=Response
0
-4000
0
-3.4
5
simpleJSONExtractInt {#simpleJSONExtractInt}
Introduced in: v21.4
Parses
Int64
from the value of the field named
field_name
.
If
field_name
is a string field, it tries to parse a number from the beginning of the string.
If the field does not exist, or it exists but does not contain a number, it returns
0
.
Syntax
sql
simpleJSONExtractInt(json, field_name)
Aliases
:
visitParamExtractInt
Arguments
json
β The JSON in which the field is searched for.
String
field_name
β The name of the field to search for.
const String
Returned value
Returns the number parsed from the field if the field exists and contains a number,
0
otherwise
Int64
Examples
Usage example
``sql title=Query
CREATE TABLE jsons
(
json` String
)
ENGINE = MergeTree
ORDER BY tuple();
INSERT INTO jsons VALUES ('{"foo":"-4e3"}');
INSERT INTO jsons VALUES ('{"foo":-3.4}');
INSERT INTO jsons VALUES ('{"foo":5}');
INSERT INTO jsons VALUES ('{"foo":"not1number"}');
INSERT INTO jsons VALUES ('{"baz":2}');
SELECT simpleJSONExtractInt(json, 'foo') FROM jsons ORDER BY json;
```
response title=Response
0
-4
0
-3
5
simpleJSONExtractRaw {#simpleJSONExtractRaw}
Introduced in: v21.4
Returns the value of the field named
field_name
as a
String
, including separators.
Syntax
sql
simpleJSONExtractRaw(json, field_name)
Aliases
:
visitParamExtractRaw
Arguments
json
β The JSON in which the field is searched for.
String
field_name
β The name of the field to search for.
const String
Returned value
Returns the value of the field as a string, including separators if the field exists, or an empty string otherwise
String
Examples
Usage example
``sql title=Query
CREATE TABLE jsons
(
json` String
)
ENGINE = MergeTree
ORDER BY tuple(); | {"source_file": "json-functions.md"} | [
-0.04061532020568848,
0.05618120729923248,
0.01451276894658804,
0.023366082459688187,
-0.053910039365291595,
-0.03649713844060898,
0.024050865322351456,
0.1029166653752327,
0.02633272111415863,
-0.09761984646320343,
-0.016842694953083992,
-0.03674330189824104,
-0.017810285091400146,
0.0037... |
0ce34e53-4988-4f6d-8a8d-73612e03813b | Examples
Usage example
``sql title=Query
CREATE TABLE jsons
(
json` String
)
ENGINE = MergeTree
ORDER BY tuple();
INSERT INTO jsons VALUES ('{"foo":"-4e3"}');
INSERT INTO jsons VALUES ('{"foo":-3.4}');
INSERT INTO jsons VALUES ('{"foo":5}');
INSERT INTO jsons VALUES ('{"foo":{"def":[1,2,3]}}');
INSERT INTO jsons VALUES ('{"baz":2}');
SELECT simpleJSONExtractRaw(json, 'foo') FROM jsons ORDER BY json;
```
response title=Response
"-4e3"
-3.4
5
{"def":[1,2,3]}
simpleJSONExtractString {#simpleJSONExtractString}
Introduced in: v21.4
Parses
String
in double quotes from the value of the field named
field_name
.
Implementation details
There is currently no support for code points in the format
\uXXXX\uYYYY
that are not from the basic multilingual plane (they are converted to CESU-8 instead of UTF-8).
Syntax
sql
simpleJSONExtractString(json, field_name)
Aliases
:
visitParamExtractString
Arguments
json
β The JSON in which the field is searched for.
String
field_name
β The name of the field to search for.
const String
Returned value
Returns the unescaped value of a field as a string, including separators. An empty string is returned if the field doesn't contain a double quoted string, if unescaping fails or if the field doesn't exist
String
Examples
Usage example
``sql title=Query
CREATE TABLE jsons
(
json` String
)
ENGINE = MergeTree
ORDER BY tuple();
INSERT INTO jsons VALUES ('{"foo":"\n\u0000"}');
INSERT INTO jsons VALUES ('{"foo":"\u263"}');
INSERT INTO jsons VALUES ('{"foo":"\u263a"}');
INSERT INTO jsons VALUES ('{"foo":"hello}');
SELECT simpleJSONExtractString(json, 'foo') FROM jsons ORDER BY json;
```
```response title=Response
\n\0
βΊ
```
simpleJSONExtractUInt {#simpleJSONExtractUInt}
Introduced in: v21.4
Parses
UInt64
from the value of the field named
field_name
.
If
field_name
is a string field, it tries to parse a number from the beginning of the string.
If the field does not exist, or it exists but does not contain a number, it returns
0
.
Syntax
sql
simpleJSONExtractUInt(json, field_name)
Aliases
:
visitParamExtractUInt
Arguments
json
β The JSON in which the field is searched for.
String
field_name
β The name of the field to search for.
const String
Returned value
Returns the number parsed from the field if the field exists and contains a number,
0
otherwise
UInt64
Examples
Usage example
``sql title=Query
CREATE TABLE jsons
(
json` String
)
ENGINE = MergeTree
ORDER BY tuple();
INSERT INTO jsons VALUES ('{"foo":"4e3"}');
INSERT INTO jsons VALUES ('{"foo":3.4}');
INSERT INTO jsons VALUES ('{"foo":5}');
INSERT INTO jsons VALUES ('{"foo":"not1number"}');
INSERT INTO jsons VALUES ('{"baz":2}');
SELECT simpleJSONExtractUInt(json, 'foo') FROM jsons ORDER BY json;
```
response title=Response
0
4
0
3
5
simpleJSONHas {#simpleJSONHas}
Introduced in: v21.4
Checks whether there is a field named
field_name
.
Syntax | {"source_file": "json-functions.md"} | [
-0.04467713460326195,
0.00022497924510389566,
0.03834700956940651,
0.03820106014609337,
-0.0864584743976593,
0.009846089407801628,
-0.01886303909122944,
0.03883064538240433,
-0.0229096207767725,
-0.018784839659929276,
0.021024568006396294,
0.02087176777422428,
0.023630453273653984,
-0.0438... |
7668ea84-5405-4111-a6ce-10fb68d43ca1 | response title=Response
0
4
0
3
5
simpleJSONHas {#simpleJSONHas}
Introduced in: v21.4
Checks whether there is a field named
field_name
.
Syntax
sql
simpleJSONHas(json, field_name)
Aliases
:
visitParamHas
Arguments
json
β The JSON in which the field is searched for.
String
field_name
β The name of the field to search for.
const String
Returned value
Returns
1
if the field exists,
0
otherwise
UInt8
Examples
Usage example
``sql title=Query
CREATE TABLE jsons
(
json` String
)
ENGINE = MergeTree
ORDER BY tuple();
INSERT INTO jsons VALUES ('{"foo":"true","qux":1}');
SELECT simpleJSONHas(json, 'foo') FROM jsons;
SELECT simpleJSONHas(json, 'bar') FROM jsons;
```
response title=Response
1
0
toJSONString {#toJSONString}
Introduced in: v21.7
Serializes a value to its JSON representation. Various data types and nested structures are supported.
64-bit
integers
or bigger (like
UInt64
or
Int128
) are enclosed in quotes by default.
output_format_json_quote_64bit_integers
controls this behavior.
Special values
NaN
and
inf
are replaced with
null
. Enable
output_format_json_quote_denormals
setting to show them.
When serializing an
Enum
value, the function outputs its name.
See also:
-
output_format_json_quote_64bit_integers
-
output_format_json_quote_denormals
Syntax
sql
toJSONString(value)
Arguments
value
β Value to serialize. Value may be of any data type.
Any
Returned value
Returns the JSON representation of the value.
String
Examples
Map serialization
sql title=Query
SELECT toJSONString(map('key1', 1, 'key2', 2));
response title=Response
ββtoJSONString(map('key1', 1, 'key2', 2))ββ
β {"key1":1,"key2":2} β
βββββββββββββββββββββββββββββββββββββββββββ
Special values
sql title=Query
SELECT toJSONString(tuple(1.25, NULL, NaN, +inf, -inf, [])) SETTINGS output_format_json_quote_denormals = 1;
response title=Response
ββtoJSONString(tuple(1.25, NULL, NaN, plus(inf), minus(inf), []))ββ
β [1.25,null,"nan","inf","-inf",[]] β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | {"source_file": "json-functions.md"} | [
-0.04253186658024788,
0.06031905859708786,
0.014422256499528885,
0.008590146899223328,
-0.10034319758415222,
-0.02354859933257103,
-0.006791211199015379,
0.05235694348812103,
0.01297380868345499,
-0.043433286249637604,
0.010096787475049496,
0.005623929668217897,
-0.009389019571244717,
-0.0... |
2b575319-3d4a-485c-b803-3e22ec9b35ff | description: 'Documentation for functions used to work with URLs'
sidebar_label: 'URLs'
slug: /sql-reference/functions/url-functions
title: 'Functions for working with URLs'
doc_type: 'reference'
Functions for working with URLs
Overview {#overview}
:::note
The functions mentioned in this section are optimized for maximum performance and for the most part do not follow the RFC-3986 standard.
Functions which implement RFC-3986 have
RFC
appended to their function name and are generally slower.
:::
You can generally use the non-
RFC
function variants when working with publicly registered domains that contain neither user strings nor
@
symbols.
The table below details which symbols in a URL can (
β
) or cannot (
β
) be parsed by the respective
RFC
and non-
RFC
variants:
|Symbol | non-
RFC
|
RFC
|
|-------|----------|-------|
| ' ' | β |β |
| \t | β |β |
| < | β |β |
| > | β |β |
| % | β |β
|
| { | β |β |
| } | β |β |
| \| | β |β |
| \\ | β |β |
| ^ | β |β |
| ~ | β |β
|
| [ | β |β |
| ] | β |β |
| ; | β |β
|
| = | β |β
|
| & | β |β* |
symbols marked
*
are sub-delimiters in RFC 3986 and allowed for user info following the
@
symbol.
There are two types of URL functions:
- Functions that extract parts of a URL. If the relevant part isn't present in a URL, an empty string is returned.
- Functions that remove part of a URL. If the URL does not have anything similar, the URL remains unchanged.
:::note
The functions below are generated from the
system.functions
system table.
:::
cutFragment {#cutFragment}
Introduced in: v1.1
Removes the fragment identifier, including the number sign, from a URL.
Syntax
sql
cutFragment(url)
Arguments
url
β URL.
String
Returned value
Returns the URL with fragment identifier removed.
String
Examples
Usage example
sql title=Query
SELECT cutFragment('http://example.com/path?query=value#fragment123');
response title=Response
ββcutFragment('http://example.com/path?query=value#fragment123')ββ
β http://example.com/path?query=value β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
cutQueryString {#cutQueryString}
Introduced in: v1.1
Removes the query string, including the question mark from a URL.
Syntax
sql
cutQueryString(url)
Arguments
url
β URL.
String
Returned value
Returns the URL with query string removed.
String
Examples
Usage example
sql title=Query
SELECT cutQueryString('http://example.com/path?query=value¶m=123#fragment'); | {"source_file": "url-functions.md"} | [
-0.03542696312069893,
-0.025909239426255226,
0.02731914073228836,
-0.03280477970838547,
-0.037690021097660065,
-0.028341373428702354,
-0.018795419484376907,
0.018828146159648895,
0.03745308890938759,
-0.02482648380100727,
-0.03592609614133835,
-0.03733624890446663,
0.055261414498090744,
-0... |
8aa28888-36b5-42c3-9fe7-de4b9bc57c1a | Returned value
Returns the URL with query string removed.
String
Examples
Usage example
sql title=Query
SELECT cutQueryString('http://example.com/path?query=value¶m=123#fragment');
response title=Response
ββcutQueryString('http://example.com/path?query=value¶m=123#fragment')ββ
β http://example.com/path#fragment β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
cutQueryStringAndFragment {#cutQueryStringAndFragment}
Introduced in: v1.1
Removes the query string and fragment identifier, including the question mark and number sign, from a URL.
Syntax
sql
cutQueryStringAndFragment(url)
Arguments
url
β URL.
String
Returned value
Returns the URL with query string and fragment identifier removed.
String
Examples
Usage example
sql title=Query
SELECT cutQueryStringAndFragment('http://example.com/path?query=value¶m=123#fragment');
response title=Response
ββcutQueryStringAndFragment('http://example.com/path?query=value¶m=123#fragment')ββ
β http://example.com/path β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
cutToFirstSignificantSubdomain {#cutToFirstSignificantSubdomain}
Introduced in: v1.1
Returns the part of the domain that includes top-level subdomains up to the
first significant subdomain
.
Syntax
sql
cutToFirstSignificantSubdomain(url)
Arguments
url
β URL or domain string to process.
String
Returned value
Returns the part of the domain that includes top-level subdomains up to the first significant subdomain if possible, otherwise returns an empty string.
String
Examples
Usage example
sql title=Query
SELECT
cutToFirstSignificantSubdomain('https://news.clickhouse.com.tr/'),
cutToFirstSignificantSubdomain('www.tr'),
cutToFirstSignificantSubdomain('tr');
response title=Response
ββcutToFirstSignificantSubdomain('https://news.clickhouse.com.tr/')ββ¬βcutToFirstSignificantSubdomain('www.tr')ββ¬βcutToFirstSignificantSubdomain('tr')ββ
β clickhouse.com.tr β tr β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββ
cutToFirstSignificantSubdomainCustom {#cutToFirstSignificantSubdomainCustom}
Introduced in: v21.1
Returns the part of the domain that includes top-level subdomains up to the first significant subdomain. Accepts custom
TLD list
name. This function can be useful if you need a fresh TLD list or if you have a custom list.
Configuration example
```yaml
public_suffix_list.dat
```
Syntax
sql
cutToFirstSignificantSubdomainCustom(url, tld_list_name)
Arguments
url
β URL or domain string to process.
String | {"source_file": "url-functions.md"} | [
-0.05094064772129059,
0.028725972399115562,
0.04294683784246445,
0.03338225558400154,
-0.052848931401968,
0.009453849866986275,
0.06906652450561523,
0.001486615277826786,
0.0336422473192215,
-0.0596204474568367,
-0.0035634564701467752,
-0.03644954040646553,
0.020244577899575233,
-0.0301945... |
efb4a6ad-bb14-4580-9e9e-abd4c8ab85f6 | ```yaml
public_suffix_list.dat
```
Syntax
sql
cutToFirstSignificantSubdomainCustom(url, tld_list_name)
Arguments
url
β URL or domain string to process.
String
tld_list_name
β Name of the custom TLD list configured in ClickHouse.
const String
Returned value
Returns the part of the domain that includes top-level subdomains up to the first significant subdomain.
String
Examples
Using custom TLD list for non-standard domains
sql title=Query
SELECT cutToFirstSignificantSubdomainCustom('bar.foo.there-is-no-such-domain', 'public_suffix_list')
response title=Response
foo.there-is-no-such-domain
cutToFirstSignificantSubdomainCustomRFC {#cutToFirstSignificantSubdomainCustomRFC}
Introduced in: v22.10
Returns the part of the domain that includes top-level subdomains up to the first significant subdomain.
Accepts custom
TLD list
name.
This function can be useful if you need a fresh TLD list or if you have a custom list.
Similar to
cutToFirstSignificantSubdomainCustom
but conforms to RFC 3986.
Configuration example
```xml
public_suffix_list.dat
```
Syntax
sql
cutToFirstSignificantSubdomainCustomRFC(url, tld_list_name)
Arguments
url
β URL or domain string to process according to RFC 3986. -
tld_list_name
β Name of the custom TLD list configured in ClickHouse.
Returned value
Returns the part of the domain that includes top-level subdomains up to the first significant subdomain.
String
Examples
Usage example
sql title=Query
SELECT cutToFirstSignificantSubdomainCustomRFC('www.foo', 'public_suffix_list');
response title=Response
ββcutToFirstSignificantSubdomainCustomRFC('www.foo', 'public_suffix_list')ββββββ
β www.foo β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
cutToFirstSignificantSubdomainCustomWithWWW {#cutToFirstSignificantSubdomainCustomWithWWW}
Introduced in: v21.1
Returns the part of the domain that includes top-level subdomains up to the first significant subdomain without stripping 'www'. Accepts custom TLD list name. It can be useful if you need a fresh TLD list or if you have a custom list.
Configuration example
```yaml
public_suffix_list.dat
Syntax
sql
cutToFirstSignificantSubdomainCustomWithWWW(url, tld_list_name)
Arguments
url
β URL or domain string to process. -
tld_list_name
β Name of the custom TLD list configured in ClickHouse.
Returned value
Part of the domain that includes top-level subdomains up to the first significant subdomain without stripping 'www'.
String
Examples
Usage example
sql title=Query
SELECT cutToFirstSignificantSubdomainCustomWithWWW('www.foo', 'public_suffix_list'); | {"source_file": "url-functions.md"} | [
-0.022537628188729286,
-0.04199008271098137,
0.008791659027338028,
-0.05830393359065056,
-0.026232309639453888,
-0.09005293995141983,
0.024159977212548256,
0.02262309566140175,
-0.001851760665886104,
0.02041737735271454,
0.01610875315964222,
-0.038435742259025574,
-0.021152736619114876,
-0... |
5aa4e58e-f5aa-4d2d-8dad-a4038003f712 | Examples
Usage example
sql title=Query
SELECT cutToFirstSignificantSubdomainCustomWithWWW('www.foo', 'public_suffix_list');
response title=Response
ββcutToFirstSignificantSubdomainCustomWithWWW('www.foo', 'public_suffix_list')ββ
β www.foo β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
cutToFirstSignificantSubdomainCustomWithWWWRFC {#cutToFirstSignificantSubdomainCustomWithWWWRFC}
Introduced in: v22.10
Returns the part of the domain that includes top-level subdomains up to the first significant subdomain without stripping
www
.
Accepts custom TLD list name.
It can be useful if you need a fresh TLD list or if you have a custom list.
Similar to
cutToFirstSignificantSubdomainCustomWithWWW
but conforms to
RFC 3986
.
Configuration example
```xml
public_suffix_list.dat
Syntax
sql
cutToFirstSignificantSubdomainCustomWithWWWRFC(url, tld_list_name)
Arguments
url
β URL or domain string to process according to RFC 3986. -
tld_list_name
β Name of the custom TLD list configured in ClickHouse.
Returned value
Returns the part of the domain that includes top-level subdomains up to the first significant subdomain without stripping
www
.
String
Examples
RFC 3986 parsing preserving www with custom TLD list
sql title=Query
SELECT cutToFirstSignificantSubdomainCustomWithWWWRFC('https://www.subdomain.example.custom', 'public_suffix_list')
response title=Response
www.example.custom
cutToFirstSignificantSubdomainRFC {#cutToFirstSignificantSubdomainRFC}
Introduced in: v22.10
Returns the part of the domain that includes top-level subdomains up to the
"first significant subdomain"
. Similar to
cutToFirstSignificantSubdomain
but conforms to
RFC 3986
.
Syntax
sql
cutToFirstSignificantSubdomainRFC(url)
Arguments
url
β URL or domain string to process according to RFC 3986.
String
Returned value
Returns the part of the domain that includes top-level subdomains up to the first significant subdomain if possible, otherwise returns an empty string.
String
Examples
Usage example
sql title=Query
SELECT
cutToFirstSignificantSubdomain('http://user:password@example.com:8080'),
cutToFirstSignificantSubdomainRFC('http://user:password@example.com:8080');
response title=Response
ββcutToFirstSignificantSubdomain('http://user:password@example.com:8080')ββ¬βcutToFirstSignificantSubdomainRFC('http://user:password@example.com:8080')ββ
β β example.com β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
cutToFirstSignificantSubdomainWithWWW {#cutToFirstSignificantSubdomainWithWWW}
Introduced in: v20.12 | {"source_file": "url-functions.md"} | [
-0.05465582758188248,
-0.025212762877345085,
-0.009370354004204273,
-0.05876559391617775,
-0.03737879544496536,
-0.09107708930969238,
0.014457782730460167,
0.038103602826595306,
-0.010087460279464722,
0.017505336552858353,
0.018231213092803955,
-0.04106529802083969,
0.023136839270591736,
-... |
ebf8a132-5c79-4cb2-b62a-5d0d0f2d0fdf | cutToFirstSignificantSubdomainWithWWW {#cutToFirstSignificantSubdomainWithWWW}
Introduced in: v20.12
Returns the part of the domain that includes top-level subdomains up to the "first significant subdomain", without stripping 'www.'.
Similar to
cutToFirstSignificantSubdomain
but preserves the 'www.' prefix if present.
Syntax
sql
cutToFirstSignificantSubdomainWithWWW(url)
Arguments
url
β URL or domain string to process.
String
Returned value
Returns the part of the domain that includes top-level subdomains up to the first significant subdomain (with www) if possible, otherwise returns an empty string.
String
Examples
Usage example
sql title=Query
SELECT
cutToFirstSignificantSubdomainWithWWW('https://news.clickhouse.com.tr/'),
cutToFirstSignificantSubdomainWithWWW('www.tr'),
cutToFirstSignificantSubdomainWithWWW('tr');
response title=Response
ββcutToFirstSignificantSubdomainWithWWW('https://news.clickhouse.com.tr/')ββ¬βcutToFirstSignificantSubdomainWithWWW('www.tr')ββ¬βcutToFirstSignificantSubdomainWithWWW('tr')ββ
β clickhouse.com.tr β www.tr β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββ
cutToFirstSignificantSubdomainWithWWWRFC {#cutToFirstSignificantSubdomainWithWWWRFC}
Introduced in: v22.10
Returns the part of the domain that includes top-level subdomains up to the "first significant subdomain", without stripping 'www'. Similar to
cutToFirstSignificantSubdomainWithWWW
but conforms to
RFC 3986
.
Syntax
sql
cutToFirstSignificantSubdomainWithWWWRFC(url)
Arguments
url
β URL or domain string to process according to RFC 3986.
Returned value
Returns the part of the domain that includes top-level subdomains up to the first significant subdomain (with 'www') if possible, otherwise returns an empty string
String
Examples
Usage example
sql title=Query
SELECT
cutToFirstSignificantSubdomainWithWWW('http:%2F%2Fwwwww.nova@mail.ru/economicheskiy'),
cutToFirstSignificantSubdomainWithWWWRFC('http:%2F%2Fwwwww.nova@mail.ru/economicheskiy');
response title=Response
ββcutToFirstSignificantSubdomainWithWWW('http:%2F%2Fwwwww.nova@mail.ru/economicheskiy')ββ¬βcutToFirstSignificantSubdomainWithWWWRFC('http:%2F%2Fwwwww.nova@mail.ru/economicheskiy')ββ
β β mail.ru β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
cutURLParameter {#cutURLParameter}
Introduced in: v1.1 | {"source_file": "url-functions.md"} | [
0.009057939983904362,
-0.028426017612218857,
0.036473389714956284,
-0.041743502020835876,
-0.022951066493988037,
-0.09958530962467194,
0.030448170378804207,
-0.03940865024924278,
0.015996607020497322,
0.006647753529250622,
0.000861273321788758,
-0.062198739498853683,
-0.00030242628417909145,... |
ac4a26f3-feb3-4ccd-a8cc-c61a73e4610b | cutURLParameter {#cutURLParameter}
Introduced in: v1.1
Removes the
name
parameter from a URL, if present.
This function does not encode or decode characters in parameter names, e.g.
Client ID
and
Client%20ID
are treated as different parameter names.
Syntax
sql
cutURLParameter(url, name)
Arguments
url
β URL.
String
name
β Name of URL parameter.
String
or
Array(String)
Returned value
URL with
name
URL parameter removed.
String
Examples
Usage example
sql title=Query
SELECT
cutURLParameter('http://bigmir.net/?a=b&c=d&e=f#g', 'a') AS url_without_a,
cutURLParameter('http://bigmir.net/?a=b&c=d&e=f#g', ['c', 'e']) AS url_without_c_and_e;
response title=Response
ββurl_without_aβββββββββββββββββ¬βurl_without_c_and_eβββββββ
β http://bigmir.net/?c=d&e=f#g β http://bigmir.net/?a=b#g β
ββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββ
cutWWW {#cutWWW}
Introduced in: v1.1
Removes the leading
www.
, if present, from the URL's domain.
Syntax
sql
cutWWW(url)
Arguments
url
β URL.
String
Returned value
Returns the URL with leading
www.
removed from the domain.
String
Examples
Usage example
sql title=Query
SELECT cutWWW('http://www.example.com/path?query=value#fragment');
response title=Response
ββcutWWW('http://www.example.com/path?query=value#fragment')ββ
β http://example.com/path?query=value#fragment β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
decodeURLComponent {#decodeURLComponent}
Introduced in: v1.1
Takes a URL-encoded string as input and decodes it back to its original, readable form.
Syntax
sql
decodeURLComponent(url)
Arguments
url
β URL.
String
Returned value
Returns the decoded URL.
String
Examples
Usage example
sql title=Query
SELECT decodeURLComponent('http://127.0.0.1:8123/?query=SELECT%201%3B') AS DecodedURL;
response title=Response
ββDecodedURLββββββββββββββββββββββββββββββ
β http://127.0.0.1:8123/?query=SELECT 1; β
ββββββββββββββββββββββββββββββββββββββββββ
decodeURLFormComponent {#decodeURLFormComponent}
Introduced in: v1.1
Decodes URL-encoded strings using form encoding rules (
RFC-1866
), where
+
signs are converted to spaces and percent-encoded characters are decoded.
Syntax
sql
decodeURLFormComponent(url)
Arguments
url
β URL.
String
Returned value
Returns the decoded URL.
String
Examples
Usage example
sql title=Query
SELECT decodeURLFormComponent('http://127.0.0.1:8123/?query=SELECT%201+2%2B3') AS DecodedURL;
response title=Response
ββDecodedURLβββββββββββββββββββββββββββββββββ
β http://127.0.0.1:8123/?query=SELECT 1 2+3 β
βββββββββββββββββββββββββββββββββββββββββββββ
domain {#domain}
Introduced in: v1.1
Extracts the hostname from a URL.
The URL can be specified with or without a protocol.
Syntax
sql
domain(url)
Arguments
url
β URL.
String
Returned value | {"source_file": "url-functions.md"} | [
-0.027431130409240723,
0.035309869796037674,
-0.0014921554829925299,
0.03307681530714035,
-0.1423465460538864,
-0.049705907702445984,
0.0037824921309947968,
-0.04960411414504051,
0.005920090712606907,
0.011542610824108124,
0.030667169019579887,
-0.05025269463658333,
0.019100306555628777,
-... |
049987e7-5e99-4e64-88b9-ad18bb4e236d | Introduced in: v1.1
Extracts the hostname from a URL.
The URL can be specified with or without a protocol.
Syntax
sql
domain(url)
Arguments
url
β URL.
String
Returned value
Returns the host name if the input string can be parsed as a URL, otherwise an empty string.
String
Examples
Usage example
sql title=Query
SELECT domain('svn+ssh://some.svn-hosting.com:80/repo/trunk');
response title=Response
ββdomain('svn+ssh://some.svn-hosting.com:80/repo/trunk')ββ
β some.svn-hosting.com β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
domainRFC {#domainRFC}
Introduced in: v22.10
Extracts the hostname from a URL.
Similar to
domain
, but
RFC 3986
conformant.
Syntax
sql
domainRFC(url)
Arguments
url
β URL.
String
Returned value
Returns the host name if the input string can be parsed as a URL, otherwise an empty string.
String
Examples
Usage example
sql title=Query
SELECT
domain('http://user:password@example.com:8080/path?query=value#fragment'),
domainRFC('http://user:password@example.com:8080/path?query=value#fragment');
response title=Response
ββdomain('http://user:password@example.com:8080/path?query=value#fragment')ββ¬βdomainRFC('http://user:password@example.com:8080/path?query=value#fragment')ββ
β β example.com β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
domainWithoutWWW {#domainWithoutWWW}
Introduced in: v1.1
Returns the domain of a URL without leading
www.
if present.
Syntax
sql
domainWithoutWWW(url)
Arguments
url
β URL.
String
Returned value
Returns the domain name if the input string can be parsed as a URL (without leading
www.
), otherwise an empty string.
String
Examples
Usage example
sql title=Query
SELECT domainWithoutWWW('http://paul@www.example.com:80/');
response title=Response
ββdomainWithoutWWW('http://paul@www.example.com:80/')ββ
β example.com β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
domainWithoutWWWRFC {#domainWithoutWWWRFC}
Introduced in: v1.1
Returns the domain without leading
www.
if present. Similar to
domainWithoutWWW
but conforms to
RFC 3986
.
Syntax
sql
domainWithoutWWWRFC(url)
Arguments
url
β URL.
String
Returned value
Returns the domain name if the input string can be parsed as a URL (without leading
www.
), otherwise an empty string.
String
Examples
Usage example
sql title=Query
SELECT
domainWithoutWWW('http://user:password@www.example.com:8080/path?query=value#fragment'),
domainWithoutWWWRFC('http://user:password@www.example.com:8080/path?query=value#fragment'); | {"source_file": "url-functions.md"} | [
-0.051788344979286194,
-0.07503188401460648,
-0.06452620029449463,
0.002294011879712343,
-0.017329121008515358,
-0.11648423969745636,
0.009957721456885338,
-0.006673752795904875,
0.04296014457941055,
-0.027038246393203735,
0.000019646746295620687,
-0.011867971159517765,
0.018634019419550896,... |
0e87d664-fce0-42cd-a114-58c10d3f636f | response title=Response
ββdomainWithoutWWW('http://user:password@www.example.com:8080/path?query=value#fragment')ββ¬βdomainWithoutWWWRFC('http://user:password@www.example.com:8080/path?query=value#fragment')ββ
β β example.com β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
encodeURLComponent {#encodeURLComponent}
Introduced in: v22.3
Takes a regular string and converts it into a URL-encoded (percent-encoded) format where special characters are replaced with their percent-encoded equivalents.
Syntax
sql
encodeURLComponent(url)
Arguments
url
β URL.
String
Returned value
Returns the encoded URL.
String
Examples
Usage example
sql title=Query
SELECT encodeURLComponent('http://127.0.0.1:8123/?query=SELECT 1;') AS EncodedURL;
response title=Response
ββEncodedURLββββββββββββββββββββββββββββββββββββββββββββββββ
β http%3A%2F%2F127.0.0.1%3A8123%2F%3Fquery%3DSELECT%201%3B β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
encodeURLFormComponent {#encodeURLFormComponent}
Introduced in: v22.3
Encodes strings using form encoding rules (
RFC-1866
), where spaces are converted to + signs and special characters are percent-encoded.
Syntax
sql
encodeURLFormComponent(url)
Arguments
url
β URL.
String
Returned value
Returns the encoded URL.
String
Examples
Usage example
sql title=Query
SELECT encodeURLFormComponent('http://127.0.0.1:8123/?query=SELECT 1 2+3') AS EncodedURL;
response title=Response
ββEncodedURLβββββββββββββββββββββββββββββββββββββββββββββββββ
β http%3A%2F%2F127.0.0.1%3A8123%2F%3Fquery%3DSELECT+1+2%2B3 β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
extractURLParameter {#extractURLParameter}
Introduced in: v1.1
Returns the value of the
name
parameter in the URL, if present, otherwise an empty string is returned.
If there are multiple parameters with this name, the first occurrence is returned.
The function assumes that the parameter in the
url
parameter is encoded in the same way as in the
name
argument.
Syntax
sql
extractURLParameter(url, name)
Arguments
url
β URL.
String
name
β Parameter name.
String
Returned value
Returns the value of the URL parameter with the specified name.
String
Examples
Usage example
sql title=Query
SELECT extractURLParameter('http://example.com/?param1=value1¶m2=value2', 'param1');
response title=Response
ββextractURLPaβ―, 'param1')ββ
β value1 β
ββββββββββββββββββββββββββββ
extractURLParameterNames {#extractURLParameterNames}
Introduced in: v1.1
Returns an array of name strings corresponding to the names of URL parameters.
The values are not decoded.
Syntax | {"source_file": "url-functions.md"} | [
-0.04454997554421425,
-0.04474275931715965,
-0.017513863742351532,
-0.01460795197635889,
-0.055919669568538666,
-0.008214449509978294,
-0.00593806616961956,
-0.010676640085875988,
0.021186061203479767,
-0.0335826501250267,
0.004231805447489023,
-0.043343815952539444,
0.0781477764248848,
-0... |
ed6f2c37-a4e9-493d-aa76-2c2ff2c77535 | extractURLParameterNames {#extractURLParameterNames}
Introduced in: v1.1
Returns an array of name strings corresponding to the names of URL parameters.
The values are not decoded.
Syntax
sql
extractURLParameterNames(url)
Arguments
url
β URL.
String
Returned value
Returns an array of name strings corresponding to the names of URL parameters.
Array(String)
Examples
Usage example
sql title=Query
SELECT extractURLParameterNames('http://example.com/?param1=value1¶m2=value2');
response title=Response
ββextractURLPaβ―m2=value2')ββ
β ['param1','param2'] β
ββββββββββββββββββββββββββββ
extractURLParameters {#extractURLParameters}
Introduced in: v1.1
Returns an array of
name=value
strings corresponding to the URL parameters.
The values are not decoded.
Syntax
sql
extractURLParameters(url)
Arguments
url
β URL.
String
Returned value
Returns an array of
name=value
strings corresponding to the URL parameters.
Array(String)
Examples
Usage example
sql title=Query
SELECT extractURLParameters('http://example.com/?param1=value1¶m2=value2');
response title=Response
ββextractURLParameβ―¶m2=value2')ββ
β ['param1=value1','param2=value2'] β
βββββββββββββββββββββββββββββββββββββ
firstSignificantSubdomain {#firstSignificantSubdomain}
Introduced in: v
Returns the "first significant subdomain".
The first significant subdomain is a second-level domain if it is 'com', 'net', 'org', or 'co'.
Otherwise, it is a third-level domain.
For example, firstSignificantSubdomain('https://news.clickhouse.com/') = 'clickhouse', firstSignificantSubdomain ('https://news.clickhouse.com.tr/') = 'clickhouse'.
The list of "insignificant" second-level domains and other implementation details may change in the future.
Syntax
```sql
```
Arguments
None.
Returned value
Examples
firstSignificantSubdomain
sql title=Query
SELECT firstSignificantSubdomain('https://news.clickhouse.com/')
```response title=Response
```
firstSignificantSubdomainRFC {#firstSignificantSubdomainRFC}
Introduced in: v
Returns the "first significant subdomain" according to RFC 1034.
Syntax
```sql
```
Arguments
None.
Returned value
Examples
fragment {#fragment}
Introduced in: v1.1
Returns the fragment identifier without the initial hash symbol.
Syntax
sql
fragment(url)
Arguments
url
β URL.
String
Returned value
Returns the fragment identifier without the initial hash symbol.
String
Examples
Usage example
sql title=Query
SELECT fragment('https://clickhouse.com/docs/getting-started/quick-start/cloud#1-create-a-clickhouse-service');
response title=Response
ββfragment('httpβ―ouse-service')ββ
β 1-create-a-clickhouse-service β
βββββββββββββββββββββββββββββββββ
netloc {#netloc}
Introduced in: v20.5
Extracts network locality (
username:password@host:port
) from a URL.
Syntax
sql
netloc(url)
Arguments
url
β URL.
String
Returned value | {"source_file": "url-functions.md"} | [
-0.0569194033741951,
-0.009495045989751816,
-0.0390506274998188,
0.057110488414764404,
-0.06239322945475578,
-0.04990696534514427,
0.06609019637107849,
-0.029317913576960564,
0.006906827911734581,
-0.023423142731189728,
-0.007804316934198141,
-0.01163253653794527,
0.044427331537008286,
-0.... |
b642ab50-adb4-4759-932c-b03d116a72fd | netloc {#netloc}
Introduced in: v20.5
Extracts network locality (
username:password@host:port
) from a URL.
Syntax
sql
netloc(url)
Arguments
url
β URL.
String
Returned value
Returns
username:password@host:port
from a given URL.
String
Examples
Usage example
sql title=Query
SELECT netloc('http://paul@www.example.com:80/');
response title=Response
ββnetloc('httpβ―e.com:80/')ββ
β paul@www.example.com:80 β
ββββββββββββββββββββββββββββ
path {#path}
Introduced in: v1.1
Returns the path without query string from a URL.
Syntax
sql
path(url)
Arguments
url
β URL.
String
Returned value
Returns the path of the URL without query string.
String
Examples
Usage example
sql title=Query
SELECT path('https://clickhouse.com/docs/sql-reference/functions/url-functions/?query=value');
response title=Response
ββpath('https://clickhouse.com/en/sql-reference/functions/url-functions/?query=value')ββ
β /docs/sql-reference/functions/url-functions/ β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
pathFull {#pathFull}
Introduced in: v1.1
The same as
path
, but includes the query string and fragment of the URL.
Syntax
sql
pathFull(url)
Arguments
url
β URL.
String
Returned value
Returns the path of the URL including query string and fragment.
String
Examples
Usage example
sql title=Query
SELECT pathFull('https://clickhouse.com/docs/sql-reference/functions/url-functions/?query=value#section');
response title=Response
ββpathFull('https://clickhouse.comβ―unctions/?query=value#section')ββ
β /docs/sql-reference/functions/url-functions/?query=value#section β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
port {#port}
Introduced in: v20.5
Returns the port of a URL, or the
default_port
if the URL contains no port or cannot be parsed.
Syntax
sql
port(url[, default_port])
Arguments
url
β URL.
String
default_port
β Optional. The default port number to be returned.
0
by default.
UInt16
Returned value
Returns the port of the URL, or the default port if there is no port in the URL or in case of a validation error.
UInt16
Examples
Usage example
sql title=Query
SELECT port('https://clickhouse.com:8443/docs'), port('https://clickhouse.com/docs', 443);
response title=Response
ββport('https://clickhouse.com:8443/docs')ββ¬βport('https://clickhouse.com/docs', 443)ββ
β 8443 β 443 β
ββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββ
portRFC {#portRFC}
Introduced in: v22.10
Returns the port or
default_port
if the URL contains no port or cannot be parsed.
Similar to
port
, but
RFC 3986
conformant.
Syntax
sql
portRFC(url[, default_port])
Arguments
url
β URL.
String | {"source_file": "url-functions.md"} | [
-0.024795880541205406,
-0.07371967285871506,
-0.03516685590147972,
0.05565075948834419,
-0.0923273041844368,
-0.047527048736810684,
0.03641564026474953,
0.008364333771169186,
0.009128987789154053,
-0.015466946177184582,
-0.020234819501638412,
-0.005879309494048357,
0.021958475932478905,
-0... |
cf34106a-1077-48d6-b8a0-c93810db0c2b | Syntax
sql
portRFC(url[, default_port])
Arguments
url
β URL.
String
default_port
β Optional. The default port number to be returned.
0
by default.
UInt16
Returned value
Returns the port or the default port if there is no port in the URL or in case of a validation error.
UInt16
Examples
Usage example
sql title=Query
SELECT port('http://user:password@example.com:8080/'), portRFC('http://user:password@example.com:8080/');
response title=Response
ββport('http:/β―com:8080/')ββ¬βportRFC('httβ―com:8080/')ββ
β 0 β 8080 β
ββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββ
protocol {#protocol}
Introduced in: v1.1
Extracts the protocol from a URL.
Examples of typical returned values: http, https, ftp, mailto, tel, magnet.
Syntax
sql
protocol(url)
Arguments
url
β URL.
String
Returned value
Returns the protocol of the URL, or an empty string if it cannot be determined.
String
Examples
Usage example
sql title=Query
SELECT protocol('https://clickhouse.com/');
response title=Response
ββprotocol('https://clickhouse.com/')ββ
β https β
βββββββββββββββββββββββββββββββββββββββ
queryString {#queryString}
Introduced in: v1.1
Returns the query string of a URL without the initial question mark,
#
and everything after
#
.
Syntax
sql
queryString(url)
Arguments
url
β URL.
String
Returned value
Returns the query string of the URL without the initial question mark and fragment.
String
Examples
Usage example
sql title=Query
SELECT queryString('https://clickhouse.com/docs?query=value¶m=123#section');
response title=Response
ββqueryString(β―3#section')ββ
β query=value¶m=123 β
ββββββββββββββββββββββββββββ
queryStringAndFragment {#queryStringAndFragment}
Introduced in: v1.1
Returns the query string and fragment identifier of a URL.
Syntax
sql
queryStringAndFragment(url)
Arguments
url
β URL.
String
Returned value
Returns the query string and fragment identifier of the URL.
String
Examples
Usage example
sql title=Query
SELECT queryStringAndFragment('https://clickhouse.com/docs?query=value¶m=123#section');
response title=Response
ββqueryStringAndβ―=123#section')ββ
β query=value¶m=123#section β
βββββββββββββββββββββββββββββββββ
topLevelDomain {#topLevelDomain}
Introduced in: v1.1
Extracts the the top-level domain from a URL.
:::note
The URL can be specified with or without a protocol.
For example:
text
svn+ssh://some.svn-hosting.com:80/repo/trunk
some.svn-hosting.com:80/repo/trunk
https://clickhouse.com/time/
:::
Syntax
sql
topLevelDomain(url)
Arguments
url
β URL.
String
Returned value
Returns the domain name if the input string can be parsed as a URL. Otherwise, an empty string.
String
Examples
Usage example
sql title=Query
SELECT topLevelDomain('svn+ssh://www.some.svn-hosting.com:80/repo/trunk'); | {"source_file": "url-functions.md"} | [
-0.0723685547709465,
-0.03816935792565346,
-0.09693082422018051,
-0.037392277270555496,
-0.053228434175252914,
-0.10920621454715729,
0.025590920820832253,
-0.0055869873613119125,
-0.044286806136369705,
-0.042327944189310074,
0.059805288910865784,
0.015012607909739017,
0.0031252196058630943,
... |
54f2a69c-3c66-4ec8-a700-74a03a2a6938 | Examples
Usage example
sql title=Query
SELECT topLevelDomain('svn+ssh://www.some.svn-hosting.com:80/repo/trunk');
response title=Response
ββtopLevelDomain('svn+ssh://www.some.svn-hosting.com:80/repo/trunk')ββ
β com β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
topLevelDomainRFC {#topLevelDomainRFC}
Introduced in: v22.10
Extracts the the top-level domain from a URL.
Similar to
topLevelDomain
, but conforms to
RFC 3986
.
Syntax
sql
topLevelDomainRFC(url)
Arguments
url
β URL.
String
Returned value
Domain name if the input string can be parsed as a URL. Otherwise, an empty string.
String
Examples
Usage example
sql title=Query
SELECT topLevelDomain('http://foo:foo%41bar@foo.com'), topLevelDomainRFC('http://foo:foo%41bar@foo.com');
response title=Response
ββtopLevelDomain('http://foo:foo%41bar@foo.com')ββ¬βtopLevelDomainRFC('http://foo:foo%41bar@foo.com')ββ
β β com β
ββββββββββββββββββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββββ | {"source_file": "url-functions.md"} | [
-0.01932387985289097,
-0.04932890832424164,
-0.03914673253893852,
-0.011570421978831291,
-0.05297914519906044,
-0.09538223594427109,
-0.021993910893797874,
0.024843893945217133,
0.03754048049449921,
-0.03295484557747841,
-0.023121442645788193,
-0.061664752662181854,
0.04700196161866188,
-0... |
f4abf74d-1cf1-4acc-b482-0b007e6ec0fb | description: 'Documentation for encoding functions'
sidebar_label: 'Encoding'
slug: /sql-reference/functions/encoding-functions
title: 'Encoding functions'
keywords: ['encoding', 'regular functions', 'encode', 'decode']
doc_type: 'reference'
Encoding functions
bech32Decode {#bech32Decode}
Introduced in: v25.6
Decodes a Bech32 address string generated by either the bech32 or bech32m algorithms.
:::note
Unlike the encode function,
Bech32Decode
will automatically handle padded FixedStrings.
:::
Syntax
sql
bech32Decode(address)
Arguments
address
β A Bech32 string to decode.
String
or
FixedString
Returned value
Returns a tuple consisting of
(hrp, data)
that was used to encode the string. The data is in binary format.
Tuple(String, String)
Examples
Decode address
sql title=Query
SELECT tup.1 AS hrp, hex(tup.2) AS data FROM (SELECT bech32Decode('bc1w508d6qejxtdg4y5r3zarvary0c5xw7kj7gz7z') AS tup)
response title=Response
bc 751E76E8199196D454941C45D1B3A323F1433BD6
Testnet address
sql title=Query
SELECT tup.1 AS hrp, hex(tup.2) AS data FROM (SELECT bech32Decode('tb1w508d6qejxtdg4y5r3zarvary0c5xw7kzp034v') AS tup)
response title=Response
tb 751E76E8199196D454941C45D1B3A323F1433BD6
bech32Encode {#bech32Encode}
Introduced in: v25.6
Encodes a binary data string, along with a human-readable part (HRP), using the
Bech32 or Bech32m
algorithms.
:::note
When using the
FixedString
data type, if a value does not fully fill the row it is padded with null characters.
While the
bech32Encode
function will handle this automatically for the hrp argument, for the data argument the values must not be padded.
For this reason it is not recommended to use the
FixedString
data type for your data values unless you are
certain that they are all the same length and ensure that your
FixedString
column is set to that length as well.
:::
Syntax
sql
bech32Encode(hrp, data[, witver])
Arguments
hrp
β A String of
1 - 83
lowercase characters specifying the "human-readable part" of the code. Usually 'bc' or 'tb'.
String
or
FixedString
data
β A String of binary data to encode.
String
or
FixedString
witver
β Optional. The witness version (default = 1). An
UInt*
specifying the version of the algorithm to run.
0
for Bech32 and
1
or greater for Bech32m.
UInt*
Returned value
Returns a Bech32 address string, consisting of the human-readable part, a separator character which is always '1', and a data part. The length of the string will never exceed 90 characters. If the algorithm cannot generate a valid address from the input, it will return an empty string.
String
Examples
Default Bech32m
sql title=Query
-- When no witness version is supplied, the default is 1, the updated Bech32m algorithm.
SELECT bech32Encode('bc', unhex('751e76e8199196d454941c45d1b3a323f1433bd6'))
response title=Response
bc1w508d6qejxtdg4y5r3zarvary0c5xw7k8zcwmq
Bech32 algorithm | {"source_file": "encoding-functions.md"} | [
0.01796361617743969,
-0.004906814079731703,
-0.05904068052768707,
0.010620342567563057,
-0.07182144373655319,
0.014044497162103653,
0.05490444228053093,
-0.014351099729537964,
-0.04537881165742874,
-0.00663487333804369,
-0.04314140975475311,
-0.042022597044706345,
0.03222484514117241,
-0.1... |
159d5037-5e43-461c-b578-4ba35ae644fd | response title=Response
bc1w508d6qejxtdg4y5r3zarvary0c5xw7k8zcwmq
Bech32 algorithm
sql title=Query
-- A witness version of 0 will result in a different address string.
SELECT bech32Encode('bc', unhex('751e76e8199196d454941c45d1b3a323f1433bd6'), 0)
response title=Response
bc1w508d6qejxtdg4y5r3zarvary0c5xw7kj7gz7z
Custom HRP
sql title=Query
-- While 'bc' (Mainnet) and 'tb' (Testnet) are the only allowed hrp values for the
-- SegWit address format, Bech32 allows any hrp that satisfies the above requirements.
SELECT bech32Encode('abcdefg', unhex('751e76e8199196d454941c45d1b3a323f1433bd6'), 10)
response title=Response
abcdefg1w508d6qejxtdg4y5r3zarvary0c5xw7k9rp8r4
bin {#bin}
Introduced in: v21.8
Returns a string containing the argument's binary representation according
to the following logic for different types:
| Type | Description |
|----------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
(U)Int*
| Prints bin digits from the most significant to least significant (big-endian or "human-readable" order). It starts with the most significant non-zero byte (leading zero bytes are omitted) but always prints eight digits of every byte if the leading digit is zero.|
|
Date
and
DateTime
| Formatted as corresponding integers (the number of days since epoch for Date and the value of unix timestamp for DateTime). |
|
String
and
FixedString
| All bytes are simply encoded as eight binary numbers. Zero bytes are not omitted. |
|
Float*
and
Decimal
| Encoded as their representation in memory. As we support little-endian architecture, they are encoded in little-endian. Zero leading/trailing bytes are not omitted. |
|
UUID
| Encoded as big-endian order string. |
Syntax
sql
bin(arg)
Arguments | {"source_file": "encoding-functions.md"} | [
0.01326151005923748,
0.055226173251867294,
0.038815587759017944,
-0.0010370807722210884,
-0.07455359399318695,
0.016151444986462593,
0.009032036177814007,
-0.06864847242832184,
0.008089008741080761,
0.016152814030647278,
-0.041457649320364,
-0.12078803032636642,
0.029025482013821602,
-0.05... |
be70b45c-247c-4165-8dba-fee443697d0a | Syntax
sql
bin(arg)
Arguments
arg
β A value to convert to binary.
String
or
FixedString
or
(U)Int*
or
Float*
or
Decimal
or
Date
or
DateTime
Returned value
Returns a string with the binary representation of the argument.
String
Examples
Simple integer
sql title=Query
SELECT bin(14)
response title=Response
ββbin(14)βββ
β 00001110 β
ββββββββββββ
Float32 numbers
sql title=Query
SELECT bin(toFloat32(number)) AS bin_presentation FROM numbers(15, 2)
response title=Response
ββbin_presentationββββββββββββββββββ
β 00000000000000000111000001000001 β
β 00000000000000001000000001000001 β
ββββββββββββββββββββββββββββββββββββ
Float64 numbers
sql title=Query
SELECT bin(toFloat64(number)) AS bin_presentation FROM numbers(15, 2)
response title=Response
ββbin_presentationββββββββββββββββββββββββββββββββββββββββββββββββββ
β 0000000000000000000000000000000000000000000000000010111001000000 β
β 0000000000000000000000000000000000000000000000000011000001000000 β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
UUID conversion
sql title=Query
SELECT bin(toUUID('61f0c404-5cb3-11e7-907b-a6006ad3dba0')) AS bin_uuid
response title=Response
ββbin_uuidββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 01100001111100001100010000000100010111001011001100010001111001111001000001111011101001100000000001101010110100111101101110100000 β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
bitPositionsToArray {#bitPositionsToArray}
Introduced in: v21.7
This function returns the positions (in ascending order) of the 1 bits in the binary representation of an unsigned integer.
Signed input integers are first casted to an unsigned integer.
Syntax
sql
bitPositionsToArray(arg)
Arguments
arg
β An integer value.
(U)Int*
Returned value
Returns an array with the ascendingly ordered positions of 1 bits in the binary representation of the input.
Array(UInt64)
Examples
Single bit set
sql title=Query
SELECT bitPositionsToArray(toInt8(1)) AS bit_positions
response title=Response
ββbit_positionsββ
β [0] β
βββββββββββββββββ
All bits set
sql title=Query
SELECT bitPositionsToArray(toInt8(-1)) AS bit_positions
response title=Response
ββbit_positionsββββββββββββββ
β [0, 1, 2, 3, 4, 5, 6, 7] β
βββββββββββββββββββββββββββββ
bitmaskToArray {#bitmaskToArray}
Introduced in: v1.1
This function decomposes an integer into a sum of powers of two.
The powers of two are returned as an ascendingly ordered array.
Syntax
sql
bitmaskToArray(num)
Arguments
num
β An integer value.
(U)Int*
Returned value
Returns an array with the ascendingly ordered powers of two which sum up to the input number.
Array(UInt64)
Examples
Basic example
sql title=Query
SELECT bitmaskToArray(50) AS powers_of_two | {"source_file": "encoding-functions.md"} | [
0.09074559807777405,
0.022608676925301552,
-0.11403637379407883,
0.04332786798477173,
-0.08467885106801987,
-0.024182016029953957,
0.07159890234470367,
0.05105225741863251,
-0.04746418446302414,
0.0307928454130888,
-0.0874849483370781,
-0.07421249896287918,
0.05521157383918762,
-0.04600124... |
17c5af77-736c-489b-91d5-45b1128deaf0 | Returns an array with the ascendingly ordered powers of two which sum up to the input number.
Array(UInt64)
Examples
Basic example
sql title=Query
SELECT bitmaskToArray(50) AS powers_of_two
response title=Response
ββpowers_of_twoββββ
β [2, 16, 32] β
βββββββββββββββββββ
Single power of two
sql title=Query
SELECT bitmaskToArray(8) AS powers_of_two
response title=Response
ββpowers_of_twoββ
β [8] β
βββββββββββββββββ
bitmaskToList {#bitmaskToList}
Introduced in: v1.1
Like bitmaskToArray but returns the powers of two as a comma-separated string.
Syntax
sql
bitmaskToList(num)
Arguments
num
β An integer value.
(U)Int*
Returned value
Returns a string containing comma-separated powers of two.
String
Examples
Basic example
sql title=Query
SELECT bitmaskToList(50) AS powers_list
response title=Response
ββpowers_listββββ
β 2, 16, 32 β
βββββββββββββββββ
char {#char}
Introduced in: v20.1
Returns a string with length equal to the number of arguments passed where each byte
has the value of the corresponding argument. Accepts multiple arguments of numeric types.
If the value of the argument is out of range of the
UInt8
data type, then it is converted
to
UInt8
with potential rounding and overflow.
Syntax
sql
char(num1[, num2[, ...]])
Arguments
num1[, num2[, num3 ...]]
β Numerical arguments interpreted as integers.
(U)Int8/16/32/64
or
Float*
Returned value
Returns a string of the given bytes.
String
Examples
Basic example
sql title=Query
SELECT char(104.1, 101, 108.9, 108.9, 111) AS hello;
response title=Response
ββhelloββ
β hello β
βββββββββ
Constructing arbitrary encodings
sql title=Query
-- You can construct a string of arbitrary encoding by passing the corresponding bytes.
-- for example UTF8
SELECT char(0xD0, 0xBF, 0xD1, 0x80, 0xD0, 0xB8, 0xD0, 0xB2, 0xD0, 0xB5, 0xD1, 0x82) AS hello;
response title=Response
ββhelloβββ
β ΠΏΡΠΈΠ²Π΅Ρ β
ββββββββββ
hex {#hex}
Introduced in: v1.1
Returns a string containing the argument's hexadecimal representation according
to the following logic for different types: | {"source_file": "encoding-functions.md"} | [
0.040159646421670914,
0.09911098331212997,
-0.07477452605962753,
0.06809060275554657,
-0.11660584807395935,
-0.07382870465517044,
0.07633376866579056,
0.005895751528441906,
-0.06791485100984573,
-0.03072984144091606,
-0.1000199168920517,
-0.054642826318740845,
0.038394030183553696,
-0.0170... |
116634c5-614b-4b2e-bf94-8e00566149e2 | hex {#hex}
Introduced in: v1.1
Returns a string containing the argument's hexadecimal representation according
to the following logic for different types:
| Type | Description |
|----------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
(U)Int*
| Prints hex digits ("nibbles") from the most significant to least significant (big-endian or "human-readable" order). It starts with the most significant non-zero byte (leading zero bytes are omitted) but always prints both digits of every byte even if the leading digit is zero. |
|
Date
and
DateTime
| Formatted as corresponding integers (the number of days since epoch for Date and the value of unix timestamp for DateTime). |
|
String
and
FixedString
| All bytes are simply encoded as two hexadecimal numbers. Zero bytes are not omitted. |
|
Float*
and
Decimal
| Encoded as their representation in memory. ClickHouse represents the values internally always as little endian, therefore they are encoded as such. Zero leading/trailing bytes are not omitted. |
|
UUID
| Encoded as big-endian order string. |
The function uses uppercase letters
A-F
and not using any prefixes (like
0x
) or suffixes (like
h
).
Syntax
sql
hex(arg)
Arguments
arg
β A value to convert to hexadecimal.
String
or
(U)Int*
or
Float*
or
Decimal
or
Date
or
DateTime
Returned value
Returns a string with the hexadecimal representation of the argument.
String
Examples
Simple integer
sql title=Query
SELECT hex(1)
response title=Response
01
Float32 numbers
sql title=Query
SELECT hex(toFloat32(number)) AS hex_presentation FROM numbers(15, 2) | {"source_file": "encoding-functions.md"} | [
0.06030441075563431,
0.08649371564388275,
-0.029553906992077827,
-0.011753437109291553,
-0.07807497680187225,
0.02628275752067566,
0.053525328636169434,
0.06368681788444519,
0.008431843481957912,
-0.023289434611797333,
0.016031833365559578,
-0.04862922057509422,
0.037288401275873184,
0.017... |
f8a2bf11-6cba-4a11-9c28-ed39201c9dc2 | Examples
Simple integer
sql title=Query
SELECT hex(1)
response title=Response
01
Float32 numbers
sql title=Query
SELECT hex(toFloat32(number)) AS hex_presentation FROM numbers(15, 2)
response title=Response
ββhex_presentationββ
β 00007041 β
β 00008041 β
ββββββββββββββββββββ
Float64 numbers
sql title=Query
SELECT hex(toFloat64(number)) AS hex_presentation FROM numbers(15, 2)
response title=Response
ββhex_presentationββ
β 0000000000002E40 β
β 0000000000003040 β
ββββββββββββββββββββ
UUID conversion
sql title=Query
SELECT lower(hex(toUUID('61f0c404-5cb3-11e7-907b-a6006ad3dba0'))) AS uuid_hex
response title=Response
ββuuid_hexββββββββββββββββββββββββββ
β 61f0c4045cb311e7907ba6006ad3dba0 β
ββββββββββββββββββββββββββββββββββββ
hilbertDecode {#hilbertDecode}
Introduced in: v24.6
Decodes a Hilbert curve index back into a tuple of unsigned integers, representing coordinates in multi-dimensional space.
As with the
hilbertEncode
function, this function has two modes of operation:
-
Simple
-
Expanded
Simple mode
Accepts up to 2 unsigned integers as arguments and produces a
UInt64
code.
Expanded mode
Accepts a range mask (tuple) as a first argument and up to 2 unsigned integers as
other arguments. Each number in the mask configures the number of bits by which
the corresponding argument will be shifted left, effectively scaling the argument
within its range.
Range expansion can be beneficial when you need a similar distribution for
arguments with wildly different ranges (or cardinality) For example: 'IP Address'
(0...FFFFFFFF)
and 'Country code'
(0...FF)
. As with the encode function, this is limited to 8
numbers at most.
Syntax
sql
hilbertDecode(tuple_size, code)
Arguments
tuple_size
β Integer value of no more than
2
.
UInt8/16/32/64
or
Tuple(UInt8/16/32/64)
code
β
UInt64
code.
UInt64
Returned value
Returns a tuple of the specified size.
Tuple(UInt64)
Examples
Simple mode
sql title=Query
SELECT hilbertDecode(2, 31)
response title=Response
["3", "4"]
Single argument
sql title=Query
-- Hilbert code for one argument is always the argument itself (as a tuple).
SELECT hilbertDecode(1, 1)
response title=Response
["1"]
Expanded mode
sql title=Query
-- A single argument with a tuple specifying bit shifts will be right-shifted accordingly.
SELECT hilbertDecode(tuple(2), 32768)
response title=Response
["128"]
Column usage
```sql title=Query
-- First create the table and insert some data
CREATE TABLE hilbert_numbers(
n1 UInt32,
n2 UInt32
)
ENGINE=MergeTree()
ORDER BY n1 SETTINGS index_granularity = 8192, index_granularity_bytes = '10Mi';
insert into hilbert_numbers (*) values(1,2);
-- Use column names instead of constants as function arguments
SELECT untuple(hilbertDecode(2, hilbertEncode(n1, n2))) FROM hilbert_numbers;
```
response title=Response
1 2
hilbertEncode {#hilbertEncode}
Introduced in: v24.6 | {"source_file": "encoding-functions.md"} | [
0.002799384295940399,
-0.0033506618347018957,
-0.07359596341848373,
-0.0108622582629323,
-0.03763458505272865,
-0.014516938477754593,
0.014686749316751957,
0.02264188602566719,
-0.058149080723524094,
-0.0604836642742157,
-0.009152663871645927,
-0.07904548943042755,
0.033636678010225296,
-0... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.