id stringlengths 36 36 | document stringlengths 3 3k | metadata stringlengths 23 69 | embeddings listlengths 384 384 |
|---|---|---|---|
1a93b79d-931f-420b-af08-13b30c215908 | toUInt32OrNull
.
toUInt64 {#touint64}
Converts an input value to a value of type
UInt64
. Throws an exception in case of an error.
Syntax
sql
toUInt64(expr)
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
.
Supported arguments:
- Values or string representations of type (U)Int8/16/32/64/128/256.
- Values of type Float32/64.
Unsupported types:
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toUInt64('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
UInt64
, the result over or under flows.
This is not considered an error.
For example:
SELECT toUInt64(18446744073709551616) == 0;
:::
Returned value
64-bit unsigned integer value.
UInt64
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toUInt64(64),
toUInt64(64.64),
toUInt64('64')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toUInt64(64): 64
toUInt64(64.64): 64
toUInt64('64'): 64
See also
toUInt64OrZero
.
toUInt64OrNull
.
toUInt64OrDefault
.
toUInt64OrZero {#touint64orzero}
Like
toUInt64
, this function converts an input value to a value of type
UInt64
but returns
0
in case of an error.
Syntax
sql
toUInt64OrZero(x)
Arguments
x
β A String representation of a number.
String
.
Supported arguments:
- String representations of (U)Int8/16/32/128/256.
Unsupported arguments (return
0
):
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toUInt64OrZero('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
UInt64
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
64-bit unsigned integer value if successful, otherwise
0
.
UInt64
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toUInt64OrZero('64'),
toUInt64OrZero('abc')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toUInt64OrZero('64'): 64
toUInt64OrZero('abc'): 0
See also
toUInt64
.
toUInt64OrNull
.
toUInt64OrDefault
.
toUInt64OrNull {#touint64ornull}
Like
toUInt64
, this function converts an input value to a value of type
UInt64
but returns
NULL
in case of an error.
Syntax
sql
toUInt64OrNull(x)
Arguments
x
β A String representation of a number.
Expression
/
String
.
Supported arguments:
- String representations of (U)Int8/16/32/128/256.
Unsupported arguments (return
\N
)
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toUInt64OrNull('0xc0fe');
. | {"source_file": "type-conversion-functions.md"} | [
0.0415244996547699,
-0.012093623168766499,
-0.05739172548055649,
0.031811781227588654,
-0.06776681542396545,
-0.006789781153202057,
0.05310248211026192,
0.047641072422266006,
-0.011248277500271797,
0.011018015444278717,
-0.03256290778517723,
-0.07865823060274124,
0.006854006089270115,
-0.0... |
446c25a4-ce89-4c56-b2e1-546f8224401b | :::note
If the input value cannot be represented within the bounds of
UInt64
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
64-bit unsigned integer value if successful, otherwise
NULL
.
UInt64
/
NULL
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toUInt64OrNull('64'),
toUInt64OrNull('abc')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toUInt64OrNull('64'): 64
toUInt64OrNull('abc'): α΄Ία΅α΄Έα΄Έ
See also
toUInt64
.
toUInt64OrZero
.
toUInt64OrDefault
.
toUInt64OrDefault {#touint64ordefault}
Like
toUInt64
, this function converts an input value to a value of type
UInt64
but returns the default value in case of an error.
If no
default
value is passed then
0
is returned in case of an error.
Syntax
sql
toUInt64OrDefault(expr[, default])
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
/
String
.
defauult
(optional) β The default value to return if parsing to type
UInt64
is unsuccessful.
UInt64
.
Supported arguments:
- Values or string representations of type (U)Int8/16/32/64/128/256.
- Values of type Float32/64.
Arguments for which the default value is returned:
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toUInt64OrDefault('0xc0fe', CAST('0', 'UInt64'));
.
:::note
If the input value cannot be represented within the bounds of
UInt64
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
64-bit unsigned integer value if successful, otherwise returns the default value if passed or
0
if not.
UInt64
.
:::note
- The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
- The default value type should be the same as the cast type.
:::
Example
Query:
sql
SELECT
toUInt64OrDefault('64', CAST('0', 'UInt64')),
toUInt64OrDefault('abc', CAST('0', 'UInt64'))
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toUInt64OrDefault('64', CAST('0', 'UInt64')): 64
toUInt64OrDefault('abc', CAST('0', 'UInt64')): 0
See also
toUInt64
.
toUInt64OrZero
.
toUInt64OrNull
.
toUInt128 {#touint128}
Converts an input value to a value of type
UInt128
. Throws an exception in case of an error.
Syntax
sql
toUInt128(expr)
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
.
Supported arguments:
- Values or string representations of type (U)Int8/16/32/64/128/256.
- Values of type Float32/64.
Unsupported arguments:
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toUInt128('0xc0fe');
. | {"source_file": "type-conversion-functions.md"} | [
0.03731410577893257,
0.045551903545856476,
-0.08457765728235245,
0.029042473062872887,
-0.0907464250922203,
0.013633825816214085,
0.017343441024422646,
0.060158923268318176,
-0.017484761774539948,
0.012671234086155891,
0.026389187201857567,
-0.04689069092273712,
0.03733162209391594,
-0.027... |
c9ac4dfc-14e4-474a-9ccb-a916f1c0b969 | Unsupported arguments:
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toUInt128('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
UInt128
, the result over or under flows.
This is not considered an error.
:::
Returned value
128-bit unsigned integer value.
UInt128
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toUInt128(128),
toUInt128(128.8),
toUInt128('128')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toUInt128(128): 128
toUInt128(128.8): 128
toUInt128('128'): 128
See also
toUInt128OrZero
.
toUInt128OrNull
.
toUInt128OrDefault
.
toUInt128OrZero {#touint128orzero}
Like
toUInt128
, this function converts an input value to a value of type
UInt128
but returns
0
in case of an error.
Syntax
sql
toUInt128OrZero(expr)
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
/
String
.
Supported arguments:
- String representations of (U)Int8/16/32/128/256.
Unsupported arguments (return
0
):
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toUInt128OrZero('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
UInt128
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
128-bit unsigned integer value if successful, otherwise
0
.
UInt128
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toUInt128OrZero('128'),
toUInt128OrZero('abc')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toUInt128OrZero('128'): 128
toUInt128OrZero('abc'): 0
See also
toUInt128
.
toUInt128OrNull
.
toUInt128OrDefault
.
toUInt128OrNull {#touint128ornull}
Like
toUInt128
, this function converts an input value to a value of type
UInt128
but returns
NULL
in case of an error.
Syntax
sql
toUInt128OrNull(x)
Arguments
x
β A String representation of a number.
Expression
/
String
.
Supported arguments:
- String representations of (U)Int8/16/32/128/256.
Unsupported arguments (return
\N
)
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toUInt128OrNull('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
UInt128
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
128-bit unsigned integer value if successful, otherwise
NULL
.
UInt128
/
NULL
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
::: | {"source_file": "type-conversion-functions.md"} | [
-0.03572045639157295,
-0.007452667690813541,
-0.09708590805530548,
-0.02224319614470005,
-0.0942721739411354,
-0.048024337738752365,
0.055887989699840546,
0.035430289804935455,
-0.029495490714907646,
-0.017798855900764465,
-0.0320611335337162,
-0.06672540307044983,
-0.02678872086107731,
-0... |
fa3d5df8-e27e-4fba-9cdf-cc739eb6ee19 | 128-bit unsigned integer value if successful, otherwise
NULL
.
UInt128
/
NULL
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toUInt128OrNull('128'),
toUInt128OrNull('abc')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toUInt128OrNull('128'): 128
toUInt128OrNull('abc'): α΄Ία΅α΄Έα΄Έ
See also
toUInt128
.
toUInt128OrZero
.
toUInt128OrDefault
.
toUInt128OrDefault {#touint128ordefault}
Like
toUInt128
, this function converts an input value to a value of type
UInt128
but returns the default value in case of an error.
If no
default
value is passed then
0
is returned in case of an error.
Syntax
sql
toUInt128OrDefault(expr[, default])
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
/
String
.
default
(optional) β The default value to return if parsing to type
UInt128
is unsuccessful.
UInt128
.
Supported arguments:
- (U)Int8/16/32/64/128/256.
- Float32/64.
- String representations of (U)Int8/16/32/128/256.
Arguments for which the default value is returned:
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toUInt128OrDefault('0xc0fe', CAST('0', 'UInt128'));
.
:::note
If the input value cannot be represented within the bounds of
UInt128
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
128-bit unsigned integer value if successful, otherwise returns the default value if passed or
0
if not.
UInt128
.
:::note
- The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
- The default value type should be the same as the cast type.
:::
Example
Query:
sql
SELECT
toUInt128OrDefault('128', CAST('0', 'UInt128')),
toUInt128OrDefault('abc', CAST('0', 'UInt128'))
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toUInt128OrDefault('128', CAST('0', 'UInt128')): 128
toUInt128OrDefault('abc', CAST('0', 'UInt128')): 0
See also
toUInt128
.
toUInt128OrZero
.
toUInt128OrNull
.
toUInt256 {#touint256}
Converts an input value to a value of type
UInt256
. Throws an exception in case of an error.
Syntax
sql
toUInt256(expr)
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
.
Supported arguments:
- Values or string representations of type (U)Int8/16/32/64/128/256.
- Values of type Float32/64.
Unsupported arguments:
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toUInt256('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
UInt256
, the result over or under flows.
This is not considered an error.
:::
Returned value | {"source_file": "type-conversion-functions.md"} | [
-0.014498609118163586,
0.0549965538084507,
-0.08489032089710236,
0.027604056522250175,
-0.09827534109354019,
0.02686283178627491,
0.06577225029468536,
0.08819124102592468,
-0.03384925797581673,
-0.01319891307502985,
-0.018349986523389816,
-0.049014341086149216,
0.013583197258412838,
-0.013... |
6e639616-20e7-47d7-9385-1aa9ec043d2d | :::note
If the input value cannot be represented within the bounds of
UInt256
, the result over or under flows.
This is not considered an error.
:::
Returned value
256-bit unsigned integer value.
Int256
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toUInt256(256),
toUInt256(256.256),
toUInt256('256')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toUInt256(256): 256
toUInt256(256.256): 256
toUInt256('256'): 256
See also
toUInt256OrZero
.
toUInt256OrNull
.
toUInt256OrDefault
.
toUInt256OrZero {#touint256orzero}
Like
toUInt256
, this function converts an input value to a value of type
UInt256
but returns
0
in case of an error.
Syntax
sql
toUInt256OrZero(x)
Arguments
x
β A String representation of a number.
String
.
Supported arguments:
- String representations of (U)Int8/16/32/128/256.
Unsupported arguments (return
0
):
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toUInt256OrZero('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
UInt256
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
256-bit unsigned integer value if successful, otherwise
0
.
UInt256
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toUInt256OrZero('256'),
toUInt256OrZero('abc')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toUInt256OrZero('256'): 256
toUInt256OrZero('abc'): 0
See also
toUInt256
.
toUInt256OrNull
.
toUInt256OrDefault
.
toUInt256OrNull {#touint256ornull}
Like
toUInt256
, this function converts an input value to a value of type
UInt256
but returns
NULL
in case of an error.
Syntax
sql
toUInt256OrNull(x)
Arguments
x
β A String representation of a number.
String
.
Supported arguments:
- String representations of (U)Int8/16/32/128/256.
Unsupported arguments (return
\N
)
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toUInt256OrNull('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
UInt256
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
256-bit unsigned integer value if successful, otherwise
NULL
.
UInt256
/
NULL
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toUInt256OrNull('256'),
toUInt256OrNull('abc')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toUInt256OrNull('256'): 256
toUInt256OrNull('abc'): α΄Ία΅α΄Έα΄Έ
See also
toUInt256
.
toUInt256OrZero
. | {"source_file": "type-conversion-functions.md"} | [
-0.014881783165037632,
-0.022871797904372215,
-0.08354609459638596,
0.028353579342365265,
-0.07354146987199783,
-0.06301148980855942,
0.06950099021196365,
0.005154894664883614,
-0.012802865356206894,
-0.028487352654337883,
-0.00962084624916315,
-0.04014132544398308,
0.010829021222889423,
-... |
c34a4be0-df25-4b0a-971a-0467259e43bd | Result:
response
Row 1:
ββββββ
toUInt256OrNull('256'): 256
toUInt256OrNull('abc'): α΄Ία΅α΄Έα΄Έ
See also
toUInt256
.
toUInt256OrZero
.
toUInt256OrDefault
.
toUInt256OrDefault {#touint256ordefault}
Like
toUInt256
, this function converts an input value to a value of type
UInt256
but returns the default value in case of an error.
If no
default
value is passed then
0
is returned in case of an error.
Syntax
sql
toUInt256OrDefault(expr[, default])
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
/
String
.
default
(optional) β The default value to return if parsing to type
UInt256
is unsuccessful.
UInt256
.
Supported arguments:
- Values or string representations of type (U)Int8/16/32/64/128/256.
- Values of type Float32/64.
Arguments for which the default value is returned:
- String representations of Float32/64 values, including
NaN
and
Inf
- String representations of binary and hexadecimal values, e.g.
SELECT toUInt256OrDefault('0xc0fe', CAST('0', 'UInt256'));
:::note
If the input value cannot be represented within the bounds of
UInt256
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
256-bit unsigned integer value if successful, otherwise returns the default value if passed or
0
if not.
UInt256
.
:::note
- The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
- The default value type should be the same as the cast type.
:::
Example
Query:
sql
SELECT
toUInt256OrDefault('-256', CAST('0', 'UInt256')),
toUInt256OrDefault('abc', CAST('0', 'UInt256'))
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toUInt256OrDefault('-256', CAST('0', 'UInt256')): 0
toUInt256OrDefault('abc', CAST('0', 'UInt256')): 0
See also
toUInt256
.
toUInt256OrZero
.
toUInt256OrNull
.
toFloat32 {#tofloat32}
Converts an input value to a value of type
Float32
. Throws an exception in case of an error.
Syntax
sql
toFloat32(expr)
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
.
Supported arguments:
- Values of type (U)Int8/16/32/64/128/256.
- String representations of (U)Int8/16/32/128/256.
- Values of type Float32/64, including
NaN
and
Inf
.
- String representations of Float32/64, including
NaN
and
Inf
(case-insensitive).
Unsupported arguments:
- String representations of binary and hexadecimal values, e.g.
SELECT toFloat32('0xc0fe');
.
Returned value
32-bit floating point value.
Float32
.
Example
Query:
sql
SELECT
toFloat32(42.7),
toFloat32('42.7'),
toFloat32('NaN')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toFloat32(42.7): 42.7
toFloat32('42.7'): 42.7
toFloat32('NaN'): nan
See also
toFloat32OrZero
.
toFloat32OrNull
.
toFloat32OrDefault
.
toFloat32OrZero {#tofloat32orzero} | {"source_file": "type-conversion-functions.md"} | [
-0.0015404478181153536,
-0.038038481026887894,
-0.08339665085077286,
0.04487711936235428,
-0.10096704959869385,
0.004359452053904533,
0.08062195032835007,
0.022679220885038376,
-0.05592004582285881,
0.0021005456801503897,
0.019452201202511787,
-0.06555657833814621,
0.042222145944833755,
-0... |
bcc36fe1-7c6d-4f7a-9a9b-8e23dbbfcb00 | See also
toFloat32OrZero
.
toFloat32OrNull
.
toFloat32OrDefault
.
toFloat32OrZero {#tofloat32orzero}
Like
toFloat32
, this function converts an input value to a value of type
Float32
but returns
0
in case of an error.
Syntax
sql
toFloat32OrZero(x)
Arguments
x
β A String representation of a number.
String
.
Supported arguments:
- String representations of (U)Int8/16/32/128/256, Float32/64.
Unsupported arguments (return
0
):
- String representations of binary and hexadecimal values, e.g.
SELECT toFloat32OrZero('0xc0fe');
.
Returned value
32-bit Float value if successful, otherwise
0
.
Float32
.
Example
Query:
sql
SELECT
toFloat32OrZero('42.7'),
toFloat32OrZero('abc')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toFloat32OrZero('42.7'): 42.7
toFloat32OrZero('abc'): 0
See also
toFloat32
.
toFloat32OrNull
.
toFloat32OrDefault
.
toFloat32OrNull {#tofloat32ornull}
Like
toFloat32
, this function converts an input value to a value of type
Float32
but returns
NULL
in case of an error.
Syntax
sql
toFloat32OrNull(x)
Arguments
x
β A String representation of a number.
String
.
Supported arguments:
- String representations of (U)Int8/16/32/128/256, Float32/64.
Unsupported arguments (return
\N
):
- String representations of binary and hexadecimal values, e.g.
SELECT toFloat32OrNull('0xc0fe');
.
Returned value
32-bit Float value if successful, otherwise
\N
.
Float32
.
Example
Query:
sql
SELECT
toFloat32OrNull('42.7'),
toFloat32OrNull('abc')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toFloat32OrNull('42.7'): 42.7
toFloat32OrNull('abc'): α΄Ία΅α΄Έα΄Έ
See also
toFloat32
.
toFloat32OrZero
.
toFloat32OrDefault
.
toFloat32OrDefault {#tofloat32ordefault}
Like
toFloat32
, this function converts an input value to a value of type
Float32
but returns the default value in case of an error.
If no
default
value is passed then
0
is returned in case of an error.
Syntax
sql
toFloat32OrDefault(expr[, default])
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
/
String
.
default
(optional) β The default value to return if parsing to type
Float32
is unsuccessful.
Float32
.
Supported arguments:
- Values of type (U)Int8/16/32/64/128/256.
- String representations of (U)Int8/16/32/128/256.
- Values of type Float32/64, including
NaN
and
Inf
.
- String representations of Float32/64, including
NaN
and
Inf
(case-insensitive).
Arguments for which the default value is returned:
- String representations of binary and hexadecimal values, e.g.
SELECT toFloat32OrDefault('0xc0fe', CAST('0', 'Float32'));
.
Returned value
32-bit Float value if successful, otherwise returns the default value if passed or
0
if not.
Float32
.
Example
Query: | {"source_file": "type-conversion-functions.md"} | [
0.05932240933179855,
-0.021244218572974205,
-0.108571857213974,
0.04274049028754234,
-0.04418244957923889,
-0.0026132476050406694,
0.05194547772407532,
0.03532138839364052,
-0.02788240648806095,
-0.024391787126660347,
-0.04887320101261139,
-0.1583203226327896,
0.021053120493888855,
0.02773... |
ee932918-5af0-4041-b99d-b9a2cb0ed291 | Returned value
32-bit Float value if successful, otherwise returns the default value if passed or
0
if not.
Float32
.
Example
Query:
sql
SELECT
toFloat32OrDefault('8', CAST('0', 'Float32')),
toFloat32OrDefault('abc', CAST('0', 'Float32'))
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toFloat32OrDefault('8', CAST('0', 'Float32')): 8
toFloat32OrDefault('abc', CAST('0', 'Float32')): 0
See also
toFloat32
.
toFloat32OrZero
.
toFloat32OrNull
.
toFloat64 {#tofloat64}
Converts an input value to a value of type
Float64
. Throws an exception in case of an error.
Syntax
sql
toFloat64(expr)
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
.
Supported arguments:
- Values of type (U)Int8/16/32/64/128/256.
- String representations of (U)Int8/16/32/128/256.
- Values of type Float32/64, including
NaN
and
Inf
.
- String representations of type Float32/64, including
NaN
and
Inf
(case-insensitive).
Unsupported arguments:
- String representations of binary and hexadecimal values, e.g.
SELECT toFloat64('0xc0fe');
.
Returned value
64-bit floating point value.
Float64
.
Example
Query:
sql
SELECT
toFloat64(42.7),
toFloat64('42.7'),
toFloat64('NaN')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toFloat64(42.7): 42.7
toFloat64('42.7'): 42.7
toFloat64('NaN'): nan
See also
toFloat64OrZero
.
toFloat64OrNull
.
toFloat64OrDefault
.
toFloat64OrZero {#tofloat64orzero}
Like
toFloat64
, this function converts an input value to a value of type
Float64
but returns
0
in case of an error.
Syntax
sql
toFloat64OrZero(x)
Arguments
x
β A String representation of a number.
String
.
Supported arguments:
- String representations of (U)Int8/16/32/128/256, Float32/64.
Unsupported arguments (return
0
):
- String representations of binary and hexadecimal values, e.g.
SELECT toFloat64OrZero('0xc0fe');
.
Returned value
64-bit Float value if successful, otherwise
0
.
Float64
.
Example
Query:
sql
SELECT
toFloat64OrZero('42.7'),
toFloat64OrZero('abc')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toFloat64OrZero('42.7'): 42.7
toFloat64OrZero('abc'): 0
See also
toFloat64
.
toFloat64OrNull
.
toFloat64OrDefault
.
toFloat64OrNull {#tofloat64ornull}
Like
toFloat64
, this function converts an input value to a value of type
Float64
but returns
NULL
in case of an error.
Syntax
sql
toFloat64OrNull(x)
Arguments
x
β A String representation of a number.
String
.
Supported arguments:
- String representations of (U)Int8/16/32/128/256, Float32/64.
Unsupported arguments (return
\N
):
- String representations of binary and hexadecimal values, e.g.
SELECT toFloat64OrNull('0xc0fe');
.
Returned value
64-bit Float value if successful, otherwise
\N
.
Float64
.
Example
Query: | {"source_file": "type-conversion-functions.md"} | [
0.04165717959403992,
-0.01137965265661478,
-0.09170440584421158,
0.051064129918813705,
-0.05275777354836464,
-0.025973951444029808,
0.07087831199169159,
0.04483768716454506,
-0.026055358350276947,
0.0016159198712557554,
-0.027674634009599686,
-0.12125419080257416,
0.0046236105263233185,
0.... |
7f633035-15a8-4218-af7d-c6e3e6fe6559 | Returned value
64-bit Float value if successful, otherwise
\N
.
Float64
.
Example
Query:
sql
SELECT
toFloat64OrNull('42.7'),
toFloat64OrNull('abc')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toFloat64OrNull('42.7'): 42.7
toFloat64OrNull('abc'): α΄Ία΅α΄Έα΄Έ
See also
toFloat64
.
toFloat64OrZero
.
toFloat64OrDefault
.
toFloat64OrDefault {#tofloat64ordefault}
Like
toFloat64
, this function converts an input value to a value of type
Float64
but returns the default value in case of an error.
If no
default
value is passed then
0
is returned in case of an error.
Syntax
sql
toFloat64OrDefault(expr[, default])
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
/
String
.
default
(optional) β The default value to return if parsing to type
Float64
is unsuccessful.
Float64
.
Supported arguments:
- Values of type (U)Int8/16/32/64/128/256.
- String representations of (U)Int8/16/32/128/256.
- Values of type Float32/64, including
NaN
and
Inf
.
- String representations of Float32/64, including
NaN
and
Inf
(case-insensitive).
Arguments for which the default value is returned:
- String representations of binary and hexadecimal values, e.g.
SELECT toFloat64OrDefault('0xc0fe', CAST('0', 'Float64'));
.
Returned value
64-bit Float value if successful, otherwise returns the default value if passed or
0
if not.
Float64
.
Example
Query:
sql
SELECT
toFloat64OrDefault('8', CAST('0', 'Float64')),
toFloat64OrDefault('abc', CAST('0', 'Float64'))
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toFloat64OrDefault('8', CAST('0', 'Float64')): 8
toFloat64OrDefault('abc', CAST('0', 'Float64')): 0
See also
toFloat64
.
toFloat64OrZero
.
toFloat64OrNull
.
toBFloat16 {#tobfloat16}
Converts an input value to a value of type
BFloat16
.
Throws an exception in case of an error.
Syntax
sql
toBFloat16(expr)
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
.
Supported arguments:
- Values of type (U)Int8/16/32/64/128/256.
- String representations of (U)Int8/16/32/128/256.
- Values of type Float32/64, including
NaN
and
Inf
.
- String representations of Float32/64, including
NaN
and
Inf
(case-insensitive).
Returned value
16-bit brain-float value.
BFloat16
.
Example
```sql
SELECT toBFloat16(toFloat32(42.7))
42.5
SELECT toBFloat16(toFloat32('42.7'));
42.5
SELECT toBFloat16('42.7');
42.5
```
See also
toBFloat16OrZero
.
toBFloat16OrNull
.
toBFloat16OrZero {#tobfloat16orzero}
Converts a String input value to a value of type
BFloat16
.
If the string does not represent a floating point value, the function returns zero.
Syntax
sql
toBFloat16OrZero(x)
Arguments
x
β A String representation of a number.
String
.
Supported arguments:
String representations of numeric values. | {"source_file": "type-conversion-functions.md"} | [
0.047373753041028976,
0.011522959917783737,
-0.06971390545368195,
0.059470873326063156,
-0.05791525915265083,
-0.01091083511710167,
0.03578953817486763,
0.05211373418569565,
-0.03727710247039795,
0.004440201446413994,
-0.015149257145822048,
-0.10210749506950378,
0.009367816150188446,
0.014... |
7854671f-489d-4a80-9c3e-83f17b65670f | Syntax
sql
toBFloat16OrZero(x)
Arguments
x
β A String representation of a number.
String
.
Supported arguments:
String representations of numeric values.
Unsupported arguments (return
0
):
String representations of binary and hexadecimal values.
Numeric values.
Returned value
16-bit brain-float value, otherwise
0
.
BFloat16
.
:::note
The function allows a silent loss of precision while converting from the string representation.
:::
Example
```sql
SELECT toBFloat16OrZero('0x5E'); -- unsupported arguments
0
SELECT toBFloat16OrZero('12.3'); -- typical use
12.25
SELECT toBFloat16OrZero('12.3456789');
12.3125 -- silent loss of precision
```
See also
toBFloat16
.
toBFloat16OrNull
.
toBFloat16OrNull {#tobfloat16ornull}
Converts a String input value to a value of type
BFloat16
but if the string does not represent a floating point value, the function returns
NULL
.
Syntax
sql
toBFloat16OrNull(x)
Arguments
x
β A String representation of a number.
String
.
Supported arguments:
String representations of numeric values.
Unsupported arguments (return
NULL
):
String representations of binary and hexadecimal values.
Numeric values.
Returned value
16-bit brain-float value, otherwise
NULL
(
\N
).
BFloat16
.
:::note
The function allows a silent loss of precision while converting from the string representation.
:::
Example
```sql
SELECT toBFloat16OrNull('0x5E'); -- unsupported arguments
\N
SELECT toBFloat16OrNull('12.3'); -- typical use
12.25
SELECT toBFloat16OrNull('12.3456789');
12.3125 -- silent loss of precision
```
See also
toBFloat16
.
toBFloat16OrZero
.
toDate {#todate}
Converts the argument to
Date
data type.
If the argument is
DateTime
or
DateTime64
, it truncates it and leaves the date component of the DateTime:
sql
SELECT
now() AS x,
toDate(x)
response
ββββββββββββββββββββxββ¬βtoDate(now())ββ
β 2022-12-30 13:44:17 β 2022-12-30 β
βββββββββββββββββββββββ΄ββββββββββββββββ
If the argument is a
String
, it is parsed as
Date
or
DateTime
. If it was parsed as
DateTime
, the date component is being used:
sql
SELECT
toDate('2022-12-30') AS x,
toTypeName(x)
```response
βββββββββββxββ¬βtoTypeName(toDate('2022-12-30'))ββ
β 2022-12-30 β Date β
ββββββββββββββ΄βββββββββββββββββββββββββββββββββββ
1 row in set. Elapsed: 0.001 sec.
```
sql
SELECT
toDate('2022-12-30 01:02:03') AS x,
toTypeName(x)
response
βββββββββββxββ¬βtoTypeName(toDate('2022-12-30 01:02:03'))ββ
β 2022-12-30 β Date β
ββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββ | {"source_file": "type-conversion-functions.md"} | [
0.07794695347547531,
-0.003356197150424123,
-0.1409878432750702,
-0.027234183624386787,
-0.04152454063296318,
-0.01027920376509428,
0.07864070683717728,
0.03951304778456688,
-0.05822686851024628,
-0.011030995287001133,
-0.0609847754240036,
-0.09091495722532272,
-0.027652105316519737,
-0.01... |
0579750e-1bd5-4619-99a8-d478f1f13564 | response
βββββββββββxββ¬βtoTypeName(toDate('2022-12-30 01:02:03'))ββ
β 2022-12-30 β Date β
ββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββ
If the argument is a number and looks like a UNIX timestamp (is greater than 65535), it is interpreted as a
DateTime
, then truncated to
Date
in the current timezone. The timezone argument can be specified as a second argument of the function. The truncation to
Date
depends on the timezone:
sql
SELECT
now() AS current_time,
toUnixTimestamp(current_time) AS ts,
toDateTime(ts) AS time_Amsterdam,
toDateTime(ts, 'Pacific/Apia') AS time_Samoa,
toDate(time_Amsterdam) AS date_Amsterdam,
toDate(time_Samoa) AS date_Samoa,
toDate(ts) AS date_Amsterdam_2,
toDate(ts, 'Pacific/Apia') AS date_Samoa_2
response
Row 1:
ββββββ
current_time: 2022-12-30 13:51:54
ts: 1672404714
time_Amsterdam: 2022-12-30 13:51:54
time_Samoa: 2022-12-31 01:51:54
date_Amsterdam: 2022-12-30
date_Samoa: 2022-12-31
date_Amsterdam_2: 2022-12-30
date_Samoa_2: 2022-12-31
The example above demonstrates how the same UNIX timestamp can be interpreted as different dates in different time zones.
If the argument is a number and it is smaller than 65536, it is interpreted as the number of days since 1970-01-01 (the first UNIX day) and converted to
Date
. It corresponds to the internal numeric representation of the
Date
data type. Example:
sql
SELECT toDate(12345)
response
ββtoDate(12345)ββ
β 2003-10-20 β
βββββββββββββββββ
This conversion does not depend on timezones.
If the argument does not fit in the range of the Date type, it results in an implementation-defined behavior, that can saturate to the maximum supported date or overflow:
sql
SELECT toDate(10000000000.)
response
ββtoDate(10000000000.)ββ
β 2106-02-07 β
ββββββββββββββββββββββββ
The function
toDate
can be also written in alternative forms:
sql
SELECT
now() AS time,
toDate(time),
DATE(time),
CAST(time, 'Date')
response
βββββββββββββββββtimeββ¬βtoDate(now())ββ¬βDATE(now())ββ¬βCAST(now(), 'Date')ββ
β 2022-12-30 13:54:58 β 2022-12-30 β 2022-12-30 β 2022-12-30 β
βββββββββββββββββββββββ΄ββββββββββββββββ΄ββββββββββββββ΄ββββββββββββββββββββββ
toDateOrZero {#todateorzero}
The same as
toDate
but returns lower boundary of
Date
if an invalid argument is received. Only
String
argument is supported.
Example
Query:
sql
SELECT toDateOrZero('2022-12-30'), toDateOrZero('');
Result:
response
ββtoDateOrZero('2022-12-30')ββ¬βtoDateOrZero('')ββ
β 2022-12-30 β 1970-01-01 β
ββββββββββββββββββββββββββββββ΄βββββββββββββββββββ
toDateOrNull {#todateornull}
The same as
toDate
but returns
NULL
if an invalid argument is received. Only
String
argument is supported.
Example
Query:
sql
SELECT toDateOrNull('2022-12-30'), toDateOrNull('');
Result: | {"source_file": "type-conversion-functions.md"} | [
0.05514129623770714,
0.012570692226290703,
0.0015588946407660842,
0.022389007732272148,
-0.01103124674409628,
-0.07592325657606125,
-0.036015357822179794,
0.010896120220422745,
-0.01768370345234871,
0.05302363634109497,
-0.013934055343270302,
-0.11051897704601288,
-0.03985612839460373,
0.0... |
d7e1dd10-d6dd-4c51-b2d8-8b38e533797a | Example
Query:
sql
SELECT toDateOrNull('2022-12-30'), toDateOrNull('');
Result:
response
ββtoDateOrNull('2022-12-30')ββ¬βtoDateOrNull('')ββ
β 2022-12-30 β α΄Ία΅α΄Έα΄Έ β
ββββββββββββββββββββββββββββββ΄βββββββββββββββββββ
toDateOrDefault {#todateordefault}
Like
toDate
but if unsuccessful, returns a default value which is either the second argument (if specified), or otherwise the lower boundary of
Date
.
Syntax
sql
toDateOrDefault(expr [, default_value])
Example
Query:
sql
SELECT toDateOrDefault('2022-12-30'), toDateOrDefault('', '2023-01-01'::Date);
Result:
response
ββtoDateOrDefault('2022-12-30')ββ¬βtoDateOrDefault('', CAST('2023-01-01', 'Date'))ββ
β 2022-12-30 β 2023-01-01 β
βββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββ
toDateTime {#todatetime}
Converts an input value to
DateTime
.
Syntax
sql
toDateTime(expr[, time_zone ])
Arguments
expr
β The value.
String
,
Int
,
Date
or
DateTime
.
time_zone
β Time zone.
String
.
:::note
If
expr
is a number, it is interpreted as the number of seconds since the beginning of the Unix Epoch (as Unix timestamp).
If
expr
is a
String
, it may be interpreted as a Unix timestamp or as a string representation of date / date with time.
Thus, parsing of short numbers' string representations (up to 4 digits) is explicitly disabled due to ambiguity, e.g. a string
'1999'
may be both a year (an incomplete string representation of Date / DateTime) or a unix timestamp. Longer numeric strings are allowed.
:::
Returned value
A date time.
DateTime
Example
Query:
sql
SELECT toDateTime('2022-12-30 13:44:17'), toDateTime(1685457500, 'UTC');
Result:
response
ββtoDateTime('2022-12-30 13:44:17')ββ¬βtoDateTime(1685457500, 'UTC')ββ
β 2022-12-30 13:44:17 β 2023-05-30 14:38:20 β
βββββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ
toDateTimeOrZero {#todatetimeorzero}
The same as
toDateTime
but returns lower boundary of
DateTime
if an invalid argument is received. Only
String
argument is supported.
Example
Query:
sql
SELECT toDateTimeOrZero('2022-12-30 13:44:17'), toDateTimeOrZero('');
Result:
response
ββtoDateTimeOrZero('2022-12-30 13:44:17')ββ¬βtoDateTimeOrZero('')ββ
β 2022-12-30 13:44:17 β 1970-01-01 00:00:00 β
βββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββ
toDateTimeOrNull {#todatetimeornull}
The same as
toDateTime
but returns
NULL
if an invalid argument is received. Only
String
argument is supported.
Example
Query:
sql
SELECT toDateTimeOrNull('2022-12-30 13:44:17'), toDateTimeOrNull('');
Result:
response
ββtoDateTimeOrNull('2022-12-30 13:44:17')ββ¬βtoDateTimeOrNull('')ββ
β 2022-12-30 13:44:17 β α΄Ία΅α΄Έα΄Έ β
βββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββ | {"source_file": "type-conversion-functions.md"} | [
0.012510137632489204,
-0.009687935002148151,
0.023110654205083847,
0.055267807096242905,
-0.019563432782888412,
-0.0196291022002697,
0.07495933026075363,
0.0688689798116684,
-0.01751934178173542,
0.031644050031900406,
-0.02044752798974514,
-0.10860752314329147,
-0.05231299623847008,
0.0276... |
b6759ff4-11c9-455b-894c-893a4b8bc3ea | toDateTimeOrDefault {#todatetimeordefault}
Like
toDateTime
but if unsuccessful, returns a default value which is either the third argument (if specified), or otherwise the lower boundary of
DateTime
.
Syntax
sql
toDateTimeOrDefault(expr [, time_zone [, default_value]])
Example
Query:
sql
SELECT toDateTimeOrDefault('2022-12-30 13:44:17'), toDateTimeOrDefault('', 'UTC', '2023-01-01'::DateTime('UTC'));
Result:
response
ββtoDateTimeOrDefault('2022-12-30 13:44:17')ββ¬βtoDateTimeOrDefault('', 'UTC', CAST('2023-01-01', 'DateTime(\'UTC\')'))ββ
β 2022-12-30 13:44:17 β 2023-01-01 00:00:00 β
ββββββββββββββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
toDate32 {#todate32}
Converts the argument to the
Date32
data type. If the value is outside the range,
toDate32
returns the border values supported by
Date32
. If the argument has
Date
type, it's borders are taken into account.
Syntax
sql
toDate32(expr)
Arguments
expr
β The value.
String
,
UInt32
or
Date
.
Returned value
A calendar date. Type
Date32
.
Example
The value is within the range:
sql
SELECT toDate32('1955-01-01') AS value, toTypeName(value);
response
βββββββvalueββ¬βtoTypeName(toDate32('1925-01-01'))ββ
β 1955-01-01 β Date32 β
ββββββββββββββ΄βββββββββββββββββββββββββββββββββββββ
The value is outside the range:
sql
SELECT toDate32('1899-01-01') AS value, toTypeName(value);
response
βββββββvalueββ¬βtoTypeName(toDate32('1899-01-01'))ββ
β 1900-01-01 β Date32 β
ββββββββββββββ΄βββββββββββββββββββββββββββββββββββββ
With
Date
argument:
sql
SELECT toDate32(toDate('1899-01-01')) AS value, toTypeName(value);
response
βββββββvalueββ¬βtoTypeName(toDate32(toDate('1899-01-01')))ββ
β 1970-01-01 β Date32 β
ββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββ
toDate32OrZero {#todate32orzero}
The same as
toDate32
but returns the min value of
Date32
if an invalid argument is received.
Example
Query:
sql
SELECT toDate32OrZero('1899-01-01'), toDate32OrZero('');
Result:
response
ββtoDate32OrZero('1899-01-01')ββ¬βtoDate32OrZero('')ββ
β 1900-01-01 β 1900-01-01 β
ββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββ
toDate32OrNull {#todate32ornull}
The same as
toDate32
but returns
NULL
if an invalid argument is received.
Example
Query:
sql
SELECT toDate32OrNull('1955-01-01'), toDate32OrNull('');
Result:
response
ββtoDate32OrNull('1955-01-01')ββ¬βtoDate32OrNull('')ββ
β 1955-01-01 β α΄Ία΅α΄Έα΄Έ β
ββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββ
toDate32OrDefault {#todate32ordefault} | {"source_file": "type-conversion-functions.md"} | [
-0.0029042272362858057,
0.007528895512223244,
-0.011533990502357483,
0.02030596323311329,
0.04987327754497528,
-0.0270627923309803,
0.06918121129274368,
0.027369262650609016,
-0.03576740249991417,
0.012356352992355824,
-0.06557580828666687,
-0.13139976561069489,
-0.06012377515435219,
0.048... |
370547cf-e44f-4d14-8fa2-b887eac6fb08 | toDate32OrDefault {#todate32ordefault}
Converts the argument to the
Date32
data type. If the value is outside the range,
toDate32OrDefault
returns the lower border value supported by
Date32
. If the argument has
Date
type, it's borders are taken into account. Returns default value if an invalid argument is received.
Example
Query:
sql
SELECT
toDate32OrDefault('1930-01-01', toDate32('2020-01-01')),
toDate32OrDefault('xx1930-01-01', toDate32('2020-01-01'));
Result:
response
ββtoDate32OrDefault('1930-01-01', toDate32('2020-01-01'))ββ¬βtoDate32OrDefault('xx1930-01-01', toDate32('2020-01-01'))ββ
β 1930-01-01 β 2020-01-01 β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
toDateTime64 {#todatetime64}
Converts an input value to a value of type
DateTime64
.
Syntax
sql
toDateTime64(expr, scale, [timezone])
Arguments
expr
β The value.
String
,
UInt32
,
Float
or
DateTime
.
scale
- Tick size (precision): 10
-precision
seconds. Valid range: [ 0 : 9 ].
timezone
(optional) - Time zone of the specified datetime64 object.
Returned value
A calendar date and time of day, with sub-second precision.
DateTime64
.
Example
The value is within the range:
sql
SELECT toDateTime64('1955-01-01 00:00:00.000', 3) AS value, toTypeName(value);
response
ββββββββββββββββββββvalueββ¬βtoTypeName(toDateTime64('1955-01-01 00:00:00.000', 3))ββ
β 1955-01-01 00:00:00.000 β DateTime64(3) β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
As decimal with precision:
sql
SELECT toDateTime64(1546300800.000, 3) AS value, toTypeName(value);
response
ββββββββββββββββββββvalueββ¬βtoTypeName(toDateTime64(1546300800., 3))ββ
β 2019-01-01 00:00:00.000 β DateTime64(3) β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββ
Without the decimal point the value is still treated as Unix Timestamp in seconds:
sql
SELECT toDateTime64(1546300800000, 3) AS value, toTypeName(value);
response
ββββββββββββββββββββvalueββ¬βtoTypeName(toDateTime64(1546300800000, 3))ββ
β 2282-12-31 00:00:00.000 β DateTime64(3) β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββ
With
timezone
:
sql
SELECT toDateTime64('2019-01-01 00:00:00', 3, 'Asia/Istanbul') AS value, toTypeName(value);
response
ββββββββββββββββββββvalueββ¬βtoTypeName(toDateTime64('2019-01-01 00:00:00', 3, 'Asia/Istanbul'))ββ
β 2019-01-01 00:00:00.000 β DateTime64(3, 'Asia/Istanbul') β
βββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
toDateTime64OrZero {#todatetime64orzero} | {"source_file": "type-conversion-functions.md"} | [
0.03355613350868225,
0.01953968219459057,
-0.016932407394051552,
0.06775535643100739,
-0.004583093803375959,
0.004798792768269777,
0.07333707809448242,
0.04103480651974678,
-0.06510695070028305,
0.015890808776021004,
-0.04113851860165596,
-0.12995676696300507,
-0.04822592809796333,
0.03445... |
f23d37c9-ebcd-43ed-acb8-384d6f5edc96 | toDateTime64OrZero {#todatetime64orzero}
Like
toDateTime64
, this function converts an input value to a value of type
DateTime64
but returns the min value of
DateTime64
if an invalid argument is received.
Syntax
sql
toDateTime64OrZero(expr, scale, [timezone])
Arguments
expr
β The value.
String
,
UInt32
,
Float
or
DateTime
.
scale
- Tick size (precision): 10
-precision
seconds. Valid range: [ 0 : 9 ].
timezone
(optional) - Time zone of the specified DateTime64 object.
Returned value
A calendar date and time of day, with sub-second precision, otherwise the minimum value of
DateTime64
:
1970-01-01 01:00:00.000
.
DateTime64
.
Example
Query:
sql
SELECT toDateTime64OrZero('2008-10-12 00:00:00 00:30:30', 3) AS invalid_arg
Result:
response
ββββββββββββββinvalid_argββ
β 1970-01-01 01:00:00.000 β
βββββββββββββββββββββββββββ
See also
toDateTime64
.
toDateTime64OrNull
.
toDateTime64OrDefault
.
toDateTime64OrNull {#todatetime64ornull}
Like
toDateTime64
, this function converts an input value to a value of type
DateTime64
but returns
NULL
if an invalid argument is received.
Syntax
sql
toDateTime64OrNull(expr, scale, [timezone])
Arguments
expr
β The value.
String
,
UInt32
,
Float
or
DateTime
.
scale
- Tick size (precision): 10
-precision
seconds. Valid range: [ 0 : 9 ].
timezone
(optional) - Time zone of the specified DateTime64 object.
Returned value
A calendar date and time of day, with sub-second precision, otherwise
NULL
.
DateTime64
/
NULL
.
Example
Query:
sql
SELECT
toDateTime64OrNull('1976-10-18 00:00:00.30', 3) AS valid_arg,
toDateTime64OrNull('1976-10-18 00:00:00 30', 3) AS invalid_arg
Result:
response
ββββββββββββββββvalid_argββ¬βinvalid_argββ
β 1976-10-18 00:00:00.300 β α΄Ία΅α΄Έα΄Έ β
βββββββββββββββββββββββββββ΄ββββββββββββββ
See also
toDateTime64
.
toDateTime64OrZero
.
toDateTime64OrDefault
.
toDateTime64OrDefault {#todatetime64ordefault}
Like
toDateTime64
, this function converts an input value to a value of type
DateTime64
,
but returns either the default value of
DateTime64
or the provided default if an invalid argument is received.
Syntax
sql
toDateTime64OrNull(expr, scale, [timezone, default])
Arguments
expr
β The value.
String
,
UInt32
,
Float
or
DateTime
.
scale
- Tick size (precision): 10
-precision
seconds. Valid range: [ 0 : 9 ].
timezone
(optional) - Time zone of the specified DateTime64 object.
default
(optional) - Default value to return if an invalid argument is received.
DateTime64
.
Returned value
A calendar date and time of day, with sub-second precision, otherwise the minimum value of
DateTime64
or the
default
value if provided.
DateTime64
.
Example
Query: | {"source_file": "type-conversion-functions.md"} | [
0.034723762422800064,
0.03662559390068054,
-0.050628043711185455,
0.05912911891937256,
-0.046343762427568436,
-0.0010574812768027186,
0.0318564772605896,
0.05463868007063866,
-0.01715938188135624,
-0.021906962618231773,
-0.04983248561620712,
-0.15563105046749115,
-0.05557551234960556,
0.04... |
5c1f260b-c876-4574-8445-7f7de35ddd02 | Returned value
A calendar date and time of day, with sub-second precision, otherwise the minimum value of
DateTime64
or the
default
value if provided.
DateTime64
.
Example
Query:
sql
SELECT
toDateTime64OrDefault('1976-10-18 00:00:00 30', 3) AS invalid_arg,
toDateTime64OrDefault('1976-10-18 00:00:00 30', 3, 'UTC', toDateTime64('2001-01-01 00:00:00.00',3)) AS invalid_arg_with_default
Result:
response
ββββββββββββββinvalid_argββ¬βinvalid_arg_with_defaultββ
β 1970-01-01 01:00:00.000 β 2000-12-31 23:00:00.000 β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββ
See also
toDateTime64
.
toDateTime64OrZero
.
toDateTime64OrNull
.
toDecimal32 {#todecimal32}
Converts an input value to a value of type
Decimal(9, S)
with scale of
S
. Throws an exception in case of an error.
Syntax
sql
toDecimal32(expr, S)
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
.
S
β Scale parameter between 0 and 9, specifying how many digits the fractional part of a number can have.
UInt8
.
Supported arguments:
- Values or string representations of type (U)Int8/16/32/64/128/256.
- Values or string representations of type Float32/64.
Unsupported arguments:
- Values or string representations of Float32/64 values
NaN
and
Inf
(case-insensitive).
- String representations of binary and hexadecimal values, e.g.
SELECT toDecimal32('0xc0fe', 1);
.
:::note
An overflow can occur if the value of
expr
exceeds the bounds of
Decimal32
:
( -1 * 10^(9 - S), 1 * 10^(9 - S) )
.
Excessive digits in a fraction are discarded (not rounded).
Excessive digits in the integer part will lead to an exception.
:::
:::warning
Conversions drop extra digits and could operate in an unexpected way when working with Float32/Float64 inputs as the operations are performed using floating point instructions.
For example:
toDecimal32(1.15, 2)
is equal to
1.14
because 1.15 * 100 in floating point is 114.99.
You can use a String input so the operations use the underlying integer type:
toDecimal32('1.15', 2) = 1.15
:::
Returned value
Value of type
Decimal(9, S)
.
Decimal32(S)
.
Example
Query:
sql
SELECT
toDecimal32(2, 1) AS a, toTypeName(a) AS type_a,
toDecimal32(4.2, 2) AS b, toTypeName(b) AS type_b,
toDecimal32('4.2', 3) AS c, toTypeName(c) AS type_c
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
a: 2
type_a: Decimal(9, 1)
b: 4.2
type_b: Decimal(9, 2)
c: 4.2
type_c: Decimal(9, 3)
See also
toDecimal32OrZero
.
toDecimal32OrNull
.
toDecimal32OrDefault
.
toDecimal32OrZero {#todecimal32orzero}
Like
toDecimal32
, this function converts an input value to a value of type
Decimal(9, S)
but returns
0
in case of an error.
Syntax
sql
toDecimal32OrZero(expr, S)
Arguments
expr
β A String representation of a number.
String
. | {"source_file": "type-conversion-functions.md"} | [
0.002179368631914258,
0.035001277923583984,
-0.03758278489112854,
0.07356607913970947,
-0.06220002844929695,
-0.015678180381655693,
0.048335034400224686,
0.06187698245048523,
-0.020797137171030045,
0.006697625387459993,
-0.05035007745027542,
-0.15849831700325012,
-0.02249925583600998,
0.05... |
5133c540-4000-43bf-96d3-3a6480b2bc90 | Syntax
sql
toDecimal32OrZero(expr, S)
Arguments
expr
β A String representation of a number.
String
.
S
β Scale parameter between 0 and 9, specifying how many digits the fractional part of a number can have.
UInt8
.
Supported arguments:
- String representations of type (U)Int8/16/32/64/128/256.
- String representations of type Float32/64.
Unsupported arguments:
- String representations of Float32/64 values
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toDecimal32OrZero('0xc0fe', 1);
.
:::note
An overflow can occur if the value of
expr
exceeds the bounds of
Decimal32
:
( -1 * 10^(9 - S), 1 * 10^(9 - S) )
.
Excessive digits in a fraction are discarded (not rounded).
Excessive digits in the integer part will lead to an error.
:::
Returned value
Value of type
Decimal(9, S)
if successful, otherwise
0
with
S
decimal places.
Decimal32(S)
.
Example
Query:
sql
SELECT
toDecimal32OrZero(toString(-1.111), 5) AS a,
toTypeName(a),
toDecimal32OrZero(toString('Inf'), 5) AS b,
toTypeName(b)
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
a: -1.111
toTypeName(a): Decimal(9, 5)
b: 0
toTypeName(b): Decimal(9, 5)
See also
toDecimal32
.
toDecimal32OrNull
.
toDecimal32OrDefault
.
toDecimal32OrNull {#todecimal32ornull}
Like
toDecimal32
, this function converts an input value to a value of type
Nullable(Decimal(9, S))
but returns
0
in case of an error.
Syntax
sql
toDecimal32OrNull(expr, S)
Arguments
expr
β A String representation of a number.
String
.
S
β Scale parameter between 0 and 9, specifying how many digits the fractional part of a number can have.
UInt8
.
Supported arguments:
- String representations of type (U)Int8/16/32/64/128/256.
- String representations of type Float32/64.
Unsupported arguments:
- String representations of Float32/64 values
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toDecimal32OrNull('0xc0fe', 1);
.
:::note
An overflow can occur if the value of
expr
exceeds the bounds of
Decimal32
:
( -1 * 10^(9 - S), 1 * 10^(9 - S) )
.
Excessive digits in a fraction are discarded (not rounded).
Excessive digits in the integer part will lead to an error.
:::
Returned value
Value of type
Nullable(Decimal(9, S))
if successful, otherwise value
NULL
of the same type.
Decimal32(S)
.
Examples
Query:
sql
SELECT
toDecimal32OrNull(toString(-1.111), 5) AS a,
toTypeName(a),
toDecimal32OrNull(toString('Inf'), 5) AS b,
toTypeName(b)
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
a: -1.111
toTypeName(a): Nullable(Decimal(9, 5))
b: α΄Ία΅α΄Έα΄Έ
toTypeName(b): Nullable(Decimal(9, 5))
See also
toDecimal32
.
toDecimal32OrZero
.
toDecimal32OrDefault
.
toDecimal32OrDefault {#todecimal32ordefault} | {"source_file": "type-conversion-functions.md"} | [
-0.013803025707602501,
-0.031398314982652664,
-0.08520284295082092,
-0.0037279282696545124,
-0.019123433157801628,
-0.06870890408754349,
0.06689323484897614,
0.10762102901935577,
-0.0652480199933052,
-0.007324068807065487,
-0.045248620212078094,
-0.15000730752944946,
0.0010210460750386119,
... |
63104d0e-eedb-4133-bf72-8c278a819fa3 | See also
toDecimal32
.
toDecimal32OrZero
.
toDecimal32OrDefault
.
toDecimal32OrDefault {#todecimal32ordefault}
Like
toDecimal32
, this function converts an input value to a value of type
Decimal(9, S)
but returns the default value in case of an error.
Syntax
sql
toDecimal32OrDefault(expr, S[, default])
Arguments
expr
β A String representation of a number.
String
.
S
β Scale parameter between 0 and 9, specifying how many digits the fractional part of a number can have.
UInt8
.
default
(optional) β The default value to return if parsing to type
Decimal32(S)
is unsuccessful.
Decimal32(S)
.
Supported arguments:
- String representations of type (U)Int8/16/32/64/128/256.
- String representations of type Float32/64.
Unsupported arguments:
- String representations of Float32/64 values
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toDecimal32OrDefault('0xc0fe', 1);
.
:::note
An overflow can occur if the value of
expr
exceeds the bounds of
Decimal32
:
( -1 * 10^(9 - S), 1 * 10^(9 - S) )
.
Excessive digits in a fraction are discarded (not rounded).
Excessive digits in the integer part will lead to an error.
:::
:::warning
Conversions drop extra digits and could operate in an unexpected way when working with Float32/Float64 inputs as the operations are performed using floating point instructions.
For example:
toDecimal32OrDefault(1.15, 2)
is equal to
1.14
because 1.15 * 100 in floating point is 114.99.
You can use a String input so the operations use the underlying integer type:
toDecimal32OrDefault('1.15', 2) = 1.15
:::
Returned value
Value of type
Decimal(9, S)
if successful, otherwise returns the default value if passed or
0
if not.
Decimal32(S)
.
Examples
Query:
sql
SELECT
toDecimal32OrDefault(toString(0.0001), 5) AS a,
toTypeName(a),
toDecimal32OrDefault('Inf', 0, CAST('-1', 'Decimal32(0)')) AS b,
toTypeName(b)
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
a: 0.0001
toTypeName(a): Decimal(9, 5)
b: -1
toTypeName(b): Decimal(9, 0)
See also
toDecimal32
.
toDecimal32OrZero
.
toDecimal32OrNull
.
toDecimal64 {#todecimal64}
Converts an input value to a value of type
Decimal(18, S)
with scale of
S
. Throws an exception in case of an error.
Syntax
sql
toDecimal64(expr, S)
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
.
S
β Scale parameter between 0 and 18, specifying how many digits the fractional part of a number can have.
UInt8
.
Supported arguments:
- Values or string representations of type (U)Int8/16/32/64/128/256.
- Values or string representations of type Float32/64.
Unsupported arguments:
- Values or string representations of Float32/64 values
NaN
and
Inf
(case-insensitive).
- String representations of binary and hexadecimal values, e.g.
SELECT toDecimal64('0xc0fe', 1);
. | {"source_file": "type-conversion-functions.md"} | [
0.02476394549012184,
-0.03502827137708664,
-0.08098627626895905,
0.0039625465869903564,
-0.05799735337495804,
-0.019582930952310562,
0.05668233335018158,
0.10467275232076645,
-0.0843280553817749,
-0.01668539084494114,
-0.05118987709283829,
-0.17043690383434296,
-0.041896361857652664,
0.049... |
d6f30c90-45c3-46a9-8672-375e813280a5 | :::note
An overflow can occur if the value of
expr
exceeds the bounds of
Decimal64
:
( -1 * 10^(18 - S), 1 * 10^(18 - S) )
.
Excessive digits in a fraction are discarded (not rounded).
Excessive digits in the integer part will lead to an exception.
:::
:::warning
Conversions drop extra digits and could operate in an unexpected way when working with Float32/Float64 inputs as the operations are performed using floating point instructions.
For example:
toDecimal64(1.15, 2)
is equal to
1.14
because 1.15 * 100 in floating point is 114.99.
You can use a String input so the operations use the underlying integer type:
toDecimal64('1.15', 2) = 1.15
:::
Returned value
Value of type
Decimal(18, S)
.
Decimal64(S)
.
Example
Query:
sql
SELECT
toDecimal64(2, 1) AS a, toTypeName(a) AS type_a,
toDecimal64(4.2, 2) AS b, toTypeName(b) AS type_b,
toDecimal64('4.2', 3) AS c, toTypeName(c) AS type_c
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
a: 2
type_a: Decimal(18, 1)
b: 4.2
type_b: Decimal(18, 2)
c: 4.2
type_c: Decimal(18, 3)
See also
toDecimal64OrZero
.
toDecimal64OrNull
.
toDecimal64OrDefault
.
toDecimal64OrZero {#todecimal64orzero}
Like
toDecimal64
, this function converts an input value to a value of type
Decimal(18, S)
but returns
0
in case of an error.
Syntax
sql
toDecimal64OrZero(expr, S)
Arguments
expr
β A String representation of a number.
String
.
S
β Scale parameter between 0 and 18, specifying how many digits the fractional part of a number can have.
UInt8
.
Supported arguments:
- String representations of type (U)Int8/16/32/64/128/256.
- String representations of type Float32/64.
Unsupported arguments:
- String representations of Float32/64 values
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toDecimal64OrZero('0xc0fe', 1);
.
:::note
An overflow can occur if the value of
expr
exceeds the bounds of
Decimal64
:
( -1 * 10^(18 - S), 1 * 10^(18 - S) )
.
Excessive digits in a fraction are discarded (not rounded).
Excessive digits in the integer part will lead to an error.
:::
Returned value
Value of type
Decimal(18, S)
if successful, otherwise
0
with
S
decimal places.
Decimal64(S)
.
Example
Query:
sql
SELECT
toDecimal64OrZero(toString(0.0001), 18) AS a,
toTypeName(a),
toDecimal64OrZero(toString('Inf'), 18) AS b,
toTypeName(b)
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
a: 0.0001
toTypeName(a): Decimal(18, 18)
b: 0
toTypeName(b): Decimal(18, 18)
See also
toDecimal64
.
toDecimal64OrNull
.
toDecimal64OrDefault
.
toDecimal64OrNull {#todecimal64ornull}
Like
toDecimal64
, this function converts an input value to a value of type
Nullable(Decimal(18, S))
but returns
0
in case of an error.
Syntax
sql
toDecimal64OrNull(expr, S)
Arguments
expr
β A String representation of a number.
String
. | {"source_file": "type-conversion-functions.md"} | [
-0.011832981370389462,
0.046385057270526886,
0.005002192221581936,
-0.013407007791101933,
-0.039802614599466324,
-0.09061925113201141,
0.052298013120889664,
0.07005491107702255,
-0.0036231449339538813,
0.038911815732717514,
-0.03927842527627945,
-0.13504202663898468,
0.01593373343348503,
-... |
3178b206-fd99-414f-969f-58f352897c59 | Syntax
sql
toDecimal64OrNull(expr, S)
Arguments
expr
β A String representation of a number.
String
.
S
β Scale parameter between 0 and 18, specifying how many digits the fractional part of a number can have.
UInt8
.
Supported arguments:
- String representations of type (U)Int8/16/32/64/128/256.
- String representations of type Float32/64.
Unsupported arguments:
- String representations of Float32/64 values
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toDecimal64OrNull('0xc0fe', 1);
.
:::note
An overflow can occur if the value of
expr
exceeds the bounds of
Decimal64
:
( -1 * 10^(18 - S), 1 * 10^(18 - S) )
.
Excessive digits in a fraction are discarded (not rounded).
Excessive digits in the integer part will lead to an error.
:::
Returned value
Value of type
Nullable(Decimal(18, S))
if successful, otherwise value
NULL
of the same type.
Decimal64(S)
.
Examples
Query:
sql
SELECT
toDecimal64OrNull(toString(0.0001), 18) AS a,
toTypeName(a),
toDecimal64OrNull(toString('Inf'), 18) AS b,
toTypeName(b)
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
a: 0.0001
toTypeName(a): Nullable(Decimal(18, 18))
b: α΄Ία΅α΄Έα΄Έ
toTypeName(b): Nullable(Decimal(18, 18))
See also
toDecimal64
.
toDecimal64OrZero
.
toDecimal64OrDefault
.
toDecimal64OrDefault {#todecimal64ordefault}
Like
toDecimal64
, this function converts an input value to a value of type
Decimal(18, S)
but returns the default value in case of an error.
Syntax
sql
toDecimal64OrDefault(expr, S[, default])
Arguments
expr
β A String representation of a number.
String
.
S
β Scale parameter between 0 and 18, specifying how many digits the fractional part of a number can have.
UInt8
.
default
(optional) β The default value to return if parsing to type
Decimal64(S)
is unsuccessful.
Decimal64(S)
.
Supported arguments:
- String representations of type (U)Int8/16/32/64/128/256.
- String representations of type Float32/64.
Unsupported arguments:
- String representations of Float32/64 values
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toDecimal64OrDefault('0xc0fe', 1);
.
:::note
An overflow can occur if the value of
expr
exceeds the bounds of
Decimal64
:
( -1 * 10^(18 - S), 1 * 10^(18 - S) )
.
Excessive digits in a fraction are discarded (not rounded).
Excessive digits in the integer part will lead to an error.
:::
:::warning
Conversions drop extra digits and could operate in an unexpected way when working with Float32/Float64 inputs as the operations are performed using floating point instructions.
For example:
toDecimal64OrDefault(1.15, 2)
is equal to
1.14
because 1.15 * 100 in floating point is 114.99.
You can use a String input so the operations use the underlying integer type:
toDecimal64OrDefault('1.15', 2) = 1.15
:::
Returned value | {"source_file": "type-conversion-functions.md"} | [
0.023577233776450157,
0.003308602375909686,
-0.06023300066590309,
0.009637683629989624,
-0.026585282757878304,
-0.058984167873859406,
0.055643659085035324,
0.1038256362080574,
-0.07203496247529984,
0.006364861037582159,
-0.018292859196662903,
-0.11094004660844803,
0.014699515886604786,
0.0... |
a294bb41-2f15-47eb-b7ed-94dda570081d | :::
Returned value
Value of type
Decimal(18, S)
if successful, otherwise returns the default value if passed or
0
if not.
Decimal64(S)
.
Examples
Query:
sql
SELECT
toDecimal64OrDefault(toString(0.0001), 18) AS a,
toTypeName(a),
toDecimal64OrDefault('Inf', 0, CAST('-1', 'Decimal64(0)')) AS b,
toTypeName(b)
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
a: 0.0001
toTypeName(a): Decimal(18, 18)
b: -1
toTypeName(b): Decimal(18, 0)
See also
toDecimal64
.
toDecimal64OrZero
.
toDecimal64OrNull
.
toDecimal128 {#todecimal128}
Converts an input value to a value of type
Decimal(38, S)
with scale of
S
. Throws an exception in case of an error.
Syntax
sql
toDecimal128(expr, S)
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
.
S
β Scale parameter between 0 and 38, specifying how many digits the fractional part of a number can have.
UInt8
.
Supported arguments:
- Values or string representations of type (U)Int8/16/32/64/128/256.
- Values or string representations of type Float32/64.
Unsupported arguments:
- Values or string representations of Float32/64 values
NaN
and
Inf
(case-insensitive).
- String representations of binary and hexadecimal values, e.g.
SELECT toDecimal128('0xc0fe', 1);
.
:::note
An overflow can occur if the value of
expr
exceeds the bounds of
Decimal128
:
( -1 * 10^(38 - S), 1 * 10^(38 - S) )
.
Excessive digits in a fraction are discarded (not rounded).
Excessive digits in the integer part will lead to an exception.
:::
:::warning
Conversions drop extra digits and could operate in an unexpected way when working with Float32/Float64 inputs as the operations are performed using floating point instructions.
For example:
toDecimal128(1.15, 2)
is equal to
1.14
because 1.15 * 100 in floating point is 114.99.
You can use a String input so the operations use the underlying integer type:
toDecimal128('1.15', 2) = 1.15
:::
Returned value
Value of type
Decimal(38, S)
.
Decimal128(S)
.
Example
Query:
sql
SELECT
toDecimal128(99, 1) AS a, toTypeName(a) AS type_a,
toDecimal128(99.67, 2) AS b, toTypeName(b) AS type_b,
toDecimal128('99.67', 3) AS c, toTypeName(c) AS type_c
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
a: 99
type_a: Decimal(38, 1)
b: 99.67
type_b: Decimal(38, 2)
c: 99.67
type_c: Decimal(38, 3)
See also
toDecimal128OrZero
.
toDecimal128OrNull
.
toDecimal128OrDefault
.
toDecimal128OrZero {#todecimal128orzero}
Like
toDecimal128
, this function converts an input value to a value of type
Decimal(38, S)
but returns
0
in case of an error.
Syntax
sql
toDecimal128OrZero(expr, S)
Arguments
expr
β A String representation of a number.
String
.
S
β Scale parameter between 0 and 38, specifying how many digits the fractional part of a number can have.
UInt8
. | {"source_file": "type-conversion-functions.md"} | [
0.015500170178711414,
0.03528853505849838,
-0.04252122715115547,
0.03719687461853027,
-0.07699324935674667,
-0.007419817615300417,
0.09610533714294434,
0.08291751146316528,
-0.01897117868065834,
0.03508731722831726,
-0.01728084683418274,
-0.12867189943790436,
0.022568685933947563,
0.006688... |
693e321d-b49d-4fbd-819f-decb1dc527e0 | Arguments
expr
β A String representation of a number.
String
.
S
β Scale parameter between 0 and 38, specifying how many digits the fractional part of a number can have.
UInt8
.
Supported arguments:
- String representations of type (U)Int8/16/32/64/128/256.
- String representations of type Float32/64.
Unsupported arguments:
- String representations of Float32/64 values
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toDecimal128OrZero('0xc0fe', 1);
.
:::note
An overflow can occur if the value of
expr
exceeds the bounds of
Decimal128
:
( -1 * 10^(38 - S), 1 * 10^(38 - S) )
.
Excessive digits in a fraction are discarded (not rounded).
Excessive digits in the integer part will lead to an error.
:::
Returned value
Value of type
Decimal(38, S)
if successful, otherwise
0
with
S
decimal places.
Decimal128(S)
.
Example
Query:
sql
SELECT
toDecimal128OrZero(toString(0.0001), 38) AS a,
toTypeName(a),
toDecimal128OrZero(toString('Inf'), 38) AS b,
toTypeName(b)
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
a: 0.0001
toTypeName(a): Decimal(38, 38)
b: 0
toTypeName(b): Decimal(38, 38)
See also
toDecimal128
.
toDecimal128OrNull
.
toDecimal128OrDefault
.
toDecimal128OrNull {#todecimal128ornull}
Like
toDecimal128
, this function converts an input value to a value of type
Nullable(Decimal(38, S))
but returns
0
in case of an error.
Syntax
sql
toDecimal128OrNull(expr, S)
Arguments
expr
β A String representation of a number.
String
.
S
β Scale parameter between 0 and 38, specifying how many digits the fractional part of a number can have.
UInt8
.
Supported arguments:
- String representations of type (U)Int8/16/32/64/128/256.
- String representations of type Float32/64.
Unsupported arguments:
- String representations of Float32/64 values
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toDecimal128OrNull('0xc0fe', 1);
.
:::note
An overflow can occur if the value of
expr
exceeds the bounds of
Decimal128
:
( -1 * 10^(38 - S), 1 * 10^(38 - S) )
.
Excessive digits in a fraction are discarded (not rounded).
Excessive digits in the integer part will lead to an error.
:::
Returned value
Value of type
Nullable(Decimal(38, S))
if successful, otherwise value
NULL
of the same type.
Decimal128(S)
.
Examples
Query:
sql
SELECT
toDecimal128OrNull(toString(1/42), 38) AS a,
toTypeName(a),
toDecimal128OrNull(toString('Inf'), 38) AS b,
toTypeName(b)
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
a: 0.023809523809523808
toTypeName(a): Nullable(Decimal(38, 38))
b: α΄Ία΅α΄Έα΄Έ
toTypeName(b): Nullable(Decimal(38, 38))
See also
toDecimal128
.
toDecimal128OrZero
.
toDecimal128OrDefault
.
toDecimal128OrDefault {#todecimal128ordefault} | {"source_file": "type-conversion-functions.md"} | [
-0.01142551377415657,
-0.0035623665899038315,
-0.07916844636201859,
-0.0067912740632891655,
-0.029219046235084534,
-0.046125512570142746,
0.07647740095853806,
0.1390107125043869,
-0.052430231124162674,
-0.010824967175722122,
-0.01606643944978714,
-0.10095693916082382,
0.01758357509970665,
... |
6afcd90c-5a92-449c-9c8d-57a22e13952f | See also
toDecimal128
.
toDecimal128OrZero
.
toDecimal128OrDefault
.
toDecimal128OrDefault {#todecimal128ordefault}
Like
toDecimal128
, this function converts an input value to a value of type
Decimal(38, S)
but returns the default value in case of an error.
Syntax
sql
toDecimal128OrDefault(expr, S[, default])
Arguments
expr
β A String representation of a number.
String
.
S
β Scale parameter between 0 and 38, specifying how many digits the fractional part of a number can have.
UInt8
.
default
(optional) β The default value to return if parsing to type
Decimal128(S)
is unsuccessful.
Decimal128(S)
.
Supported arguments:
- String representations of type (U)Int8/16/32/64/128/256.
- String representations of type Float32/64.
Unsupported arguments:
- String representations of Float32/64 values
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toDecimal128OrDefault('0xc0fe', 1);
.
:::note
An overflow can occur if the value of
expr
exceeds the bounds of
Decimal128
:
( -1 * 10^(38 - S), 1 * 10^(38 - S) )
.
Excessive digits in a fraction are discarded (not rounded).
Excessive digits in the integer part will lead to an error.
:::
:::warning
Conversions drop extra digits and could operate in an unexpected way when working with Float32/Float64 inputs as the operations are performed using floating point instructions.
For example:
toDecimal128OrDefault(1.15, 2)
is equal to
1.14
because 1.15 * 100 in floating point is 114.99.
You can use a String input so the operations use the underlying integer type:
toDecimal128OrDefault('1.15', 2) = 1.15
:::
Returned value
Value of type
Decimal(38, S)
if successful, otherwise returns the default value if passed or
0
if not.
Decimal128(S)
.
Examples
Query:
sql
SELECT
toDecimal128OrDefault(toString(1/42), 18) AS a,
toTypeName(a),
toDecimal128OrDefault('Inf', 0, CAST('-1', 'Decimal128(0)')) AS b,
toTypeName(b)
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
a: 0.023809523809523808
toTypeName(a): Decimal(38, 18)
b: -1
toTypeName(b): Decimal(38, 0)
See also
toDecimal128
.
toDecimal128OrZero
.
toDecimal128OrNull
.
toDecimal256 {#todecimal256}
Converts an input value to a value of type
Decimal(76, S)
with scale of
S
. Throws an exception in case of an error.
Syntax
sql
toDecimal256(expr, S)
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
.
S
β Scale parameter between 0 and 76, specifying how many digits the fractional part of a number can have.
UInt8
.
Supported arguments:
- Values or string representations of type (U)Int8/16/32/64/128/256.
- Values or string representations of type Float32/64. | {"source_file": "type-conversion-functions.md"} | [
0.015072811394929886,
-0.01605750434100628,
-0.06799406558275223,
0.005042990203946829,
-0.07160074263811111,
-0.017817538231611252,
0.05413225665688515,
0.10435035824775696,
-0.08315198123455048,
-0.012122317217290401,
-0.0316159650683403,
-0.1355942338705063,
-0.03708486258983612,
0.0466... |
24da146f-18fd-4463-9242-3aafb38d434b | Supported arguments:
- Values or string representations of type (U)Int8/16/32/64/128/256.
- Values or string representations of type Float32/64.
Unsupported arguments:
- Values or string representations of Float32/64 values
NaN
and
Inf
(case-insensitive).
- String representations of binary and hexadecimal values, e.g.
SELECT toDecimal256('0xc0fe', 1);
.
:::note
An overflow can occur if the value of
expr
exceeds the bounds of
Decimal256
:
( -1 * 10^(76 - S), 1 * 10^(76 - S) )
.
Excessive digits in a fraction are discarded (not rounded).
Excessive digits in the integer part will lead to an exception.
:::
:::warning
Conversions drop extra digits and could operate in an unexpected way when working with Float32/Float64 inputs as the operations are performed using floating point instructions.
For example:
toDecimal256(1.15, 2)
is equal to
1.14
because 1.15 * 100 in floating point is 114.99.
You can use a String input so the operations use the underlying integer type:
toDecimal256('1.15', 2) = 1.15
:::
Returned value
Value of type
Decimal(76, S)
.
Decimal256(S)
.
Example
Query:
sql
SELECT
toDecimal256(99, 1) AS a, toTypeName(a) AS type_a,
toDecimal256(99.67, 2) AS b, toTypeName(b) AS type_b,
toDecimal256('99.67', 3) AS c, toTypeName(c) AS type_c
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
a: 99
type_a: Decimal(76, 1)
b: 99.67
type_b: Decimal(76, 2)
c: 99.67
type_c: Decimal(76, 3)
See also
toDecimal256OrZero
.
toDecimal256OrNull
.
toDecimal256OrDefault
.
toDecimal256OrZero {#todecimal256orzero}
Like
toDecimal256
, this function converts an input value to a value of type
Decimal(76, S)
but returns
0
in case of an error.
Syntax
sql
toDecimal256OrZero(expr, S)
Arguments
expr
β A String representation of a number.
String
.
S
β Scale parameter between 0 and 76, specifying how many digits the fractional part of a number can have.
UInt8
.
Supported arguments:
- String representations of type (U)Int8/16/32/64/128/256.
- String representations of type Float32/64.
Unsupported arguments:
- String representations of Float32/64 values
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toDecimal256OrZero('0xc0fe', 1);
.
:::note
An overflow can occur if the value of
expr
exceeds the bounds of
Decimal256
:
( -1 * 10^(76 - S), 1 * 10^(76 - S) )
.
Excessive digits in a fraction are discarded (not rounded).
Excessive digits in the integer part will lead to an error.
:::
Returned value
Value of type
Decimal(76, S)
if successful, otherwise
0
with
S
decimal places.
Decimal256(S)
.
Example
Query:
sql
SELECT
toDecimal256OrZero(toString(0.0001), 76) AS a,
toTypeName(a),
toDecimal256OrZero(toString('Inf'), 76) AS b,
toTypeName(b)
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
a: 0.0001
toTypeName(a): Decimal(76, 76)
b: 0
toTypeName(b): Decimal(76, 76) | {"source_file": "type-conversion-functions.md"} | [
-0.022131692618131638,
0.010747366584837437,
-0.02173086255788803,
-0.044755954295396805,
0.02644556201994419,
-0.1117502972483635,
0.03978348150849342,
0.09464320540428162,
-0.02826795168220997,
-0.011650606989860535,
-0.05662330612540245,
-0.13777099549770355,
-0.0003884673351421952,
0.0... |
a12e9047-b1be-4c63-a3a6-8665f22046b5 | Result:
response
Row 1:
ββββββ
a: 0.0001
toTypeName(a): Decimal(76, 76)
b: 0
toTypeName(b): Decimal(76, 76)
See also
toDecimal256
.
toDecimal256OrNull
.
toDecimal256OrDefault
.
toDecimal256OrNull {#todecimal256ornull}
Like
toDecimal256
, this function converts an input value to a value of type
Nullable(Decimal(76, S))
but returns
0
in case of an error.
Syntax
sql
toDecimal256OrNull(expr, S)
Arguments
expr
β A String representation of a number.
String
.
S
β Scale parameter between 0 and 76, specifying how many digits the fractional part of a number can have.
UInt8
.
Supported arguments:
- String representations of type (U)Int8/16/32/64/128/256.
- String representations of type Float32/64.
Unsupported arguments:
- String representations of Float32/64 values
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toDecimal256OrNull('0xc0fe', 1);
.
:::note
An overflow can occur if the value of
expr
exceeds the bounds of
Decimal256
:
( -1 * 10^(76 - S), 1 * 10^(76 - S) )
.
Excessive digits in a fraction are discarded (not rounded).
Excessive digits in the integer part will lead to an error.
:::
Returned value
Value of type
Nullable(Decimal(76, S))
if successful, otherwise value
NULL
of the same type.
Decimal256(S)
.
Examples
Query:
sql
SELECT
toDecimal256OrNull(toString(1/42), 76) AS a,
toTypeName(a),
toDecimal256OrNull(toString('Inf'), 76) AS b,
toTypeName(b)
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
a: 0.023809523809523808
toTypeName(a): Nullable(Decimal(76, 76))
b: α΄Ία΅α΄Έα΄Έ
toTypeName(b): Nullable(Decimal(76, 76))
See also
toDecimal256
.
toDecimal256OrZero
.
toDecimal256OrDefault
.
toDecimal256OrDefault {#todecimal256ordefault}
Like
toDecimal256
, this function converts an input value to a value of type
Decimal(76, S)
but returns the default value in case of an error.
Syntax
sql
toDecimal256OrDefault(expr, S[, default])
Arguments
expr
β A String representation of a number.
String
.
S
β Scale parameter between 0 and 76, specifying how many digits the fractional part of a number can have.
UInt8
.
default
(optional) β The default value to return if parsing to type
Decimal256(S)
is unsuccessful.
Decimal256(S)
.
Supported arguments:
- String representations of type (U)Int8/16/32/64/128/256.
- String representations of type Float32/64.
Unsupported arguments:
- String representations of Float32/64 values
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toDecimal256OrDefault('0xc0fe', 1);
.
:::note
An overflow can occur if the value of
expr
exceeds the bounds of
Decimal256
:
( -1 * 10^(76 - S), 1 * 10^(76 - S) )
.
Excessive digits in a fraction are discarded (not rounded).
Excessive digits in the integer part will lead to an error.
::: | {"source_file": "type-conversion-functions.md"} | [
0.0032188796903938055,
-0.013267521746456623,
-0.10303046554327011,
0.02416958101093769,
-0.06714053452014923,
-0.04755478724837303,
0.07560674846172333,
0.06405184417963028,
-0.09904562681913376,
0.007027491927146912,
-0.0161973275244236,
-0.16673679649829865,
0.021284086629748344,
0.0142... |
6f5c0e05-b159-4fb0-8f8f-050b90ac314d | :::warning
Conversions drop extra digits and could operate in an unexpected way when working with Float32/Float64 inputs as the operations are performed using floating point instructions.
For example:
toDecimal256OrDefault(1.15, 2)
is equal to
1.14
because 1.15 * 100 in floating point is 114.99.
You can use a String input so the operations use the underlying integer type:
toDecimal256OrDefault('1.15', 2) = 1.15
:::
Returned value
Value of type
Decimal(76, S)
if successful, otherwise returns the default value if passed or
0
if not.
Decimal256(S)
.
Examples
Query:
sql
SELECT
toDecimal256OrDefault(toString(1/42), 76) AS a,
toTypeName(a),
toDecimal256OrDefault('Inf', 0, CAST('-1', 'Decimal256(0)')) AS b,
toTypeName(b)
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
a: 0.023809523809523808
toTypeName(a): Decimal(76, 76)
b: -1
toTypeName(b): Decimal(76, 0)
See also
toDecimal256
.
toDecimal256OrZero
.
toDecimal256OrNull
.
toString {#tostring}
Converts values to their string representation.
For DateTime arguments, the function can take a second String argument containing the name of the time zone.
Syntax
sql
toString(value[, timezone])
Arguments
-
value
: Value to convert to string.
Any
.
-
timezone
: Optional. Timezone name for
DateTime
conversion.
String
.
Returned value
- Returns a string representation of the input value.
String
.
Examples
Usage example
sql title="Query"
SELECT
now() AS ts,
time_zone,
toString(ts, time_zone) AS str_tz_datetime
FROM system.time_zones
WHERE time_zone LIKE 'Europe%'
LIMIT 10;
response title="Response"
βββββββββββββββββββtsββ¬βtime_zoneββββββββββ¬βstr_tz_datetimeββββββ
β 2023-09-08 19:14:59 β Europe/Amsterdam β 2023-09-08 21:14:59 β
β 2023-09-08 19:14:59 β Europe/Andorra β 2023-09-08 21:14:59 β
β 2023-09-08 19:14:59 β Europe/Astrakhan β 2023-09-08 23:14:59 β
β 2023-09-08 19:14:59 β Europe/Athens β 2023-09-08 22:14:59 β
β 2023-09-08 19:14:59 β Europe/Belfast β 2023-09-08 20:14:59 β
βββββββββββββββββββββββ΄ββββββββββββββββββββ΄ββββββββββββββββββββββ
toFixedString {#tofixedstring}
Converts a
String
type argument to a
FixedString(N)
type (a string of fixed length N).
If the string has fewer bytes than N, it is padded with null bytes to the right. If the string has more bytes than N, an exception is thrown.
Syntax
sql
toFixedString(s, N)
Arguments
s
β A String to convert to a fixed string.
String
.
N
β Length N.
UInt8
Returned value
An N length fixed string of
s
.
FixedString
.
Example
Query:
sql
SELECT toFixedString('foo', 8) AS s;
Result:
response
ββsββββββββββββββ
β foo\0\0\0\0\0 β
βββββββββββββββββ
toStringCutToZero {#tostringcuttozero}
Accepts a String or FixedString argument. Returns the String with the content truncated at the first zero byte found.
Syntax
sql
toStringCutToZero(s)
Example
Query: | {"source_file": "type-conversion-functions.md"} | [
0.000041086797864409164,
0.019301578402519226,
-0.05409223586320877,
0.011417653411626816,
-0.040221571922302246,
-0.06236810237169266,
0.10175979137420654,
0.06723444908857346,
0.010472084395587444,
0.02381419576704502,
-0.03193189948797226,
-0.15937501192092896,
0.02197316102683544,
-0.0... |
7fbe3a71-d094-4a03-b569-0e8dc44d9656 | Accepts a String or FixedString argument. Returns the String with the content truncated at the first zero byte found.
Syntax
sql
toStringCutToZero(s)
Example
Query:
sql
SELECT toFixedString('foo', 8) AS s, toStringCutToZero(s) AS s_cut;
Result:
response
ββsββββββββββββββ¬βs_cutββ
β foo\0\0\0\0\0 β foo β
βββββββββββββββββ΄ββββββββ
Query:
sql
SELECT toFixedString('foo\0bar', 8) AS s, toStringCutToZero(s) AS s_cut;
Result:
response
ββsβββββββββββ¬βs_cutββ
β foo\0bar\0 β foo β
ββββββββββββββ΄ββββββββ
toDecimalString {#todecimalstring}
Converts a numeric value to String with the number of fractional digits in the output specified by the user.
Syntax
sql
toDecimalString(number, scale)
Arguments
number
β Value to be represented as String,
Int, UInt
,
Float
,
Decimal
,
scale
β Number of fractional digits,
UInt8
.
Maximum scale for
Decimal
and
Int, UInt
types is 77 (it is the maximum possible number of significant digits for Decimal),
Maximum scale for
Float
is 60.
Returned value
Input value represented as
String
with given number of fractional digits (scale).
The number is rounded up or down according to common arithmetic in case requested scale is smaller than original number's scale.
Example
Query:
sql
SELECT toDecimalString(CAST('64.32', 'Float64'), 5);
Result:
response
βtoDecimalString(CAST('64.32', 'Float64'), 5)ββ
β 64.32000 β
βββββββββββββββββββββββββββββββββββββββββββββββ
reinterpretAsUInt8 {#reinterpretasuint8}
Performs byte reinterpretation by treating the input value as a value of type UInt8. Unlike
CAST
, the function does not attempt to preserve the original value - if the target type is not able to represent the input type, the output is meaningless.
Syntax
sql
reinterpretAsUInt8(x)
Parameters
x
: value to byte reinterpret as UInt8.
(U)Int*
,
Float
,
Date
,
DateTime
,
UUID
,
String
or
FixedString
.
Returned value
Reinterpreted value
x
as UInt8.
UInt8
.
Example
Query:
sql
SELECT
toInt8(257) AS x,
toTypeName(x),
reinterpretAsUInt8(x) AS res,
toTypeName(res);
Result:
response
ββxββ¬βtoTypeName(x)ββ¬βresββ¬βtoTypeName(res)ββ
β 1 β Int8 β 1 β UInt8 β
βββββ΄ββββββββββββββββ΄ββββββ΄ββββββββββββββββββ
reinterpretAsUInt16 {#reinterpretasuint16}
Performs byte reinterpretation by treating the input value as a value of type UInt16. Unlike
CAST
, the function does not attempt to preserve the original value - if the target type is not able to represent the input type, the output is meaningless.
Syntax
sql
reinterpretAsUInt16(x)
Parameters
x
: value to byte reinterpret as UInt16.
(U)Int*
,
Float
,
Date
,
DateTime
,
UUID
,
String
or
FixedString
.
Returned value
Reinterpreted value
x
as UInt16.
UInt16
.
Example
Query:
sql
SELECT
toUInt8(257) AS x,
toTypeName(x),
reinterpretAsUInt16(x) AS res,
toTypeName(res); | {"source_file": "type-conversion-functions.md"} | [
0.039218418300151825,
-0.013510283082723618,
-0.023531846702098846,
0.025768402963876724,
-0.10734116286039352,
-0.013342256657779217,
0.10242113471031189,
0.11263056844472885,
-0.02804258093237877,
0.018374329432845116,
-0.025138752534985542,
-0.09028542041778564,
0.014059395529329777,
-0... |
fcaa3ad9-c090-43a6-9759-5a0566821264 | Returned value
Reinterpreted value
x
as UInt16.
UInt16
.
Example
Query:
sql
SELECT
toUInt8(257) AS x,
toTypeName(x),
reinterpretAsUInt16(x) AS res,
toTypeName(res);
Result:
response
ββxββ¬βtoTypeName(x)ββ¬βresββ¬βtoTypeName(res)ββ
β 1 β UInt8 β 1 β UInt16 β
βββββ΄ββββββββββββββββ΄ββββββ΄ββββββββββββββββββ
reinterpretAsUInt32 {#reinterpretasuint32}
Performs byte reinterpretation by treating the input value as a value of type UInt32. Unlike
CAST
, the function does not attempt to preserve the original value - if the target type is not able to represent the input type, the output is meaningless.
Syntax
sql
reinterpretAsUInt32(x)
Parameters
x
: value to byte reinterpret as UInt32.
(U)Int*
,
Float
,
Date
,
DateTime
,
UUID
,
String
or
FixedString
.
Returned value
Reinterpreted value
x
as UInt32.
UInt32
.
Example
Query:
sql
SELECT
toUInt16(257) AS x,
toTypeName(x),
reinterpretAsUInt32(x) AS res,
toTypeName(res)
Result:
response
ββββxββ¬βtoTypeName(x)ββ¬βresββ¬βtoTypeName(res)ββ
β 257 β UInt16 β 257 β UInt32 β
βββββββ΄ββββββββββββββββ΄ββββββ΄ββββββββββββββββββ
reinterpretAsUInt64 {#reinterpretasuint64}
Performs byte reinterpretation by treating the input value as a value of type UInt64. Unlike
CAST
, the function does not attempt to preserve the original value - if the target type is not able to represent the input type, the output is meaningless.
Syntax
sql
reinterpretAsUInt64(x)
Parameters
x
: value to byte reinterpret as UInt64.
(U)Int*
,
Float
,
Date
,
DateTime
,
UUID
,
String
or
FixedString
.
Returned value
Reinterpreted value
x
as UInt64.
UInt64
.
Example
Query:
sql
SELECT
toUInt32(257) AS x,
toTypeName(x),
reinterpretAsUInt64(x) AS res,
toTypeName(res)
Result:
response
ββββxββ¬βtoTypeName(x)ββ¬βresββ¬βtoTypeName(res)ββ
β 257 β UInt32 β 257 β UInt64 β
βββββββ΄ββββββββββββββββ΄ββββββ΄ββββββββββββββββββ
reinterpretAsUInt128 {#reinterpretasuint128}
Performs byte reinterpretation by treating the input value as a value of type UInt128. Unlike
CAST
, the function does not attempt to preserve the original value - if the target type is not able to represent the input type, the output is meaningless.
Syntax
sql
reinterpretAsUInt128(x)
Parameters
x
: value to byte reinterpret as UInt128.
(U)Int*
,
Float
,
Date
,
DateTime
,
UUID
,
String
or
FixedString
.
Returned value
Reinterpreted value
x
as UInt128.
UInt128
.
Example
Query:
sql
SELECT
toUInt64(257) AS x,
toTypeName(x),
reinterpretAsUInt128(x) AS res,
toTypeName(res)
Result:
response
ββββxββ¬βtoTypeName(x)ββ¬βresββ¬βtoTypeName(res)ββ
β 257 β UInt64 β 257 β UInt128 β
βββββββ΄ββββββββββββββββ΄ββββββ΄ββββββββββββββββββ
reinterpretAsUInt256 {#reinterpretasuint256} | {"source_file": "type-conversion-functions.md"} | [
0.014149315655231476,
-0.04171786084771156,
-0.017465071752667427,
0.07699976116418839,
-0.10912284255027771,
0.0026584004517644644,
0.07220500707626343,
-0.010389099828898907,
-0.06468677520751953,
-0.0323343425989151,
-0.05296219140291214,
-0.05434127897024155,
0.00122460734564811,
-0.03... |
ac1a8c37-df4e-4cc9-9b38-e53680c30c1e | reinterpretAsUInt256 {#reinterpretasuint256}
Performs byte reinterpretation by treating the input value as a value of type UInt256. Unlike
CAST
, the function does not attempt to preserve the original value - if the target type is not able to represent the input type, the output is meaningless.
Syntax
sql
reinterpretAsUInt256(x)
Parameters
x
: value to byte reinterpret as UInt256.
(U)Int*
,
Float
,
Date
,
DateTime
,
UUID
,
String
or
FixedString
.
Returned value
Reinterpreted value
x
as UInt256.
UInt256
.
Example
Query:
sql
SELECT
toUInt128(257) AS x,
toTypeName(x),
reinterpretAsUInt256(x) AS res,
toTypeName(res)
Result:
response
ββββxββ¬βtoTypeName(x)ββ¬βresββ¬βtoTypeName(res)ββ
β 257 β UInt128 β 257 β UInt256 β
βββββββ΄ββββββββββββββββ΄ββββββ΄ββββββββββββββββββ
reinterpretAsInt8 {#reinterpretasint8}
Performs byte reinterpretation by treating the input value as a value of type Int8. Unlike
CAST
, the function does not attempt to preserve the original value - if the target type is not able to represent the input type, the output is meaningless.
Syntax
sql
reinterpretAsInt8(x)
Parameters
x
: value to byte reinterpret as Int8.
(U)Int*
,
Float
,
Date
,
DateTime
,
UUID
,
String
or
FixedString
.
Returned value
Reinterpreted value
x
as Int8.
Int8
.
Example
Query:
sql
SELECT
toUInt8(257) AS x,
toTypeName(x),
reinterpretAsInt8(x) AS res,
toTypeName(res);
Result:
response
ββxββ¬βtoTypeName(x)ββ¬βresββ¬βtoTypeName(res)ββ
β 1 β UInt8 β 1 β Int8 β
βββββ΄ββββββββββββββββ΄ββββββ΄ββββββββββββββββββ
reinterpretAsInt16 {#reinterpretasint16}
Performs byte reinterpretation by treating the input value as a value of type Int16. Unlike
CAST
, the function does not attempt to preserve the original value - if the target type is not able to represent the input type, the output is meaningless.
Syntax
sql
reinterpretAsInt16(x)
Parameters
x
: value to byte reinterpret as Int16.
(U)Int*
,
Float
,
Date
,
DateTime
,
UUID
,
String
or
FixedString
.
Returned value
Reinterpreted value
x
as Int16.
Int16
.
Example
Query:
sql
SELECT
toInt8(257) AS x,
toTypeName(x),
reinterpretAsInt16(x) AS res,
toTypeName(res);
Result:
response
ββxββ¬βtoTypeName(x)ββ¬βresββ¬βtoTypeName(res)ββ
β 1 β Int8 β 1 β Int16 β
βββββ΄ββββββββββββββββ΄ββββββ΄ββββββββββββββββββ
reinterpretAsInt32 {#reinterpretasint32}
Performs byte reinterpretation by treating the input value as a value of type Int32. Unlike
CAST
, the function does not attempt to preserve the original value - if the target type is not able to represent the input type, the output is meaningless.
Syntax
sql
reinterpretAsInt32(x)
Parameters
x
: value to byte reinterpret as Int32.
(U)Int*
,
Float
,
Date
,
DateTime
,
UUID
,
String
or
FixedString
.
Returned value | {"source_file": "type-conversion-functions.md"} | [
-0.026833882555365562,
-0.06241140142083168,
0.016114821657538414,
0.06397085636854172,
-0.09774458408355713,
-0.017768586054444313,
0.0731610581278801,
-0.031495146453380585,
-0.04118453711271286,
-0.006959816440939903,
-0.05949191749095917,
-0.020877601578831673,
0.016475632786750793,
-0... |
4b35efaa-3e38-445a-bd30-41e3b922ed47 | Syntax
sql
reinterpretAsInt32(x)
Parameters
x
: value to byte reinterpret as Int32.
(U)Int*
,
Float
,
Date
,
DateTime
,
UUID
,
String
or
FixedString
.
Returned value
Reinterpreted value
x
as Int32.
Int32
.
Example
Query:
sql
SELECT
toInt16(257) AS x,
toTypeName(x),
reinterpretAsInt32(x) AS res,
toTypeName(res);
Result:
response
ββββxββ¬βtoTypeName(x)ββ¬βresββ¬βtoTypeName(res)ββ
β 257 β Int16 β 257 β Int32 β
βββββββ΄ββββββββββββββββ΄ββββββ΄ββββββββββββββββββ
reinterpretAsInt64 {#reinterpretasint64}
Performs byte reinterpretation by treating the input value as a value of type Int64. Unlike
CAST
, the function does not attempt to preserve the original value - if the target type is not able to represent the input type, the output is meaningless.
Syntax
sql
reinterpretAsInt64(x)
Parameters
x
: value to byte reinterpret as Int64.
(U)Int*
,
Float
,
Date
,
DateTime
,
UUID
,
String
or
FixedString
.
Returned value
Reinterpreted value
x
as Int64.
Int64
.
Example
Query:
sql
SELECT
toInt32(257) AS x,
toTypeName(x),
reinterpretAsInt64(x) AS res,
toTypeName(res);
Result:
response
ββββxββ¬βtoTypeName(x)ββ¬βresββ¬βtoTypeName(res)ββ
β 257 β Int32 β 257 β Int64 β
βββββββ΄ββββββββββββββββ΄ββββββ΄ββββββββββββββββββ
reinterpretAsInt128 {#reinterpretasint128}
Performs byte reinterpretation by treating the input value as a value of type Int128. Unlike
CAST
, the function does not attempt to preserve the original value - if the target type is not able to represent the input type, the output is meaningless.
Syntax
sql
reinterpretAsInt128(x)
Parameters
x
: value to byte reinterpret as Int128.
(U)Int*
,
Float
,
Date
,
DateTime
,
UUID
,
String
or
FixedString
.
Returned value
Reinterpreted value
x
as Int128.
Int128
.
Example
Query:
sql
SELECT
toInt64(257) AS x,
toTypeName(x),
reinterpretAsInt128(x) AS res,
toTypeName(res);
Result:
response
ββββxββ¬βtoTypeName(x)ββ¬βresββ¬βtoTypeName(res)ββ
β 257 β Int64 β 257 β Int128 β
βββββββ΄ββββββββββββββββ΄ββββββ΄ββββββββββββββββββ
reinterpretAsInt256 {#reinterpretasint256}
Performs byte reinterpretation by treating the input value as a value of type Int256. Unlike
CAST
, the function does not attempt to preserve the original value - if the target type is not able to represent the input type, the output is meaningless.
Syntax
sql
reinterpretAsInt256(x)
Parameters
x
: value to byte reinterpret as Int256.
(U)Int*
,
Float
,
Date
,
DateTime
,
UUID
,
String
or
FixedString
.
Returned value
Reinterpreted value
x
as Int256.
Int256
.
Example
Query:
sql
SELECT
toInt128(257) AS x,
toTypeName(x),
reinterpretAsInt256(x) AS res,
toTypeName(res);
Result: | {"source_file": "type-conversion-functions.md"} | [
0.022818317636847496,
-0.03129595145583153,
-0.017477957531809807,
0.0813823714852333,
-0.07958605140447617,
-0.015288861468434334,
0.07195835560560226,
0.005958928260952234,
-0.07060866057872772,
-0.009305311366915703,
-0.04226304963231087,
-0.041530292481184006,
0.03383179381489754,
-0.0... |
ea10f623-fca3-405f-89ca-e03a25bb49a5 | Reinterpreted value
x
as Int256.
Int256
.
Example
Query:
sql
SELECT
toInt128(257) AS x,
toTypeName(x),
reinterpretAsInt256(x) AS res,
toTypeName(res);
Result:
response
ββββxββ¬βtoTypeName(x)ββ¬βresββ¬βtoTypeName(res)ββ
β 257 β Int128 β 257 β Int256 β
βββββββ΄ββββββββββββββββ΄ββββββ΄ββββββββββββββββββ
reinterpretAsFloat32 {#reinterpretasfloat32}
Performs byte reinterpretation by treating the input value as a value of type Float32. Unlike
CAST
, the function does not attempt to preserve the original value - if the target type is not able to represent the input type, the output is meaningless.
Syntax
sql
reinterpretAsFloat32(x)
Parameters
x
: value to reinterpret as Float32.
(U)Int*
,
Float
,
Date
,
DateTime
,
UUID
,
String
or
FixedString
.
Returned value
Reinterpreted value
x
as Float32.
Float32
.
Example
Query:
sql
SELECT reinterpretAsUInt32(toFloat32(0.2)) AS x, reinterpretAsFloat32(x);
Result:
response
βββββββββββxββ¬βreinterpretAsFloat32(x)ββ
β 1045220557 β 0.2 β
ββββββββββββββ΄ββββββββββββββββββββββββββ
reinterpretAsFloat64 {#reinterpretasfloat64}
Performs byte reinterpretation by treating the input value as a value of type Float64. Unlike
CAST
, the function does not attempt to preserve the original value - if the target type is not able to represent the input type, the output is meaningless.
Syntax
sql
reinterpretAsFloat64(x)
Parameters
x
: value to reinterpret as Float64.
(U)Int*
,
Float
,
Date
,
DateTime
,
UUID
,
String
or
FixedString
.
Returned value
Reinterpreted value
x
as Float64.
Float64
.
Example
Query:
sql
SELECT reinterpretAsUInt64(toFloat64(0.2)) AS x, reinterpretAsFloat64(x);
Result:
response
ββββββββββββββββββββxββ¬βreinterpretAsFloat64(x)ββ
β 4596373779694328218 β 0.2 β
βββββββββββββββββββββββ΄ββββββββββββββββββββββββββ
reinterpretAsDate {#reinterpretasdate}
Accepts a string, fixed string or numeric value and interprets the bytes as a number in host order (little endian). It returns a date from the interpreted number as the number of days since the beginning of the Unix Epoch.
Syntax
sql
reinterpretAsDate(x)
Parameters
x
: number of days since the beginning of the Unix Epoch.
(U)Int*
,
Float
,
Date
,
DateTime
,
UUID
,
String
or
FixedString
.
Returned value
Date.
Date
.
Implementation details
:::note
If the provided string isn't long enough, the function works as if the string is padded with the necessary number of null bytes. If the string is longer than needed, the extra bytes are ignored.
:::
Example
Query:
sql
SELECT reinterpretAsDate(65), reinterpretAsDate('A');
Result:
response
ββreinterpretAsDate(65)ββ¬βreinterpretAsDate('A')ββ
β 1970-03-07 β 1970-03-07 β
βββββββββββββββββββββββββ΄βββββββββββββββββββββββββ
reinterpretAsDateTime {#reinterpretasdatetime} | {"source_file": "type-conversion-functions.md"} | [
0.02424030750989914,
-0.05817970260977745,
-0.0044872090220451355,
0.08168764412403107,
-0.0817275270819664,
-0.0038357439916580915,
0.05790070444345474,
-0.02945239655673504,
-0.07139197736978531,
-0.016965065151453018,
-0.06288190186023712,
-0.052146755158901215,
0.005048542749136686,
-0... |
d2e96d41-f77e-4b47-ab03-7ea1d06564de | reinterpretAsDateTime {#reinterpretasdatetime}
These functions accept a string and interpret the bytes placed at the beginning of the string as a number in host order (little endian). Returns a date with time interpreted as the number of seconds since the beginning of the Unix Epoch.
Syntax
sql
reinterpretAsDateTime(x)
Parameters
x
: number of seconds since the beginning of the Unix Epoch.
(U)Int*
,
Float
,
Date
,
DateTime
,
UUID
,
String
or
FixedString
.
Returned value
Date and Time.
DateTime
.
Implementation details
:::note
If the provided string isn't long enough, the function works as if the string is padded with the necessary number of null bytes. If the string is longer than needed, the extra bytes are ignored.
:::
Example
Query:
sql
SELECT reinterpretAsDateTime(65), reinterpretAsDateTime('A');
Result:
response
ββreinterpretAsDateTime(65)ββ¬βreinterpretAsDateTime('A')ββ
β 1970-01-01 01:01:05 β 1970-01-01 01:01:05 β
βββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββ
reinterpretAsString {#reinterpretasstring}
This function accepts a number, date or date with time and returns a string containing bytes representing the corresponding value in host order (little endian). Null bytes are dropped from the end. For example, a UInt32 type value of 255 is a string that is one byte long.
Syntax
sql
reinterpretAsString(x)
Parameters
x
: value to reinterpret to string.
(U)Int*
,
Float
,
Date
,
DateTime
.
Returned value
String containing bytes representing
x
.
String
.
Example
Query:
sql
SELECT
reinterpretAsString(toDateTime('1970-01-01 01:01:05')),
reinterpretAsString(toDate('1970-03-07'));
Result:
response
ββreinterpretAsString(toDateTime('1970-01-01 01:01:05'))ββ¬βreinterpretAsString(toDate('1970-03-07'))ββ
β A β A β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββ
reinterpretAsFixedString {#reinterpretasfixedstring}
This function accepts a number, date or date with time and returns a FixedString containing bytes representing the corresponding value in host order (little endian). Null bytes are dropped from the end. For example, a UInt32 type value of 255 is a FixedString that is one byte long.
Syntax
sql
reinterpretAsFixedString(x)
Parameters
x
: value to reinterpret to string.
(U)Int*
,
Float
,
Date
,
DateTime
.
Returned value
Fixed string containing bytes representing
x
.
FixedString
.
Example
Query:
sql
SELECT
reinterpretAsFixedString(toDateTime('1970-01-01 01:01:05')),
reinterpretAsFixedString(toDate('1970-03-07'));
Result: | {"source_file": "type-conversion-functions.md"} | [
-0.017633581534028053,
0.02441411279141903,
-0.03179705888032913,
0.07482802867889404,
-0.09428732097148895,
-0.017100123688578606,
0.004475320223718882,
0.024200493469834328,
0.005795554723590612,
0.031340911984443665,
0.01898820698261261,
-0.04612492769956589,
0.007300269789993763,
-0.05... |
ae2ae17d-4afe-4fab-8173-7b891df3ca90 | Example
Query:
sql
SELECT
reinterpretAsFixedString(toDateTime('1970-01-01 01:01:05')),
reinterpretAsFixedString(toDate('1970-03-07'));
Result:
response
ββreinterpretAsFixedString(toDateTime('1970-01-01 01:01:05'))ββ¬βreinterpretAsFixedString(toDate('1970-03-07'))ββ
β A β A β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββββββ
reinterpretAsUUID {#reinterpretasuuid}
:::note
In addition to the UUID functions listed here, there is dedicated
UUID function documentation
.
:::
Accepts a 16 byte string and returns a UUID by interpreting each 8-byte half in little-endian byte order. If the string isn't long enough, the function works as if the string is padded with the necessary number of null bytes to the end. If the string is longer than 16 bytes, the extra bytes at the end are ignored.
Syntax
sql
reinterpretAsUUID(fixed_string)
Arguments
fixed_string
β Big-endian byte string.
FixedString
.
Returned value
The UUID type value.
UUID
.
Examples
String to UUID.
Query:
sql
SELECT reinterpretAsUUID(reverse(unhex('000102030405060708090a0b0c0d0e0f')));
Result:
response
ββreinterpretAsUUID(reverse(unhex('000102030405060708090a0b0c0d0e0f')))ββ
β 08090a0b-0c0d-0e0f-0001-020304050607 β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Going back and forth from String to UUID.
Query:
sql
WITH
generateUUIDv4() AS uuid,
identity(lower(hex(reverse(reinterpretAsString(uuid))))) AS str,
reinterpretAsUUID(reverse(unhex(str))) AS uuid2
SELECT uuid = uuid2;
Result:
response
ββequals(uuid, uuid2)ββ
β 1 β
βββββββββββββββββββββββ
reinterpret {#reinterpret}
Uses the same source in-memory bytes sequence for
x
value and reinterprets it to destination type.
Syntax
sql
reinterpret(x, type)
Arguments
x
β Any type.
type
β Destination type. If it is an array, then the array element type must be a fixed length type.
Returned value
Destination type value.
Examples
Query:
sql
SELECT reinterpret(toInt8(-1), 'UInt8') AS int_to_uint,
reinterpret(toInt8(1), 'Float32') AS int_to_float,
reinterpret('1', 'UInt32') AS string_to_int;
Result:
text
ββint_to_uintββ¬βint_to_floatββ¬βstring_to_intββ
β 255 β 1e-45 β 49 β
βββββββββββββββ΄βββββββββββββββ΄ββββββββββββββββ
Query:
sql
SELECT reinterpret(x'3108b4403108d4403108b4403108d440', 'Array(Float32)') AS string_to_array_of_Float32;
Result:
text
ββstring_to_array_of_Float32ββ
β [5.626,6.626,5.626,6.626] β
ββββββββββββββββββββββββββββββ
CAST {#cast} | {"source_file": "type-conversion-functions.md"} | [
-0.029763931408524513,
0.0034277066588401794,
-0.0009495869744569063,
0.0337546207010746,
-0.059191636741161346,
-0.0216195248067379,
0.04455442726612091,
0.006097013130784035,
-0.05291491001844406,
-0.010160038247704506,
0.0015666944673284888,
-0.007192015182226896,
0.022914566099643707,
... |
a83e5a1f-76fa-462e-a7b9-bb77c3c288a9 | Result:
text
ββstring_to_array_of_Float32ββ
β [5.626,6.626,5.626,6.626] β
ββββββββββββββββββββββββββββββ
CAST {#cast}
Converts an input value to the specified data type. Unlike the
reinterpret
function,
CAST
tries to present the same value using the new data type. If the conversion can not be done then an exception is raised.
Several syntax variants are supported.
Syntax
sql
CAST(x, T)
CAST(x AS t)
x::t
Arguments
x
β A value to convert. May be of any type.
T
β The name of the target data type.
String
.
t
β The target data type.
Returned value
Converted value.
:::note
If the input value does not fit the bounds of the target type, the result overflows. For example,
CAST(-1, 'UInt8')
returns
255
.
:::
Examples
Query:
sql
SELECT
CAST(toInt8(-1), 'UInt8') AS cast_int_to_uint,
CAST(1.5 AS Decimal(3,2)) AS cast_float_to_decimal,
'1'::Int32 AS cast_string_to_int;
Result:
yaml
ββcast_int_to_uintββ¬βcast_float_to_decimalββ¬βcast_string_to_intββ
β 255 β 1.50 β 1 β
ββββββββββββββββββββ΄ββββββββββββββββββββββββ΄βββββββββββββββββββββ
Query:
sql
SELECT
'2016-06-15 23:00:00' AS timestamp,
CAST(timestamp AS DateTime) AS datetime,
CAST(timestamp AS Date) AS date,
CAST(timestamp, 'String') AS string,
CAST(timestamp, 'FixedString(22)') AS fixed_string;
Result:
response
ββtimestampββββββββββββ¬ββββββββββββdatetimeββ¬βββββββdateββ¬βstringβββββββββββββββ¬βfixed_stringβββββββββββββββ
β 2016-06-15 23:00:00 β 2016-06-15 23:00:00 β 2016-06-15 β 2016-06-15 23:00:00 β 2016-06-15 23:00:00\0\0\0 β
βββββββββββββββββββββββ΄ββββββββββββββββββββββ΄βββββββββββββ΄ββββββββββββββββββββββ΄ββββββββββββββββββββββββββββ
Conversion to
FixedString (N)
only works for arguments of type
String
or
FixedString
.
Type conversion to
Nullable
and back is supported.
Example
Query:
sql
SELECT toTypeName(x) FROM t_null;
Result:
response
ββtoTypeName(x)ββ
β Int8 β
β Int8 β
βββββββββββββββββ
Query:
sql
SELECT toTypeName(CAST(x, 'Nullable(UInt16)')) FROM t_null;
Result:
response
ββtoTypeName(CAST(x, 'Nullable(UInt16)'))ββ
β Nullable(UInt16) β
β Nullable(UInt16) β
βββββββββββββββββββββββββββββββββββββββββββ
See also
cast_keep_nullable
setting
accurateCast(x, T) {#accuratecastx-t}
Converts
x
to the
T
data type.
The difference from
cast
is that
accurateCast
does not allow overflow of numeric types during cast if type value
x
does not fit the bounds of type
T
. For example,
accurateCast(-1, 'UInt8')
throws an exception.
Example
Query:
sql
SELECT cast(-1, 'UInt8') AS uint8;
Result:
response
ββuint8ββ
β 255 β
βββββββββ
Query:
sql
SELECT accurateCast(-1, 'UInt8') AS uint8;
Result: | {"source_file": "type-conversion-functions.md"} | [
0.03340044245123863,
-0.004589776508510113,
0.014328598976135254,
0.02721879817545414,
-0.1139410063624382,
-0.02820894680917263,
0.10135938972234726,
0.03007756546139717,
-0.0979093611240387,
0.00752769922837615,
-0.03751546889543533,
-0.043591711670160294,
0.0072594680823385715,
-0.07953... |
3ca85335-210b-454c-a0b4-c7dcd53313ea | Example
Query:
sql
SELECT cast(-1, 'UInt8') AS uint8;
Result:
response
ββuint8ββ
β 255 β
βββββββββ
Query:
sql
SELECT accurateCast(-1, 'UInt8') AS uint8;
Result:
response
Code: 70. DB::Exception: Received from localhost:9000. DB::Exception: Value in column Int8 cannot be safely converted into type UInt8: While processing accurateCast(-1, 'UInt8') AS uint8.
accurateCastOrNull(x, T) {#accuratecastornullx-t}
Converts input value
x
to the specified data type
T
. Always returns
Nullable
type and returns
NULL
if the cast value is not representable in the target type.
Syntax
sql
accurateCastOrNull(x, T)
Arguments
x
β Input value.
T
β The name of the returned data type.
Returned value
The value, converted to the specified data type
T
.
Example
Query:
sql
SELECT toTypeName(accurateCastOrNull(5, 'UInt8'));
Result:
response
ββtoTypeName(accurateCastOrNull(5, 'UInt8'))ββ
β Nullable(UInt8) β
ββββββββββββββββββββββββββββββββββββββββββββββ
Query:
sql
SELECT
accurateCastOrNull(-1, 'UInt8') AS uint8,
accurateCastOrNull(128, 'Int8') AS int8,
accurateCastOrNull('Test', 'FixedString(2)') AS fixed_string;
Result:
response
ββuint8ββ¬βint8ββ¬βfixed_stringββ
β α΄Ία΅α΄Έα΄Έ β α΄Ία΅α΄Έα΄Έ β α΄Ία΅α΄Έα΄Έ β
βββββββββ΄βββββββ΄βββββββββββββββ
accurateCastOrDefault(x, T[, default_value]) {#accuratecastordefaultx-t-default_value}
Converts input value
x
to the specified data type
T
. Returns default type value or
default_value
if specified if the cast value is not representable in the target type.
Syntax
sql
accurateCastOrDefault(x, T)
Arguments
x
β Input value.
T
β The name of the returned data type.
default_value
β Default value of returned data type.
Returned value
The value converted to the specified data type
T
.
Example
Query:
sql
SELECT toTypeName(accurateCastOrDefault(5, 'UInt8'));
Result:
response
ββtoTypeName(accurateCastOrDefault(5, 'UInt8'))ββ
β UInt8 β
βββββββββββββββββββββββββββββββββββββββββββββββββ
Query:
sql
SELECT
accurateCastOrDefault(-1, 'UInt8') AS uint8,
accurateCastOrDefault(-1, 'UInt8', 5) AS uint8_default,
accurateCastOrDefault(128, 'Int8') AS int8,
accurateCastOrDefault(128, 'Int8', 5) AS int8_default,
accurateCastOrDefault('Test', 'FixedString(2)') AS fixed_string,
accurateCastOrDefault('Test', 'FixedString(2)', 'Te') AS fixed_string_default;
Result:
response
ββuint8ββ¬βuint8_defaultββ¬βint8ββ¬βint8_defaultββ¬βfixed_stringββ¬βfixed_string_defaultββ
β 0 β 5 β 0 β 5 β β Te β
βββββββββ΄ββββββββββββββββ΄βββββββ΄βββββββββββββββ΄βββββββββββββββ΄βββββββββββββββββββββββ
toInterval {#toInterval}
Creates an
Interval
data type value from a numeric value and interval unit (eg. 'second' or 'day').
Syntax
sql
toInterval(value, unit)
Arguments | {"source_file": "type-conversion-functions.md"} | [
0.024343818426132202,
-0.022324368357658386,
-0.0029425753746181726,
0.04843160882592201,
-0.10950692743062973,
-0.029460124671459198,
0.10419458150863647,
0.039742786437273026,
-0.10306946933269501,
-0.026230977848172188,
-0.030050504952669144,
-0.08776932954788208,
0.075778067111969,
-0.... |
b632d70a-d42b-4c52-922b-a0bf7c8f8f9c | toInterval {#toInterval}
Creates an
Interval
data type value from a numeric value and interval unit (eg. 'second' or 'day').
Syntax
sql
toInterval(value, unit)
Arguments
value
β Length of the interval. Integer numbers or string representations thereof, and float numbers.
(U)Int*
/
Float*
/
String
.
unit
β The type of interval to create.
String Literal
.
Possible values:
nanosecond
microsecond
millisecond
second
minute
hour
day
week
month
quarter
year
The
unit
argument is case-insensitive.
Returned value
The resulting interval.
Interval
Example
sql
SELECT toDateTime('2025-01-01 00:00:00') + toInterval(1, 'hour')
response
ββtoDateTime('2025-01-01 00:00:00') + toInterval(1, 'hour') ββ
β 2025-01-01 01:00:00 β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
toIntervalYear {#tointervalyear}
Returns an interval of
n
years of data type
IntervalYear
.
Syntax
sql
toIntervalYear(n)
Arguments
n
β Number of years. Integer numbers or string representations thereof, and float numbers.
(U)Int*
/
Float*
/
String
.
Returned values
Interval of
n
years.
IntervalYear
.
Example
Query:
sql
WITH
toDate('2024-06-15') AS date,
toIntervalYear(1) AS interval_to_year
SELECT date + interval_to_year AS result
Result:
response
ββββββresultββ
β 2025-06-15 β
ββββββββββββββ
toIntervalQuarter {#tointervalquarter}
Returns an interval of
n
quarters of data type
IntervalQuarter
.
Syntax
sql
toIntervalQuarter(n)
Arguments
n
β Number of quarters. Integer numbers or string representations thereof, and float numbers.
(U)Int*
/
Float*
/
String
.
Returned values
Interval of
n
quarters.
IntervalQuarter
.
Example
Query:
sql
WITH
toDate('2024-06-15') AS date,
toIntervalQuarter(1) AS interval_to_quarter
SELECT date + interval_to_quarter AS result
Result:
response
ββββββresultββ
β 2024-09-15 β
ββββββββββββββ
toIntervalMonth {#tointervalmonth}
Returns an interval of
n
months of data type
IntervalMonth
.
Syntax
sql
toIntervalMonth(n)
Arguments
n
β Number of months. Integer numbers or string representations thereof, and float numbers.
(U)Int*
/
Float*
/
String
.
Returned values
Interval of
n
months.
IntervalMonth
.
Example
Query:
sql
WITH
toDate('2024-06-15') AS date,
toIntervalMonth(1) AS interval_to_month
SELECT date + interval_to_month AS result
Result:
response
ββββββresultββ
β 2024-07-15 β
ββββββββββββββ
toIntervalWeek {#tointervalweek}
Returns an interval of
n
weeks of data type
IntervalWeek
.
Syntax
sql
toIntervalWeek(n)
Arguments
n
β Number of weeks. Integer numbers or string representations thereof, and float numbers.
(U)Int*
/
Float*
/
String
.
Returned values
Interval of
n
weeks.
IntervalWeek
.
Example
Query: | {"source_file": "type-conversion-functions.md"} | [
-0.0024783380795270205,
-0.0007937957998365164,
0.019928492605686188,
0.05506415292620659,
-0.0932973176240921,
0.013034488074481487,
0.028365546837449074,
0.034328561276197433,
-0.06528332829475403,
-0.03041110374033451,
0.017163332551717758,
-0.11373177915811539,
0.0481591522693634,
0.03... |
d8a04602-06c0-4739-9615-6855610231b2 | Returned values
Interval of
n
weeks.
IntervalWeek
.
Example
Query:
sql
WITH
toDate('2024-06-15') AS date,
toIntervalWeek(1) AS interval_to_week
SELECT date + interval_to_week AS result
Result:
response
ββββββresultββ
β 2024-06-22 β
ββββββββββββββ
toIntervalDay {#tointervalday}
Returns an interval of
n
days of data type
IntervalDay
.
Syntax
sql
toIntervalDay(n)
Arguments
n
β Number of days. Integer numbers or string representations thereof, and float numbers.
(U)Int*
/
Float*
/
String
.
Returned values
Interval of
n
days.
IntervalDay
.
Example
Query:
sql
WITH
toDate('2024-06-15') AS date,
toIntervalDay(5) AS interval_to_days
SELECT date + interval_to_days AS result
Result:
response
ββββββresultββ
β 2024-06-20 β
ββββββββββββββ
toIntervalHour {#tointervalhour}
Returns an interval of
n
hours of data type
IntervalHour
.
Syntax
sql
toIntervalHour(n)
Arguments
n
β Number of hours. Integer numbers or string representations thereof, and float numbers.
(U)Int*
/
Float*
/
String
.
Returned values
Interval of
n
hours.
IntervalHour
.
Example
Query:
sql
WITH
toDate('2024-06-15') AS date,
toIntervalHour(12) AS interval_to_hours
SELECT date + interval_to_hours AS result
Result:
response
βββββββββββββββresultββ
β 2024-06-15 12:00:00 β
βββββββββββββββββββββββ
toIntervalMinute {#tointervalminute}
Returns an interval of
n
minutes of data type
IntervalMinute
.
Syntax
sql
toIntervalMinute(n)
Arguments
n
β Number of minutes. Integer numbers or string representations thereof, and float numbers.
(U)Int*
/
Float*
/
String
.
Returned values
Interval of
n
minutes.
IntervalMinute
.
Example
Query:
sql
WITH
toDate('2024-06-15') AS date,
toIntervalMinute(12) AS interval_to_minutes
SELECT date + interval_to_minutes AS result
Result:
response
βββββββββββββββresultββ
β 2024-06-15 00:12:00 β
βββββββββββββββββββββββ
toIntervalSecond {#tointervalsecond}
Returns an interval of
n
seconds of data type
IntervalSecond
.
Syntax
sql
toIntervalSecond(n)
Arguments
n
β Number of seconds. Integer numbers or string representations thereof, and float numbers.
(U)Int*
/
Float*
/
String
.
Returned values
Interval of
n
seconds.
IntervalSecond
.
Example
Query:
sql
WITH
toDate('2024-06-15') AS date,
toIntervalSecond(30) AS interval_to_seconds
SELECT date + interval_to_seconds AS result
Result:
response
βββββββββββββββresultββ
β 2024-06-15 00:00:30 β
βββββββββββββββββββββββ
toIntervalMillisecond {#tointervalmillisecond}
Returns an interval of
n
milliseconds of data type
IntervalMillisecond
.
Syntax
sql
toIntervalMillisecond(n)
Arguments
n
β Number of milliseconds. Integer numbers or string representations thereof, and float numbers.
(U)Int*
/
Float*
/
String
.
Returned values
Interval of
n
milliseconds.
IntervalMilliseconds
.
Example | {"source_file": "type-conversion-functions.md"} | [
-0.03394698351621628,
0.034002043306827545,
0.012607582844793797,
0.0873304232954979,
-0.0926942452788353,
-0.009148865938186646,
0.03193758800625801,
0.029444711282849312,
-0.08040904998779297,
-0.039724692702293396,
-0.032051168382167816,
-0.09302514046430588,
0.024671101942658424,
-0.01... |
edc005f6-250e-4ab5-8824-9cf058f72ff8 | Returned values
Interval of
n
milliseconds.
IntervalMilliseconds
.
Example
Query:
sql
WITH
toDateTime('2024-06-15') AS date,
toIntervalMillisecond(30) AS interval_to_milliseconds
SELECT date + interval_to_milliseconds AS result
Result:
response
βββββββββββββββββββresultββ
β 2024-06-15 00:00:00.030 β
βββββββββββββββββββββββββββ
toIntervalMicrosecond {#tointervalmicrosecond}
Returns an interval of
n
microseconds of data type
IntervalMicrosecond
.
Syntax
sql
toIntervalMicrosecond(n)
Arguments
n
β Number of microseconds. Integer numbers or string representations thereof, and float numbers.
(U)Int*
/
Float*
/
String
.
Returned values
Interval of
n
microseconds.
IntervalMicrosecond
.
Example
Query:
sql
WITH
toDateTime('2024-06-15') AS date,
toIntervalMicrosecond(30) AS interval_to_microseconds
SELECT date + interval_to_microseconds AS result
Result:
response
ββββββββββββββββββββββresultββ
β 2024-06-15 00:00:00.000030 β
ββββββββββββββββββββββββββββββ
toIntervalNanosecond {#tointervalnanosecond}
Returns an interval of
n
nanoseconds of data type
IntervalNanosecond
.
Syntax
sql
toIntervalNanosecond(n)
Arguments
n
β Number of nanoseconds. Integer numbers or string representations thereof, and float numbers.
(U)Int*
/
Float*
/
String
.
Returned values
Interval of
n
nanoseconds.
IntervalNanosecond
.
Example
Query:
sql
WITH
toDateTime('2024-06-15') AS date,
toIntervalNanosecond(30) AS interval_to_nanoseconds
SELECT date + interval_to_nanoseconds AS result
Result:
response
βββββββββββββββββββββββββresultββ
β 2024-06-15 00:00:00.000000030 β
βββββββββββββββββββββββββββββββββ
parseDateTime {#parsedatetime}
Converts a
String
to
DateTime
according to a
MySQL format string
.
This function is the opposite operation of function
formatDateTime
.
Syntax
sql
parseDateTime(str[, format[, timezone]])
Arguments
str
β The String to be parsed
format
β The format string. Optional.
%Y-%m-%d %H:%i:%s
if not specified.
timezone
β
Timezone
. Optional.
Returned value(s)
Return a
DateTime
value parsed from the input string according to a MySQL-style format string.
Supported format specifiers
All format specifiers listed in
formatDateTime
except:
- %Q: Quarter (1-4)
Example
```sql
SELECT parseDateTime('2021-01-04+23:00:00', '%Y-%m-%d+%H:%i:%s')
ββparseDateTime('2021-01-04+23:00:00', '%Y-%m-%d+%H:%i:%s')ββ
β 2021-01-04 23:00:00 β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
Alias:
TO_TIMESTAMP
.
parseDateTimeOrZero {#parsedatetimeorzero}
Same as for
parseDateTime
except that it returns zero date when it encounters a date format that cannot be processed.
parseDateTimeOrNull {#parsedatetimeornull}
Same as for
parseDateTime
except that it returns
NULL
when it encounters a date format that cannot be processed.
Alias:
str_to_date
. | {"source_file": "type-conversion-functions.md"} | [
-0.0010594716295599937,
-0.018524490296840668,
-0.013645215891301632,
0.07734409719705582,
-0.06760863959789276,
-0.006709540728479624,
0.019044335931539536,
0.08023834973573685,
-0.00783463940024376,
-0.013097461313009262,
0.022506700828671455,
-0.11419934034347534,
0.003919141832739115,
... |
9d148350-60a1-49a8-8f39-51b22ad9a3a4 | parseDateTimeOrNull {#parsedatetimeornull}
Same as for
parseDateTime
except that it returns
NULL
when it encounters a date format that cannot be processed.
Alias:
str_to_date
.
parseDateTimeInJodaSyntax {#parsedatetimeinjodasyntax}
Similar to
parseDateTime
, except that the format string is in
Joda
instead of MySQL syntax.
This function is the opposite operation of function
formatDateTimeInJodaSyntax
.
Syntax
sql
parseDateTimeInJodaSyntax(str[, format[, timezone]])
Arguments
str
β The String to be parsed
format
β The format string. Optional.
yyyy-MM-dd HH:mm:ss
if not specified.
timezone
β
Timezone
. Optional.
Returned value(s)
Return a
DateTime
value parsed from the input string according to a Joda-style format string.
Supported format specifiers
All format specifiers listed in
formatDateTimeInJodaSyntax
are supported, except:
- S: fraction of second
- z: time zone
- Z: time zone offset/id
Example
```sql
SELECT parseDateTimeInJodaSyntax('2023-02-24 14:53:31', 'yyyy-MM-dd HH:mm:ss', 'Europe/Minsk')
ββparseDateTimeInJodaSyntax('2023-02-24 14:53:31', 'yyyy-MM-dd HH:mm:ss', 'Europe/Minsk')ββ
β 2023-02-24 14:53:31 β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
parseDateTimeInJodaSyntaxOrZero {#parsedatetimeinjodasyntaxorzero}
Same as for
parseDateTimeInJodaSyntax
except that it returns zero date when it encounters a date format that cannot be processed.
parseDateTimeInJodaSyntaxOrNull {#parsedatetimeinjodasyntaxornull}
Same as for
parseDateTimeInJodaSyntax
except that it returns
NULL
when it encounters a date format that cannot be processed.
parseDateTime64 {#parsedatetime64}
Converts a
String
to
DateTime64
according to a
MySQL format string
.
Syntax
sql
parseDateTime64(str[, format[, timezone]])
Arguments
str
β The String to be parsed.
format
β The format string. Optional.
%Y-%m-%d %H:%i:%s.%f
if not specified.
timezone
β
Timezone
. Optional.
Returned value(s)
Return a
DateTime64
value parsed from the input string according to a MySQL-style format string.
The precision of the returned value is 6.
parseDateTime64OrZero {#parsedatetime64orzero}
Same as for
parseDateTime64
except that it returns zero date when it encounters a date format that cannot be processed.
parseDateTime64OrNull {#parsedatetime64ornull}
Same as for
parseDateTime64
except that it returns
NULL
when it encounters a date format that cannot be processed.
parseDateTime64InJodaSyntax {#parsedatetime64injodasyntax}
Converts a
String
to
DateTime64
according to a
Joda format string
.
Syntax
sql
parseDateTime64InJodaSyntax(str[, format[, timezone]])
Arguments
str
β The String to be parsed.
format
β The format string. Optional.
yyyy-MM-dd HH:mm:ss
if not specified.
timezone
β
Timezone
. Optional.
Returned value(s) | {"source_file": "type-conversion-functions.md"} | [
0.02579142153263092,
0.03173336759209633,
-0.015484398230910301,
0.01186096016317606,
-0.04444039240479469,
-0.019233785569667816,
0.0067499722354114056,
0.08310338854789734,
-0.01585335284471512,
-0.028532514348626137,
-0.04142550006508827,
-0.09269468486309052,
-0.003236363874748349,
0.0... |
c40ae578-3901-4117-ac70-724492e65033 | Arguments
str
β The String to be parsed.
format
β The format string. Optional.
yyyy-MM-dd HH:mm:ss
if not specified.
timezone
β
Timezone
. Optional.
Returned value(s)
Return a
DateTime64
value parsed from the input string according to a Joda-style format string.
The precision of the returned value equal to the number of
S
placeholders in the format string (but at most 6).
parseDateTime64InJodaSyntaxOrZero {#parsedatetime64injodasyntaxorzero}
Same as for
parseDateTime64InJodaSyntax
except that it returns zero date when it encounters a date format that cannot be processed.
parseDateTime64InJodaSyntaxOrNull {#parsedatetime64injodasyntaxornull}
Same as for
parseDateTime64InJodaSyntax
except that it returns
NULL
when it encounters a date format that cannot be processed.
parseDateTimeBestEffort {#parsedatetimebesteffort}
parseDateTime32BestEffort {#parsedatetime32besteffort}
Converts a date and time in the
String
representation to
DateTime
data type.
The function parses
ISO 8601
,
RFC 1123 - 5.2.14 RFC-822 Date and Time Specification
, ClickHouse's and some other date and time formats.
Syntax
sql
parseDateTimeBestEffort(time_string [, time_zone])
Arguments
time_string
β String containing a date and time to convert.
String
.
time_zone
β Time zone. The function parses
time_string
according to the time zone.
String
.
Supported non-standard formats
A string containing 9..10 digit
unix timestamp
.
A string with a date and a time component:
YYYYMMDDhhmmss
,
DD/MM/YYYY hh:mm:ss
,
DD-MM-YY hh:mm
,
YYYY-MM-DD hh:mm:ss
, etc.
A string with a date, but no time component:
YYYY
,
YYYYMM
,
YYYY*MM
,
DD/MM/YYYY
,
DD-MM-YY
etc.
A string with a day and time:
DD
,
DD hh
,
DD hh:mm
. In this case
MM
is substituted by
01
.
A string that includes the date and time along with time zone offset information:
YYYY-MM-DD hh:mm:ss Β±h:mm
, etc. For example,
2020-12-12 17:36:00 -5:00
.
A
syslog timestamp
:
Mmm dd hh:mm:ss
. For example,
Jun 9 14:20:32
.
For all of the formats with separator the function parses months names expressed by their full name or by the first three letters of a month name. Examples:
24/DEC/18
,
24-Dec-18
,
01-September-2018
.
If the year is not specified, it is considered to be equal to the current year. If the resulting DateTime happen to be in the future (even by a second after the current moment), then the current year is substituted by the previous year.
Returned value
time_string
converted to the
DateTime
data type.
Examples
Query:
sql
SELECT parseDateTimeBestEffort('23/10/2020 12:12:57')
AS parseDateTimeBestEffort;
Result:
response
ββparseDateTimeBestEffortββ
β 2020-10-23 12:12:57 β
βββββββββββββββββββββββββββ
Query:
sql
SELECT parseDateTimeBestEffort('Sat, 18 Aug 2018 07:22:16 GMT', 'Asia/Istanbul')
AS parseDateTimeBestEffort;
Result: | {"source_file": "type-conversion-functions.md"} | [
0.031845442950725555,
0.057568661868572235,
-0.06796922534704208,
0.008054319769144058,
-0.04562355950474739,
0.01838342472910881,
-0.0871090218424797,
0.03158963844180107,
0.004112016875296831,
-0.04993756115436554,
-0.032568395137786865,
-0.04731111228466034,
-0.05388675257563591,
-0.015... |
eda20d8e-6617-4a5e-bc4f-1afeff98c22e | Query:
sql
SELECT parseDateTimeBestEffort('Sat, 18 Aug 2018 07:22:16 GMT', 'Asia/Istanbul')
AS parseDateTimeBestEffort;
Result:
response
ββparseDateTimeBestEffortββ
β 2018-08-18 10:22:16 β
βββββββββββββββββββββββββββ
Query:
sql
SELECT parseDateTimeBestEffort('1284101485')
AS parseDateTimeBestEffort;
Result:
response
ββparseDateTimeBestEffortββ
β 2015-07-07 12:04:41 β
βββββββββββββββββββββββββββ
Query:
sql
SELECT parseDateTimeBestEffort('2018-10-23 10:12:12')
AS parseDateTimeBestEffort;
Result:
response
ββparseDateTimeBestEffortββ
β 2018-10-23 10:12:12 β
βββββββββββββββββββββββββββ
Query:
sql
SELECT toYear(now()) AS year, parseDateTimeBestEffort('10 20:19');
Result:
response
ββyearββ¬βparseDateTimeBestEffort('10 20:19')ββ
β 2023 β 2023-01-10 20:19:00 β
ββββββββ΄ββββββββββββββββββββββββββββββββββββββ
Query:
sql
WITH
now() AS ts_now,
formatDateTime(ts_around, '%b %e %T') AS syslog_arg
SELECT
ts_now,
syslog_arg,
parseDateTimeBestEffort(syslog_arg)
FROM (SELECT arrayJoin([ts_now - 30, ts_now + 30]) AS ts_around);
Result:
response
βββββββββββββββts_nowββ¬βsyslog_argβββββββ¬βparseDateTimeBestEffort(syslog_arg)ββ
β 2023-06-30 23:59:30 β Jun 30 23:59:00 β 2023-06-30 23:59:00 β
β 2023-06-30 23:59:30 β Jul 1 00:00:00 β 2022-07-01 00:00:00 β
βββββββββββββββββββββββ΄ββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββ
See also
RFC 1123
toDate
toDateTime
ISO 8601 announcement by @xkcd
RFC 3164
parseDateTimeBestEffortUS {#parsedatetimebesteffortus}
This function behaves like
parseDateTimeBestEffort
for ISO date formats, e.g.
YYYY-MM-DD hh:mm:ss
, and other date formats where the month and date components can be unambiguously extracted, e.g.
YYYYMMDDhhmmss
,
YYYY-MM
,
DD hh
, or
YYYY-MM-DD hh:mm:ss Β±h:mm
. If the month and the date components cannot be unambiguously extracted, e.g.
MM/DD/YYYY
,
MM-DD-YYYY
, or
MM-DD-YY
, it prefers the US date format instead of
DD/MM/YYYY
,
DD-MM-YYYY
, or
DD-MM-YY
. As an exception from the latter, if the month is bigger than 12 and smaller or equal than 31, this function falls back to the behavior of
parseDateTimeBestEffort
, e.g.
15/08/2020
is parsed as
2020-08-15
.
parseDateTimeBestEffortOrNull {#parsedatetimebesteffortornull}
parseDateTime32BestEffortOrNull {#parsedatetime32besteffortornull}
Same as for
parseDateTimeBestEffort
except that it returns
NULL
when it encounters a date format that cannot be processed.
parseDateTimeBestEffortOrZero {#parsedatetimebesteffortorzero}
parseDateTime32BestEffortOrZero {#parsedatetime32besteffortorzero}
Same as for
parseDateTimeBestEffort
except that it returns zero date or zero date time when it encounters a date format that cannot be processed.
parseDateTimeBestEffortUSOrNull {#parsedatetimebesteffortusornull} | {"source_file": "type-conversion-functions.md"} | [
0.0036844632122665644,
-0.012726180255413055,
0.026528602465987206,
0.03776298090815544,
-0.03884339705109596,
-0.0047369408421218395,
0.05710950493812561,
0.03386537358164787,
0.01654442958533764,
0.020428454503417015,
0.010867144912481308,
-0.05494222790002823,
-0.05878453329205513,
0.01... |
43377779-6299-4ef7-a2ce-e1808aa9e266 | parseDateTimeBestEffortUSOrNull {#parsedatetimebesteffortusornull}
Same as
parseDateTimeBestEffortUS
function except that it returns
NULL
when it encounters a date format that cannot be processed.
parseDateTimeBestEffortUSOrZero {#parsedatetimebesteffortusorzero}
Same as
parseDateTimeBestEffortUS
function except that it returns zero date (
1970-01-01
) or zero date with time (
1970-01-01 00:00:00
) when it encounters a date format that cannot be processed.
parseDateTime64BestEffort {#parsedatetime64besteffort}
Same as
parseDateTimeBestEffort
function but also parse milliseconds and microseconds and returns
DateTime
data type.
Syntax
sql
parseDateTime64BestEffort(time_string [, precision [, time_zone]])
Arguments
time_string
β String containing a date or date with time to convert.
String
.
precision
β Required precision.
3
β for milliseconds,
6
β for microseconds. Default β
3
. Optional.
UInt8
.
time_zone
β
Timezone
. The function parses
time_string
according to the timezone. Optional.
String
.
Returned value
time_string
converted to the
DateTime
data type.
Examples
Query:
sql
SELECT parseDateTime64BestEffort('2021-01-01') AS a, toTypeName(a) AS t
UNION ALL
SELECT parseDateTime64BestEffort('2021-01-01 01:01:00.12346') AS a, toTypeName(a) AS t
UNION ALL
SELECT parseDateTime64BestEffort('2021-01-01 01:01:00.12346',6) AS a, toTypeName(a) AS t
UNION ALL
SELECT parseDateTime64BestEffort('2021-01-01 01:01:00.12346',3,'Asia/Istanbul') AS a, toTypeName(a) AS t
FORMAT PrettyCompactMonoBlock;
Result:
sql
βββββββββββββββββββββββββββaββ¬βtβββββββββββββββββββββββββββββββ
β 2021-01-01 01:01:00.123000 β DateTime64(3) β
β 2021-01-01 00:00:00.000000 β DateTime64(3) β
β 2021-01-01 01:01:00.123460 β DateTime64(6) β
β 2020-12-31 22:01:00.123000 β DateTime64(3, 'Asia/Istanbul') β
ββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββ
parseDateTime64BestEffortUS {#parsedatetime64besteffortus}
Same as for
parseDateTime64BestEffort
, except that this function prefers US date format (
MM/DD/YYYY
etc.) in case of ambiguity.
parseDateTime64BestEffortOrNull {#parsedatetime64besteffortornull}
Same as for
parseDateTime64BestEffort
except that it returns
NULL
when it encounters a date format that cannot be processed.
parseDateTime64BestEffortOrZero {#parsedatetime64besteffortorzero}
Same as for
parseDateTime64BestEffort
except that it returns zero date or zero date time when it encounters a date format that cannot be processed.
parseDateTime64BestEffortUSOrNull {#parsedatetime64besteffortusornull}
Same as for
parseDateTime64BestEffort
, except that this function prefers US date format (
MM/DD/YYYY
etc.) in case of ambiguity and returns
NULL
when it encounters a date format that cannot be processed.
parseDateTime64BestEffortUSOrZero {#parsedatetime64besteffortusorzero} | {"source_file": "type-conversion-functions.md"} | [
0.032715845853090286,
-0.018602823838591576,
-0.032961808145046234,
0.030333612114191055,
-0.015289605595171452,
-0.013753007166087627,
-0.009535592049360275,
0.09619304537773132,
-0.021036481484770775,
0.008841972798109055,
-0.02645930089056492,
-0.0808434933423996,
-0.034140583127737045,
... |
db140826-aeba-465e-a953-50ace604dc2a | parseDateTime64BestEffortUSOrZero {#parsedatetime64besteffortusorzero}
Same as for
parseDateTime64BestEffort
, except that this function prefers US date format (
MM/DD/YYYY
etc.) in case of ambiguity and returns zero date or zero date time when it encounters a date format that cannot be processed.
toLowCardinality {#tolowcardinality}
Converts input parameter to the
LowCardinality
version of same data type.
To convert data from the
LowCardinality
data type use the
CAST
function. For example,
CAST(x as String)
.
Syntax
sql
toLowCardinality(expr)
Arguments
expr
β
Expression
resulting in one of the
supported data types
.
Returned values
Result of
expr
.
LowCardinality
of the type of
expr
.
Example
Query:
sql
SELECT toLowCardinality('1');
Result:
response
ββtoLowCardinality('1')ββ
β 1 β
βββββββββββββββββββββββββ
toUnixTimestamp {#toUnixTimestamp}
Converts a
String
,
Date
, or
DateTime
to a Unix timestamp (seconds since
1970-01-01 00:00:00 UTC
) as
UInt32
.
Syntax
sql
toUnixTimestamp(date, [timezone])
Arguments
date
: Value to convert.
Date
or
Date32
or
DateTime
or
DateTime64
or
String
.
timezone
: Optional. Timezone to use for conversion. If not specified, the server's timezone is used.
String
Returned value
Returns the Unix timestamp.
UInt32
Examples
Usage example
sql title="Query"
SELECT
'2017-11-05 08:07:47' AS dt_str,
toUnixTimestamp(dt_str) AS from_str,
toUnixTimestamp(dt_str, 'Asia/Tokyo') AS from_str_tokyo,
toUnixTimestamp(toDateTime(dt_str)) AS from_datetime,
toUnixTimestamp(toDateTime64(dt_str, 0)) AS from_datetime64,
toUnixTimestamp(toDate(dt_str)) AS from_date,
toUnixTimestamp(toDate32(dt_str)) AS from_date32
FORMAT Vertical;
response title="Response"
Row 1:
ββββββ
dt_str: 2017-11-05 08:07:47
from_str: 1509869267
from_str_tokyo: 1509836867
from_datetime: 1509869267
from_datetime64: 1509869267
from_date: 1509840000
from_date32: 1509840000
toUnixTimestamp64Second {#tounixtimestamp64second}
Converts a
DateTime64
to a
Int64
value with fixed second precision. The input value is scaled up or down appropriately depending on its precision.
:::note
The output value is a timestamp in UTC, not in the timezone of
DateTime64
.
:::
Syntax
sql
toUnixTimestamp64Second(value)
Arguments
value
β DateTime64 value with any precision.
DateTime64
.
Returned value
value
converted to the
Int64
data type.
Int64
.
Example
Query:
sql
WITH toDateTime64('2009-02-13 23:31:31.011', 3, 'UTC') AS dt64
SELECT toUnixTimestamp64Second(dt64);
Result:
response
ββtoUnixTimestamp64Second(dt64)ββ
β 1234567891 β
βββββββββββββββββββββββββββββββββ
toUnixTimestamp64Milli {#tounixtimestamp64milli}
Converts a
DateTime64
to a
Int64
value with fixed millisecond precision. The input value is scaled up or down appropriately depending on its precision. | {"source_file": "type-conversion-functions.md"} | [
0.08436721563339233,
0.03807196393609047,
-0.0581737756729126,
0.06033778190612793,
-0.05010513961315155,
-0.002231323393061757,
0.014604007825255394,
0.11619054526090622,
-0.05368323624134064,
-0.03173069283366203,
-0.02125607430934906,
-0.09215262532234192,
0.004310670308768749,
-0.00339... |
34ab9533-f786-457e-a26f-50c2f7e225c4 | Converts a
DateTime64
to a
Int64
value with fixed millisecond precision. The input value is scaled up or down appropriately depending on its precision.
:::note
The output value is a timestamp in UTC, not in the timezone of
DateTime64
.
:::
Syntax
sql
toUnixTimestamp64Milli(value)
Arguments
value
β DateTime64 value with any precision.
DateTime64
.
Returned value
value
converted to the
Int64
data type.
Int64
.
Example
Query:
sql
WITH toDateTime64('2009-02-13 23:31:31.011', 3, 'UTC') AS dt64
SELECT toUnixTimestamp64Milli(dt64);
Result:
response
ββtoUnixTimestamp64Milli(dt64)ββ
β 1234567891011 β
ββββββββββββββββββββββββββββββββ
toUnixTimestamp64Micro {#tounixtimestamp64micro}
Converts a
DateTime64
to a
Int64
value with fixed microsecond precision. The input value is scaled up or down appropriately depending on its precision.
:::note
The output value is a timestamp in UTC, not in the timezone of
DateTime64
.
:::
Syntax
sql
toUnixTimestamp64Micro(value)
Arguments
value
β DateTime64 value with any precision.
DateTime64
.
Returned value
value
converted to the
Int64
data type.
Int64
.
Example
Query:
sql
WITH toDateTime64('1970-01-15 06:56:07.891011', 6, 'UTC') AS dt64
SELECT toUnixTimestamp64Micro(dt64);
Result:
response
ββtoUnixTimestamp64Micro(dt64)ββ
β 1234567891011 β
ββββββββββββββββββββββββββββββββ
toUnixTimestamp64Nano {#tounixtimestamp64nano}
Converts a
DateTime64
to a
Int64
value with fixed nanosecond precision. The input value is scaled up or down appropriately depending on its precision.
:::note
The output value is a timestamp in UTC, not in the timezone of
DateTime64
.
:::
Syntax
sql
toUnixTimestamp64Nano(value)
Arguments
value
β DateTime64 value with any precision.
DateTime64
.
Returned value
value
converted to the
Int64
data type.
Int64
.
Example
Query:
sql
WITH toDateTime64('1970-01-01 00:20:34.567891011', 9, 'UTC') AS dt64
SELECT toUnixTimestamp64Nano(dt64);
Result:
response
ββtoUnixTimestamp64Nano(dt64)ββ
β 1234567891011 β
βββββββββββββββββββββββββββββββ
fromUnixTimestamp64Second {#fromunixtimestamp64second}
Converts an
Int64
to a
DateTime64
value with fixed second precision and optional timezone. The input value is scaled up or down appropriately depending on its precision.
:::note
Please note that input value is treated as a UTC timestamp, not timestamp at the given (or implicit) timezone.
:::
Syntax
sql
fromUnixTimestamp64Second(value[, timezone])
Arguments
value
β value with any precision.
Int64
.
timezone
β (optional) timezone name of the result.
String
.
Returned value
value
converted to DateTime64 with precision
0
.
DateTime64
.
Example
Query:
sql
WITH CAST(1733935988, 'Int64') AS i64
SELECT
fromUnixTimestamp64Second(i64, 'UTC') AS x,
toTypeName(x);
Result: | {"source_file": "type-conversion-functions.md"} | [
0.04051205888390541,
0.013627302832901478,
-0.06235962733626366,
0.043452873826026917,
-0.041481874883174896,
0.0008344129892066121,
-0.028318168595433235,
0.05337349697947502,
-0.000298288679914549,
-0.0059294318780303,
-0.0024005863815546036,
-0.08901512622833252,
0.016067195683717728,
-... |
d6baccd6-7d25-41e5-80ec-c35145c78902 | Example
Query:
sql
WITH CAST(1733935988, 'Int64') AS i64
SELECT
fromUnixTimestamp64Second(i64, 'UTC') AS x,
toTypeName(x);
Result:
response
ββββββββββββββββββββxββ¬βtoTypeName(x)βββββββββ
β 2024-12-11 16:53:08 β DateTime64(0, 'UTC') β
βββββββββββββββββββββββ΄βββββββββββββββββββββββ
fromUnixTimestamp64Milli {#fromunixtimestamp64milli}
Converts an
Int64
to a
DateTime64
value with fixed millisecond precision and optional timezone. The input value is scaled up or down appropriately depending on its precision.
:::note
Please note that input value is treated as a UTC timestamp, not timestamp at the given (or implicit) timezone.
:::
Syntax
sql
fromUnixTimestamp64Milli(value[, timezone])
Arguments
value
β value with any precision.
Int64
.
timezone
β (optional) timezone name of the result.
String
.
Returned value
value
converted to DateTime64 with precision
3
.
DateTime64
.
Example
Query:
sql
WITH CAST(1733935988123, 'Int64') AS i64
SELECT
fromUnixTimestamp64Milli(i64, 'UTC') AS x,
toTypeName(x);
Result:
response
ββββββββββββββββββββββββxββ¬βtoTypeName(x)βββββββββ
β 2024-12-11 16:53:08.123 β DateTime64(3, 'UTC') β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββ
fromUnixTimestamp64Micro {#fromunixtimestamp64micro}
Converts an
Int64
to a
DateTime64
value with fixed microsecond precision and optional timezone. The input value is scaled up or down appropriately depending on its precision.
:::note
Please note that input value is treated as a UTC timestamp, not timestamp at the given (or implicit) timezone.
:::
Syntax
sql
fromUnixTimestamp64Micro(value[, timezone])
Arguments
value
β value with any precision.
Int64
.
timezone
β (optional) timezone name of the result.
String
.
Returned value
value
converted to DateTime64 with precision
6
.
DateTime64
.
Example
Query:
sql
WITH CAST(1733935988123456, 'Int64') AS i64
SELECT
fromUnixTimestamp64Micro(i64, 'UTC') AS x,
toTypeName(x);
Result:
response
βββββββββββββββββββββββββββxββ¬βtoTypeName(x)βββββββββ
β 2024-12-11 16:53:08.123456 β DateTime64(6, 'UTC') β
ββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββ
fromUnixTimestamp64Nano {#fromunixtimestamp64nano}
Converts an
Int64
to a
DateTime64
value with fixed nanosecond precision and optional timezone. The input value is scaled up or down appropriately depending on its precision.
:::note
Please note that input value is treated as a UTC timestamp, not timestamp at the given (or implicit) timezone.
:::
Syntax
sql
fromUnixTimestamp64Nano(value[, timezone])
Arguments
value
β value with any precision.
Int64
.
timezone
β (optional) timezone name of the result.
String
.
Returned value
value
converted to DateTime64 with precision
9
.
DateTime64
.
Example
Query:
sql
WITH CAST(1733935988123456789, 'Int64') AS i64
SELECT
fromUnixTimestamp64Nano(i64, 'UTC') AS x,
toTypeName(x);
Result: | {"source_file": "type-conversion-functions.md"} | [
0.06250934302806854,
0.02244637906551361,
-0.0734245628118515,
0.03941669315099716,
-0.07979699224233627,
-0.017113300040364265,
0.01270473375916481,
0.06706070154905319,
-0.03295502811670303,
-0.008907608687877655,
-0.041612859815359116,
-0.09886442124843597,
0.030778352171182632,
-0.0079... |
798ed8df-b98e-43b6-ba57-a65a9e9d71b4 | Example
Query:
sql
WITH CAST(1733935988123456789, 'Int64') AS i64
SELECT
fromUnixTimestamp64Nano(i64, 'UTC') AS x,
toTypeName(x);
Result:
response
ββββββββββββββββββββββββββββββxββ¬βtoTypeName(x)βββββββββ
β 2024-12-11 16:53:08.123456789 β DateTime64(9, 'UTC') β
βββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββ
formatRow {#formatrow}
Converts arbitrary expressions into a string via given format.
Syntax
sql
formatRow(format, x, y, ...)
Arguments
format
β Text format. For example,
CSV
,
TabSeparated (TSV)
.
x
,
y
, ... β Expressions.
Returned value
A formatted string. (for text formats it's usually terminated with the new line character).
Example
Query:
sql
SELECT formatRow('CSV', number, 'good')
FROM numbers(3);
Result:
response
ββformatRow('CSV', number, 'good')ββ
β 0,"good"
β
β 1,"good"
β
β 2,"good"
β
ββββββββββββββββββββββββββββββββββββ
Note
: If format contains suffix/prefix, it will be written in each row.
Example
Query:
sql
SELECT formatRow('CustomSeparated', number, 'good')
FROM numbers(3)
SETTINGS format_custom_result_before_delimiter='<prefix>\n', format_custom_result_after_delimiter='<suffix>'
Result:
response
ββformatRow('CustomSeparated', number, 'good')ββ
β <prefix>
0 good
<suffix> β
β <prefix>
1 good
<suffix> β
β <prefix>
2 good
<suffix> β
ββββββββββββββββββββββββββββββββββββββββββββββββ
Note: Only row-based formats are supported in this function.
formatRowNoNewline {#formatrownonewline}
Converts arbitrary expressions into a string via given format. Differs from formatRow in that this function trims the last
\n
if any.
Syntax
sql
formatRowNoNewline(format, x, y, ...)
Arguments
format
β Text format. For example,
CSV
,
TabSeparated (TSV)
.
x
,
y
, ... β Expressions.
Returned value
A formatted string.
Example
Query:
sql
SELECT formatRowNoNewline('CSV', number, 'good')
FROM numbers(3);
Result:
response
ββformatRowNoNewline('CSV', number, 'good')ββ
β 0,"good" β
β 1,"good" β
β 2,"good" β
βββββββββββββββββββββββββββββββββββββββββββββ | {"source_file": "type-conversion-functions.md"} | [
0.04039397090673447,
0.013193387538194656,
-0.024688705801963806,
0.034246575087308884,
-0.09996821731328964,
0.03708863630890846,
0.030440255999565125,
0.05652867257595062,
-0.022178510203957558,
0.008019095286726952,
-0.038001470267772675,
-0.050843462347984314,
0.05384242162108421,
-0.0... |
16cd4485-a21f-4903-bdbd-40f1dc1ae17e | description: 'Overview of external dictionaries functionality in ClickHouse'
sidebar_label: 'Defining Dictionaries'
sidebar_position: 35
slug: /sql-reference/dictionaries
title: 'Dictionaries'
doc_type: 'reference'
import SelfManaged from '@site/docs/_snippets/_self_managed_only_no_roadmap.md';
import CloudDetails from '@site/docs/sql-reference/dictionaries/_snippet_dictionary_in_cloud.md';
import CloudNotSupportedBadge from '@theme/badges/CloudNotSupportedBadge';
Dictionaries
A dictionary is a mapping (
key -> attributes
) that is convenient for various types of reference lists.
ClickHouse supports special functions for working with dictionaries that can be used in queries. It is easier and more efficient to use dictionaries with functions than a
JOIN
with reference tables.
ClickHouse supports:
Dictionaries with a
set of functions
.
Embedded dictionaries
with a specific
set of functions
.
:::tip Tutorial
If you are getting started with Dictionaries in ClickHouse we have a tutorial that covers that topic. Take a look
here
.
:::
You can add your own dictionaries from various data sources. The source for a dictionary can be a ClickHouse table, a local text or executable file, an HTTP(s) resource, or another DBMS. For more information, see "
Dictionary Sources
".
ClickHouse:
Fully or partially stores dictionaries in RAM.
Periodically updates dictionaries and dynamically loads missing values. In other words, dictionaries can be loaded dynamically.
Allows creating dictionaries with xml files or
DDL queries
.
The configuration of dictionaries can be located in one or more xml-files. The path to the configuration is specified in the
dictionaries_config
parameter.
Dictionaries can be loaded at server startup or at first use, depending on the
dictionaries_lazy_load
setting.
The
dictionaries
system table contains information about dictionaries configured at server. For each dictionary you can find there:
Status of the dictionary.
Configuration parameters.
Metrics like amount of RAM allocated for the dictionary or a number of queries since the dictionary was successfully loaded.
Creating a dictionary with a DDL query {#creating-a-dictionary-with-a-ddl-query}
Dictionaries can be created with
DDL queries
, and this is the recommended method because with DDL created dictionaries:
- No additional records are added to server configuration files.
- The dictionaries can be worked with as first-class entities, like tables or views.
- Data can be read directly, using familiar SELECT rather than dictionary table functions. Note that when accessing a dictionary directly via a SELECT statement, cached dictionary will return only cached data, while non-cached dictionary - will return all of the data that it stores.
- The dictionaries can be easily renamed.
Creating a dictionary with a configuration file {#creating-a-dictionary-with-a-configuration-file} | {"source_file": "index.md"} | [
-0.0236422810703516,
0.005949774291366339,
-0.04412141442298889,
0.015228133648633957,
0.0044370549730956554,
-0.036927491426467896,
0.06681393086910248,
-0.013787813484668732,
-0.0518445186316967,
-0.0035851402208209038,
0.02994612790644169,
-0.011634941212832928,
0.09764227271080017,
-0.... |
55a71ab1-2b1c-4fbc-9159-8f35976575b6 | Creating a dictionary with a configuration file {#creating-a-dictionary-with-a-configuration-file}
:::note
Creating a dictionary with a configuration file is not applicable to ClickHouse Cloud. Please use DDL (see above), and create your dictionary as user
default
.
:::
The dictionary configuration file has the following format:
```xml
An optional element with any content. Ignored by the ClickHouse server.
<!--Optional element. File name with substitutions-->
<include_from>/etc/metrika.xml</include_from>
<dictionary>
<!-- Dictionary configuration. -->
<!-- There can be any number of dictionary sections in a configuration file. -->
</dictionary>
```
You can
configure
any number of dictionaries in the same file.
:::note
You can convert values for a small dictionary by describing it in a
SELECT
query (see the
transform
function). This functionality is not related to dictionaries.
:::
Configuring a Dictionary {#configuring-a-dictionary}
If dictionary is configured using xml file, than dictionary configuration has the following structure:
```xml
dict_name
<structure>
<!-- Complex key configuration -->
</structure>
<source>
<!-- Source configuration -->
</source>
<layout>
<!-- Memory layout configuration -->
</layout>
<lifetime>
<!-- Lifetime of dictionary in memory -->
</lifetime>
```
Corresponding
DDL-query
has the following structure:
sql
CREATE DICTIONARY dict_name
(
... -- attributes
)
PRIMARY KEY ... -- complex or single key configuration
SOURCE(...) -- Source configuration
LAYOUT(...) -- Memory layout configuration
LIFETIME(...) -- Lifetime of dictionary in memory
Storing Dictionaries in Memory {#storing-dictionaries-in-memory}
There are a variety of ways to store dictionaries in memory.
We recommend
flat
,
hashed
and
complex_key_hashed
, which provide optimal processing speed.
Caching is not recommended because of potentially poor performance and difficulties in selecting optimal parameters. Read more in the section
cache
.
There are several ways to improve dictionary performance:
Call the function for working with the dictionary after
GROUP BY
.
Mark attributes to extract as injective. An attribute is called injective if different keys correspond to different attribute values. So when
GROUP BY
uses a function that fetches an attribute value by the key, this function is automatically taken out of
GROUP BY
.
ClickHouse generates an exception for errors with dictionaries. Examples of errors:
The dictionary being accessed could not be loaded.
Error querying a
cached
dictionary.
You can view the list of dictionaries and their statuses in the
system.dictionaries
table.
The configuration looks like this:
xml
<clickhouse>
<dictionary>
...
<layout>
<layout_type>
<!-- layout settings -->
</layout_type>
</layout>
...
</dictionary>
</clickhouse> | {"source_file": "index.md"} | [
-0.005412044934928417,
-0.0001373391569359228,
-0.10606800019741058,
-0.02587452530860901,
-0.06767042726278305,
-0.04960706830024719,
0.05306056886911392,
-0.056977782398462296,
-0.03796433284878731,
0.0302643571048975,
0.0896766185760498,
-0.016563013195991516,
0.09803151339292526,
-0.04... |
52f4fe89-47f3-47df-a370-40ad54e00ce3 | Corresponding
DDL-query
:
sql
CREATE DICTIONARY (...)
...
LAYOUT(LAYOUT_TYPE(param value)) -- layout settings
...
Dictionaries without word
complex-key*
in a layout have a key with
UInt64
type,
complex-key*
dictionaries have a composite key (complex, with arbitrary types).
UInt64
keys in XML dictionaries are defined with
<id>
tag.
Configuration example (column key_column has UInt64 type):
xml
...
<structure>
<id>
<name>key_column</name>
</id>
...
Composite
complex
keys XML dictionaries are defined
<key>
tag.
Configuration example of a composite key (key has one element with
String
type):
xml
...
<structure>
<key>
<attribute>
<name>country_code</name>
<type>String</type>
</attribute>
</key>
...
Ways to Store Dictionaries in Memory {#ways-to-store-dictionaries-in-memory}
Various methods of storing dictionary data in memory are associated with CPU and RAM-usage trade-offs. Decision tree published in
Choosing a Layout
paragraph of dictionary-related
blog post
is a good starting point for deciding which layout to use.
flat
hashed
sparse_hashed
complex_key_hashed
complex_key_sparse_hashed
hashed_array
complex_key_hashed_array
range_hashed
complex_key_range_hashed
cache
complex_key_cache
ssd_cache
complex_key_ssd_cache
direct
complex_key_direct
ip_trie
flat {#flat}
The dictionary is completely stored in memory in the form of flat arrays. How much memory does the dictionary use? The amount is proportional to the size of the largest key (in space used).
The dictionary key has the
UInt64
type and the value is limited to
max_array_size
(by default β 500,000). If a larger key is discovered when creating the dictionary, ClickHouse throws an exception and does not create the dictionary. Dictionary flat arrays initial size is controlled by
initial_array_size
setting (by default β 1024).
All types of sources are supported. When updating, data (from a file or from a table) is read in it entirety.
This method provides the best performance among all available methods of storing the dictionary.
Configuration example:
xml
<layout>
<flat>
<initial_array_size>50000</initial_array_size>
<max_array_size>5000000</max_array_size>
</flat>
</layout>
or
sql
LAYOUT(FLAT(INITIAL_ARRAY_SIZE 50000 MAX_ARRAY_SIZE 5000000))
hashed {#hashed}
The dictionary is completely stored in memory in the form of a hash table. The dictionary can contain any number of elements with any identifiers. In practice, the number of keys can reach tens of millions of items.
The dictionary key has the
UInt64
type.
All types of sources are supported. When updating, data (from a file or from a table) is read in its entirety.
Configuration example:
xml
<layout>
<hashed />
</layout>
or
sql
LAYOUT(HASHED())
Configuration example: | {"source_file": "index.md"} | [
0.04122330993413925,
0.012002531439065933,
-0.1323430836200714,
-0.008467612788081169,
-0.07279901951551437,
-0.07962287962436676,
0.005752094089984894,
0.005594287533313036,
-0.03061530366539955,
-0.008868547156453133,
0.06673260033130646,
-0.00963978748768568,
0.10992669314146042,
-0.076... |
759821cc-2f3f-475a-a399-cfb1b1bd9e00 | Configuration example:
xml
<layout>
<hashed />
</layout>
or
sql
LAYOUT(HASHED())
Configuration example:
``xml
<layout>
<hashed>
<!-- If shards greater then 1 (default is
1`) the dictionary will load
data in parallel, useful if you have huge amount of elements in one
dictionary. -->
10
<!-- Size of the backlog for blocks in parallel queue.
Since the bottleneck in parallel loading is rehash, and so to avoid
stalling because of thread is doing rehash, you need to have some
backlog.
10000 is good balance between memory and speed.
Even for 10e10 elements and can handle all the load without starvation. -->
<shard_load_queue_backlog>10000</shard_load_queue_backlog>
<!-- Maximum load factor of the hash table, with greater values, the memory
is utilized more efficiently (less memory is wasted) but read/performance
may deteriorate.
Valid values: [0.5, 0.99]
Default: 0.5 -->
<max_load_factor>0.5</max_load_factor>
```
or
sql
LAYOUT(HASHED([SHARDS 1] [SHARD_LOAD_QUEUE_BACKLOG 10000] [MAX_LOAD_FACTOR 0.5]))
sparse_hashed {#sparse_hashed}
Similar to
hashed
, but uses less memory in favor more CPU usage.
The dictionary key has the
UInt64
type.
Configuration example:
xml
<layout>
<sparse_hashed>
<!-- <shards>1</shards> -->
<!-- <shard_load_queue_backlog>10000</shard_load_queue_backlog> -->
<!-- <max_load_factor>0.5</max_load_factor> -->
</sparse_hashed>
</layout>
or
sql
LAYOUT(SPARSE_HASHED([SHARDS 1] [SHARD_LOAD_QUEUE_BACKLOG 10000] [MAX_LOAD_FACTOR 0.5]))
It is also possible to use
shards
for this type of dictionary, and again it is more important for
sparse_hashed
then for
hashed
, since
sparse_hashed
is slower.
complex_key_hashed {#complex_key_hashed}
This type of storage is for use with composite
keys
. Similar to
hashed
.
Configuration example:
xml
<layout>
<complex_key_hashed>
<!-- <shards>1</shards> -->
<!-- <shard_load_queue_backlog>10000</shard_load_queue_backlog> -->
<!-- <max_load_factor>0.5</max_load_factor> -->
</complex_key_hashed>
</layout>
or
sql
LAYOUT(COMPLEX_KEY_HASHED([SHARDS 1] [SHARD_LOAD_QUEUE_BACKLOG 10000] [MAX_LOAD_FACTOR 0.5]))
complex_key_sparse_hashed {#complex_key_sparse_hashed}
This type of storage is for use with composite
keys
. Similar to
sparse_hashed
.
Configuration example:
xml
<layout>
<complex_key_sparse_hashed>
<!-- <shards>1</shards> -->
<!-- <shard_load_queue_backlog>10000</shard_load_queue_backlog> -->
<!-- <max_load_factor>0.5</max_load_factor> -->
</complex_key_sparse_hashed>
</layout>
or
sql
LAYOUT(COMPLEX_KEY_SPARSE_HASHED([SHARDS 1] [SHARD_LOAD_QUEUE_BACKLOG 10000] [MAX_LOAD_FACTOR 0.5]))
hashed_array {#hashed_array} | {"source_file": "index.md"} | [
0.023916326463222504,
-0.00717865489423275,
-0.07089827954769135,
-0.0017090080073103309,
-0.08678660541772842,
-0.08969133347272873,
-0.04100592061877251,
-0.017724312841892242,
-0.006017068866640329,
0.004245813004672527,
0.018931306898593903,
0.07898776978254318,
0.05873897299170494,
-0... |
81a1c21f-8960-4f3f-a71b-90c071f37136 | or
sql
LAYOUT(COMPLEX_KEY_SPARSE_HASHED([SHARDS 1] [SHARD_LOAD_QUEUE_BACKLOG 10000] [MAX_LOAD_FACTOR 0.5]))
hashed_array {#hashed_array}
The dictionary is completely stored in memory. Each attribute is stored in an array. The key attribute is stored in the form of a hashed table where value is an index in the attributes array. The dictionary can contain any number of elements with any identifiers. In practice, the number of keys can reach tens of millions of items.
The dictionary key has the
UInt64
type.
All types of sources are supported. When updating, data (from a file or from a table) is read in its entirety.
Configuration example:
xml
<layout>
<hashed_array>
</hashed_array>
</layout>
or
sql
LAYOUT(HASHED_ARRAY([SHARDS 1]))
complex_key_hashed_array {#complex_key_hashed_array}
This type of storage is for use with composite
keys
. Similar to
hashed_array
.
Configuration example:
xml
<layout>
<complex_key_hashed_array />
</layout>
or
sql
LAYOUT(COMPLEX_KEY_HASHED_ARRAY([SHARDS 1]))
range_hashed {#range_hashed}
The dictionary is stored in memory in the form of a hash table with an ordered array of ranges and their corresponding values.
The dictionary key has the
UInt64
type.
This storage method works the same way as hashed and allows using date/time (arbitrary numeric type) ranges in addition to the key.
Example: The table contains discounts for each advertiser in the format:
text
ββadvertiser_idββ¬βdiscount_start_dateββ¬βdiscount_end_dateββ¬βamountββ
β 123 β 2015-01-16 β 2015-01-31 β 0.25 β
β 123 β 2015-01-01 β 2015-01-15 β 0.15 β
β 456 β 2015-01-01 β 2015-01-15 β 0.05 β
βββββββββββββββββ΄ββββββββββββββββββββββ΄ββββββββββββββββββββ΄βββββββββ
To use a sample for date ranges, define the
range_min
and
range_max
elements in the
structure
. These elements must contain elements
name
and
type
(if
type
is not specified, the default type will be used - Date).
type
can be any numeric type (Date / DateTime / UInt64 / Int32 / others).
:::note
Values of
range_min
and
range_max
should fit in
Int64
type.
:::
Example:
xml
<layout>
<range_hashed>
<!-- Strategy for overlapping ranges (min/max). Default: min (return a matching range with the min(range_min -> range_max) value) -->
<range_lookup_strategy>min</range_lookup_strategy>
</range_hashed>
</layout>
<structure>
<id>
<name>advertiser_id</name>
</id>
<range_min>
<name>discount_start_date</name>
<type>Date</type>
</range_min>
<range_max>
<name>discount_end_date</name>
<type>Date</type>
</range_max>
...
or | {"source_file": "index.md"} | [
0.03156168758869171,
0.019099125638604164,
-0.13622352480888367,
-0.0011836346238851547,
-0.04192589223384857,
-0.09455612301826477,
-0.010631267912685871,
-0.019601283594965935,
0.03734074532985687,
0.031108753755688667,
0.04488806799054146,
0.1353950798511505,
0.09749333560466766,
-0.100... |
23b7edf1-8d07-4ed0-8bbb-7f454c9dd482 | or
sql
CREATE DICTIONARY discounts_dict (
advertiser_id UInt64,
discount_start_date Date,
discount_end_date Date,
amount Float64
)
PRIMARY KEY id
SOURCE(CLICKHOUSE(TABLE 'discounts'))
LIFETIME(MIN 1 MAX 1000)
LAYOUT(RANGE_HASHED(range_lookup_strategy 'max'))
RANGE(MIN discount_start_date MAX discount_end_date)
To work with these dictionaries, you need to pass an additional argument to the
dictGet
function, for which a range is selected:
sql
dictGet('dict_name', 'attr_name', id, date)
Query example:
sql
SELECT dictGet('discounts_dict', 'amount', 1, '2022-10-20'::Date);
This function returns the value for the specified
id
s and the date range that includes the passed date.
Details of the algorithm:
If the
id
is not found or a range is not found for the
id
, it returns the default value of the attribute's type.
If there are overlapping ranges and
range_lookup_strategy=min
, it returns a matching range with minimal
range_min
, if several ranges found, it returns a range with minimal
range_max
, if again several ranges found (several ranges had the same
range_min
and
range_max
it returns a random range of them.
If there are overlapping ranges and
range_lookup_strategy=max
, it returns a matching range with maximal
range_min
, if several ranges found, it returns a range with maximal
range_max
, if again several ranges found (several ranges had the same
range_min
and
range_max
it returns a random range of them.
If the
range_max
is
NULL
, the range is open.
NULL
is treated as maximal possible value. For the
range_min
1970-01-01
or
0
(-MAX_INT) can be used as the open value.
Configuration example:
```xml
...
<layout>
<range_hashed />
</layout>
<structure>
<id>
<name>Abcdef</name>
</id>
<range_min>
<name>StartTimeStamp</name>
<type>UInt64</type>
</range_min>
<range_max>
<name>EndTimeStamp</name>
<type>UInt64</type>
</range_max>
<attribute>
<name>XXXType</name>
<type>String</type>
<null_value />
</attribute>
</structure>
</dictionary>
```
or
sql
CREATE DICTIONARY somedict(
Abcdef UInt64,
StartTimeStamp UInt64,
EndTimeStamp UInt64,
XXXType String DEFAULT ''
)
PRIMARY KEY Abcdef
RANGE(MIN StartTimeStamp MAX EndTimeStamp)
Configuration example with overlapping ranges and open ranges:
```sql
CREATE TABLE discounts
(
advertiser_id UInt64,
discount_start_date Date,
discount_end_date Nullable(Date),
amount Float64
)
ENGINE = Memory; | {"source_file": "index.md"} | [
-0.06939832121133804,
0.06772131472826004,
-0.07160618156194687,
0.004356703720986843,
-0.06566064059734344,
0.00022442788758780807,
0.021351400762796402,
0.03515661507844925,
-0.020824575796723366,
-0.0034042007755488157,
0.04949897527694702,
-0.015723345801234245,
0.04576614499092102,
-0... |
04eac73b-f42a-4c04-a2d1-3f8b55dfbafa | ```sql
CREATE TABLE discounts
(
advertiser_id UInt64,
discount_start_date Date,
discount_end_date Nullable(Date),
amount Float64
)
ENGINE = Memory;
INSERT INTO discounts VALUES (1, '2015-01-01', Null, 0.1);
INSERT INTO discounts VALUES (1, '2015-01-15', Null, 0.2);
INSERT INTO discounts VALUES (2, '2015-01-01', '2015-01-15', 0.3);
INSERT INTO discounts VALUES (2, '2015-01-04', '2015-01-10', 0.4);
INSERT INTO discounts VALUES (3, '1970-01-01', '2015-01-15', 0.5);
INSERT INTO discounts VALUES (3, '1970-01-01', '2015-01-10', 0.6);
SELECT * FROM discounts ORDER BY advertiser_id, discount_start_date;
ββadvertiser_idββ¬βdiscount_start_dateββ¬βdiscount_end_dateββ¬βamountββ
β 1 β 2015-01-01 β α΄Ία΅α΄Έα΄Έ β 0.1 β
β 1 β 2015-01-15 β α΄Ία΅α΄Έα΄Έ β 0.2 β
β 2 β 2015-01-01 β 2015-01-15 β 0.3 β
β 2 β 2015-01-04 β 2015-01-10 β 0.4 β
β 3 β 1970-01-01 β 2015-01-15 β 0.5 β
β 3 β 1970-01-01 β 2015-01-10 β 0.6 β
βββββββββββββββββ΄ββββββββββββββββββββββ΄ββββββββββββββββββββ΄βββββββββ
-- RANGE_LOOKUP_STRATEGY 'max'
CREATE DICTIONARY discounts_dict
(
advertiser_id UInt64,
discount_start_date Date,
discount_end_date Nullable(Date),
amount Float64
)
PRIMARY KEY advertiser_id
SOURCE(CLICKHOUSE(TABLE discounts))
LIFETIME(MIN 600 MAX 900)
LAYOUT(RANGE_HASHED(RANGE_LOOKUP_STRATEGY 'max'))
RANGE(MIN discount_start_date MAX discount_end_date);
select dictGet('discounts_dict', 'amount', 1, toDate('2015-01-14')) res;
ββresββ
β 0.1 β -- the only one range is matching: 2015-01-01 - Null
βββββββ
select dictGet('discounts_dict', 'amount', 1, toDate('2015-01-16')) res;
ββresββ
β 0.2 β -- two ranges are matching, range_min 2015-01-15 (0.2) is bigger than 2015-01-01 (0.1)
βββββββ
select dictGet('discounts_dict', 'amount', 2, toDate('2015-01-06')) res;
ββresββ
β 0.4 β -- two ranges are matching, range_min 2015-01-04 (0.4) is bigger than 2015-01-01 (0.3)
βββββββ
select dictGet('discounts_dict', 'amount', 3, toDate('2015-01-01')) res;
ββresββ
β 0.5 β -- two ranges are matching, range_min are equal, 2015-01-15 (0.5) is bigger than 2015-01-10 (0.6)
βββββββ
DROP DICTIONARY discounts_dict;
-- RANGE_LOOKUP_STRATEGY 'min'
CREATE DICTIONARY discounts_dict
(
advertiser_id UInt64,
discount_start_date Date,
discount_end_date Nullable(Date),
amount Float64
)
PRIMARY KEY advertiser_id
SOURCE(CLICKHOUSE(TABLE discounts))
LIFETIME(MIN 600 MAX 900)
LAYOUT(RANGE_HASHED(RANGE_LOOKUP_STRATEGY 'min'))
RANGE(MIN discount_start_date MAX discount_end_date);
select dictGet('discounts_dict', 'amount', 1, toDate('2015-01-14')) res;
ββresββ
β 0.1 β -- the only one range is matching: 2015-01-01 - Null
βββββββ | {"source_file": "index.md"} | [
-0.01906849443912506,
0.025167765095829964,
0.010849381797015667,
0.029316283762454987,
-0.034383080899715424,
0.024115756154060364,
0.019399238750338554,
0.0033583950717002153,
0.004155536647886038,
0.02955496497452259,
0.14570720493793488,
-0.05552535876631737,
0.03070242330431938,
-0.04... |
59657fbf-7594-4184-80f3-a6cc2b54e0ec | select dictGet('discounts_dict', 'amount', 1, toDate('2015-01-14')) res;
ββresββ
β 0.1 β -- the only one range is matching: 2015-01-01 - Null
βββββββ
select dictGet('discounts_dict', 'amount', 1, toDate('2015-01-16')) res;
ββresββ
β 0.1 β -- two ranges are matching, range_min 2015-01-01 (0.1) is less than 2015-01-15 (0.2)
βββββββ
select dictGet('discounts_dict', 'amount', 2, toDate('2015-01-06')) res;
ββresββ
β 0.3 β -- two ranges are matching, range_min 2015-01-01 (0.3) is less than 2015-01-04 (0.4)
βββββββ
select dictGet('discounts_dict', 'amount', 3, toDate('2015-01-01')) res;
ββresββ
β 0.6 β -- two ranges are matching, range_min are equal, 2015-01-10 (0.6) is less than 2015-01-15 (0.5)
βββββββ
```
complex_key_range_hashed {#complex_key_range_hashed}
The dictionary is stored in memory in the form of a hash table with an ordered array of ranges and their corresponding values (see
range_hashed
). This type of storage is for use with composite
keys
.
Configuration example:
sql
CREATE DICTIONARY range_dictionary
(
CountryID UInt64,
CountryKey String,
StartDate Date,
EndDate Date,
Tax Float64 DEFAULT 0.2
)
PRIMARY KEY CountryID, CountryKey
SOURCE(CLICKHOUSE(TABLE 'date_table'))
LIFETIME(MIN 1 MAX 1000)
LAYOUT(COMPLEX_KEY_RANGE_HASHED())
RANGE(MIN StartDate MAX EndDate);
cache {#cache}
The dictionary is stored in a cache that has a fixed number of cells. These cells contain frequently used elements.
The dictionary key has the
UInt64
type.
When searching for a dictionary, the cache is searched first. For each block of data, all keys that are not found in the cache or are outdated are requested from the source using
SELECT attrs... FROM db.table WHERE id IN (k1, k2, ...)
. The received data is then written to the cache.
If keys are not found in dictionary, then update cache task is created and added into update queue. Update queue properties can be controlled with settings
max_update_queue_size
,
update_queue_push_timeout_milliseconds
,
query_wait_timeout_milliseconds
,
max_threads_for_updates
.
For cache dictionaries, the expiration
lifetime
of data in the cache can be set. If more time than
lifetime
has passed since loading the data in a cell, the cell's value is not used and key becomes expired. The key is re-requested the next time it needs to be used. This behaviour can be configured with setting
allow_read_expired_keys
.
This is the least effective of all the ways to store dictionaries. The speed of the cache depends strongly on correct settings and the usage scenario. A cache type dictionary performs well only when the hit rates are high enough (recommended 99% and higher). You can view the average hit rate in the
system.dictionaries
table. | {"source_file": "index.md"} | [
-0.030067194253206253,
0.09094681590795517,
0.07028286904096603,
-0.012379692867398262,
-0.02698657661676407,
0.0020486973226070404,
-0.010286049917340279,
0.006625431589782238,
0.025209689512848854,
0.028782008215785027,
0.049149129539728165,
-0.12963367998600006,
0.02568153105676174,
-0.... |
79c67f37-348a-4ab0-8b43-e6f22f8ba6d0 | If setting
allow_read_expired_keys
is set to 1, by default 0. Then dictionary can support asynchronous updates. If a client requests keys and all of them are in cache, but some of them are expired, then dictionary will return expired keys for a client and request them asynchronously from the source.
To improve cache performance, use a subquery with
LIMIT
, and call the function with the dictionary externally.
All types of sources are supported.
Example of settings:
xml
<layout>
<cache>
<!-- The size of the cache, in number of cells. Rounded up to a power of two. -->
<size_in_cells>1000000000</size_in_cells>
<!-- Allows to read expired keys. -->
<allow_read_expired_keys>0</allow_read_expired_keys>
<!-- Max size of update queue. -->
<max_update_queue_size>100000</max_update_queue_size>
<!-- Max timeout in milliseconds for push update task into queue. -->
<update_queue_push_timeout_milliseconds>10</update_queue_push_timeout_milliseconds>
<!-- Max wait timeout in milliseconds for update task to complete. -->
<query_wait_timeout_milliseconds>60000</query_wait_timeout_milliseconds>
<!-- Max threads for cache dictionary update. -->
<max_threads_for_updates>4</max_threads_for_updates>
</cache>
</layout>
or
sql
LAYOUT(CACHE(SIZE_IN_CELLS 1000000000))
Set a large enough cache size. You need to experiment to select the number of cells:
Set some value.
Run queries until the cache is completely full.
Assess memory consumption using the
system.dictionaries
table.
Increase or decrease the number of cells until the required memory consumption is reached.
:::note
Do not use ClickHouse as a source, because it is slow to process queries with random reads.
:::
complex_key_cache {#complex_key_cache}
This type of storage is for use with composite
keys
. Similar to
cache
.
ssd_cache {#ssd_cache}
Similar to
cache
, but stores data on SSD and index in RAM. All cache dictionary settings related to update queue can also be applied to SSD cache dictionaries.
The dictionary key has the
UInt64
type.
xml
<layout>
<ssd_cache>
<!-- Size of elementary read block in bytes. Recommended to be equal to SSD's page size. -->
<block_size>4096</block_size>
<!-- Max cache file size in bytes. -->
<file_size>16777216</file_size>
<!-- Size of RAM buffer in bytes for reading elements from SSD. -->
<read_buffer_size>131072</read_buffer_size>
<!-- Size of RAM buffer in bytes for aggregating elements before flushing to SSD. -->
<write_buffer_size>1048576</write_buffer_size>
<!-- Path where cache file will be stored. -->
<path>/var/lib/clickhouse/user_files/test_dict</path>
</ssd_cache>
</layout>
or
sql
LAYOUT(SSD_CACHE(BLOCK_SIZE 4096 FILE_SIZE 16777216 READ_BUFFER_SIZE 1048576
PATH '/var/lib/clickhouse/user_files/test_dict')) | {"source_file": "index.md"} | [
-0.04422958940267563,
0.02015259489417076,
-0.14345845580101013,
0.01731235347688198,
-0.1073991060256958,
-0.10151591151952744,
-0.016492020338773727,
-0.04087035730481148,
0.03332999348640442,
0.038023024797439575,
0.07847750186920166,
0.08281262964010239,
0.05277207866311073,
-0.1223413... |
a94b1e5a-26b0-4e74-8983-c1584ea08bba | or
sql
LAYOUT(SSD_CACHE(BLOCK_SIZE 4096 FILE_SIZE 16777216 READ_BUFFER_SIZE 1048576
PATH '/var/lib/clickhouse/user_files/test_dict'))
complex_key_ssd_cache {#complex_key_ssd_cache}
This type of storage is for use with composite
keys
. Similar to
ssd_cache
.
direct {#direct}
The dictionary is not stored in memory and directly goes to the source during the processing of a request.
The dictionary key has the
UInt64
type.
All types of
sources
, except local files, are supported.
Configuration example:
xml
<layout>
<direct />
</layout>
or
sql
LAYOUT(DIRECT())
complex_key_direct {#complex_key_direct}
This type of storage is for use with composite
keys
. Similar to
direct
.
ip_trie {#ip_trie}
This dictionary is designed for IP address lookups by network prefix. It stores IP ranges in CIDR notation and allows fast determination of which prefix (e.g. subnet or ASN range) a given IP falls into, making it ideal for IP-based searches like geolocation or network classification.
Example
Suppose we have a table in ClickHouse that contains our IP prefixes and mappings:
sql
CREATE TABLE my_ip_addresses (
prefix String,
asn UInt32,
cca2 String
)
ENGINE = MergeTree
PRIMARY KEY prefix;
sql
INSERT INTO my_ip_addresses VALUES
('202.79.32.0/20', 17501, 'NP'),
('2620:0:870::/48', 3856, 'US'),
('2a02:6b8:1::/48', 13238, 'RU'),
('2001:db8::/32', 65536, 'ZZ')
;
Let's define an
ip_trie
dictionary for this table. The
ip_trie
layout requires a composite key:
xml
<structure>
<key>
<attribute>
<name>prefix</name>
<type>String</type>
</attribute>
</key>
<attribute>
<name>asn</name>
<type>UInt32</type>
<null_value />
</attribute>
<attribute>
<name>cca2</name>
<type>String</type>
<null_value>??</null_value>
</attribute>
...
</structure>
<layout>
<ip_trie>
<!-- Key attribute `prefix` can be retrieved via dictGetString. -->
<!-- This option increases memory usage. -->
<access_to_key_from_attributes>true</access_to_key_from_attributes>
</ip_trie>
</layout>
or
sql
CREATE DICTIONARY my_ip_trie_dictionary (
prefix String,
asn UInt32,
cca2 String DEFAULT '??'
)
PRIMARY KEY prefix
SOURCE(CLICKHOUSE(TABLE 'my_ip_addresses'))
LAYOUT(IP_TRIE)
LIFETIME(3600);
The key must have only one
String
type attribute that contains an allowed IP prefix. Other types are not supported yet.
The syntax is:
sql
dictGetT('dict_name', 'attr_name', ip)
The function takes either
UInt32
for IPv4, or
FixedString(16)
for IPv6. For example:
```sql
SELECT dictGet('my_ip_trie_dictionary', 'cca2', toIPv4('202.79.32.10')) AS result;
ββresultββ
β NP β
ββββββββββ
SELECT dictGet('my_ip_trie_dictionary', 'asn', IPv6StringToNum('2001:db8::1')) AS result;
ββresultββ
β 65536 β
ββββββββββ | {"source_file": "index.md"} | [
-0.038946621119976044,
-0.0009172364370897412,
-0.12137093394994736,
-0.023419752717018127,
-0.03589196503162384,
-0.07412049174308777,
0.005785264074802399,
-0.000511123042088002,
0.003851634915918112,
-0.01460959855467081,
0.06394926458597183,
0.1408034861087799,
0.0508243665099144,
-0.0... |
6fc4a47c-c4d6-4007-bb61-b6cb2c8412ad | ββresultββ
β NP β
ββββββββββ
SELECT dictGet('my_ip_trie_dictionary', 'asn', IPv6StringToNum('2001:db8::1')) AS result;
ββresultββ
β 65536 β
ββββββββββ
SELECT dictGet('my_ip_trie_dictionary', ('asn', 'cca2'), IPv6StringToNum('2001:db8::1')) AS result;
ββresultββββββββ
β (65536,'ZZ') β
ββββββββββββββββ
```
Other types are not supported yet. The function returns the attribute for the prefix that corresponds to this IP address. If there are overlapping prefixes, the most specific one is returned.
Data must completely fit into RAM.
Refreshing dictionary data using LIFETIME {#refreshing-dictionary-data-using-lifetime}
ClickHouse periodically updates dictionaries based on the
LIFETIME
tag (defined in seconds).
LIFETIME
is the update interval for fully downloaded dictionaries and the invalidation interval for cached dictionaries.
During updates, the old version of a dictionary can still be queried. Dictionary updates (other than when loading the dictionary for first use) do not block queries. If an error occurs during an update, the error is written to the server log and queries can continue using the old version of the dictionary. If a dictionary update is successful, the old version of the dictionary is replaced atomically.
Example of settings:
xml
<dictionary>
...
<lifetime>300</lifetime>
...
</dictionary>
or
sql
CREATE DICTIONARY (...)
...
LIFETIME(300)
...
Setting
<lifetime>0</lifetime>
(
LIFETIME(0)
) prevents dictionaries from updating.
You can set a time interval for updates, and ClickHouse will choose a uniformly random time within this range. This is necessary in order to distribute the load on the dictionary source when updating on a large number of servers.
Example of settings:
xml
<dictionary>
...
<lifetime>
<min>300</min>
<max>360</max>
</lifetime>
...
</dictionary>
or
sql
LIFETIME(MIN 300 MAX 360)
If
<min>0</min>
and
<max>0</max>
, ClickHouse does not reload the dictionary by timeout.
In this case, ClickHouse can reload the dictionary earlier if the dictionary configuration file was changed or the
SYSTEM RELOAD DICTIONARY
command was executed.
When updating the dictionaries, the ClickHouse server applies different logic depending on the type of
source
:
For a text file, it checks the time of modification. If the time differs from the previously recorded time, the dictionary is updated.
Dictionaries from other sources are updated every time by default.
For other sources (ODBC, PostgreSQL, ClickHouse, etc), you can set up a query that will update the dictionaries only if they really changed, rather than each time. To do this, follow these steps:
The dictionary table must have a field that always changes when the source data is updated. | {"source_file": "index.md"} | [
-0.07576807588338852,
-0.038195837289094925,
-0.035753604024648666,
0.0026592242065817118,
-0.014467147178947926,
-0.10251973569393158,
0.0020900091622024775,
-0.09657368063926697,
0.012286249548196793,
-0.014271644875407219,
0.0775287076830864,
0.06293175369501114,
-0.01802884228527546,
-... |
ad99df71-0f4f-4bba-957d-081bfbdb5b9f | The dictionary table must have a field that always changes when the source data is updated.
The settings of the source must specify a query that retrieves the changing field. The ClickHouse server interprets the query result as a row, and if this row has changed relative to its previous state, the dictionary is updated. Specify the query in the
<invalidate_query>
field in the settings for the
source
.
Example of settings:
xml
<dictionary>
...
<odbc>
...
<invalidate_query>SELECT update_time FROM dictionary_source where id = 1</invalidate_query>
</odbc>
...
</dictionary>
or
sql
...
SOURCE(ODBC(... invalidate_query 'SELECT update_time FROM dictionary_source where id = 1'))
...
For
Cache
,
ComplexKeyCache
,
SSDCache
, and
SSDComplexKeyCache
dictionaries both synchronous and asynchronous updates are supported.
It is also possible for
Flat
,
Hashed
,
HashedArray
,
ComplexKeyHashed
dictionaries to only request data that was changed after the previous update. If
update_field
is specified as part of the dictionary source configuration, value of the previous update time in seconds will be added to the data request. Depends on source type (Executable, HTTP, MySQL, PostgreSQL, ClickHouse, or ODBC) different logic will be applied to
update_field
before request data from an external source.
If the source is HTTP then
update_field
will be added as a query parameter with the last update time as the parameter value.
If the source is Executable then
update_field
will be added as an executable script argument with the last update time as the argument value.
If the source is ClickHouse, MySQL, PostgreSQL, ODBC there will be an additional part of
WHERE
, where
update_field
is compared as greater or equal with the last update time.
Per default, this
WHERE
-condition is checked at the highest level of the SQL-Query. Alternatively, the condition can be checked in any other
WHERE
-clause within the query using the
{condition}
-keyword. Example:
sql
...
SOURCE(CLICKHOUSE(...
update_field 'added_time'
QUERY '
SELECT my_arr.1 AS x, my_arr.2 AS y, creation_time
FROM (
SELECT arrayZip(x_arr, y_arr) AS my_arr, creation_time
FROM dictionary_source
WHERE {condition}
)'
))
...
If
update_field
option is set, additional option
update_lag
can be set. Value of
update_lag
option is subtracted from previous update time before request updated data.
Example of settings:
xml
<dictionary>
...
<clickhouse>
...
<update_field>added_time</update_field>
<update_lag>15</update_lag>
</clickhouse>
...
</dictionary>
or
sql
...
SOURCE(CLICKHOUSE(... update_field 'added_time' update_lag 15))
...
Dictionary Sources {#dictionary-sources}
A dictionary can be connected to ClickHouse from many different sources. | {"source_file": "index.md"} | [
-0.04280061647295952,
-0.017680490389466286,
-0.08592287451028824,
0.03670554608106613,
-0.04086592420935631,
-0.11783924698829651,
0.03486933559179306,
-0.07229070365428925,
0.05973084270954132,
0.023709464818239212,
0.03370916098356247,
0.025573454797267914,
0.06649040430784225,
-0.12649... |
579d9827-fda7-4015-b5a4-d80e2c2d420c | sql
...
SOURCE(CLICKHOUSE(... update_field 'added_time' update_lag 15))
...
Dictionary Sources {#dictionary-sources}
A dictionary can be connected to ClickHouse from many different sources.
If the dictionary is configured using an xml-file, the configuration looks like this:
xml
<clickhouse>
<dictionary>
...
<source>
<source_type>
<!-- Source configuration -->
</source_type>
</source>
...
</dictionary>
...
</clickhouse>
In case of
DDL-query
, the configuration described above will look like:
sql
CREATE DICTIONARY dict_name (...)
...
SOURCE(SOURCE_TYPE(param1 val1 ... paramN valN)) -- Source configuration
...
The source is configured in the
source
section.
For source types
Local file
,
Executable file
,
HTTP(s)
,
ClickHouse
optional settings are available:
xml
<source>
<file>
<path>/opt/dictionaries/os.tsv</path>
<format>TabSeparated</format>
</file>
<settings>
<format_csv_allow_single_quotes>0</format_csv_allow_single_quotes>
</settings>
</source>
or
sql
SOURCE(FILE(path './user_files/os.tsv' format 'TabSeparated'))
SETTINGS(format_csv_allow_single_quotes = 0)
Types of sources (
source_type
):
Local file
Executable File
Executable Pool
HTTP(S)
DBMS
ODBC
MySQL
ClickHouse
MongoDB
Redis
Cassandra
PostgreSQL
Local File {#local-file}
Example of settings:
xml
<source>
<file>
<path>/opt/dictionaries/os.tsv</path>
<format>TabSeparated</format>
</file>
</source>
or
sql
SOURCE(FILE(path './user_files/os.tsv' format 'TabSeparated'))
Setting fields:
path
β The absolute path to the file.
format
β The file format. All the formats described in
Formats
are supported.
When a dictionary with source
FILE
is created via DDL command (
CREATE DICTIONARY ...
), the source file needs to be located in the
user_files
directory to prevent DB users from accessing arbitrary files on the ClickHouse node.
See Also
Dictionary function
Executable File {#executable-file}
Working with executable files depends on
how the dictionary is stored in memory
. If the dictionary is stored using
cache
and
complex_key_cache
, ClickHouse requests the necessary keys by sending a request to the executable file's STDIN. Otherwise, ClickHouse starts the executable file and treats its output as dictionary data.
Example of settings:
xml
<source>
<executable>
<command>cat /opt/dictionaries/os.tsv</command>
<format>TabSeparated</format>
<implicit_key>false</implicit_key>
</executable>
</source>
Setting fields:
command
β The absolute path to the executable file, or the file name (if the command's directory is in the
PATH
).
format
β The file format. All the formats described in
Formats
are supported. | {"source_file": "index.md"} | [
-0.049965400248765945,
-0.06517372280359268,
-0.0841400995850563,
0.007003472652286291,
-0.06965802609920502,
-0.09860612452030182,
0.08629375696182251,
-0.023306846618652344,
-0.020886708050966263,
0.004292523954063654,
0.05291800945997238,
-0.03799218311905861,
0.07807440310716629,
-0.13... |
73bb549c-a3ca-497f-b5ca-894d73bc94eb | format
β The file format. All the formats described in
Formats
are supported.
command_termination_timeout
β The executable script should contain a main read-write loop. After the dictionary is destroyed, the pipe is closed, and the executable file will have
command_termination_timeout
seconds to shutdown before ClickHouse will send a SIGTERM signal to the child process.
command_termination_timeout
is specified in seconds. Default value is 10. Optional parameter.
command_read_timeout
- Timeout for reading data from command stdout in milliseconds. Default value 10000. Optional parameter.
command_write_timeout
- Timeout for writing data to command stdin in milliseconds. Default value 10000. Optional parameter.
implicit_key
β The executable source file can return only values, and the correspondence to the requested keys is determined implicitly β by the order of rows in the result. Default value is 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 a whitespace separator. Example:
script_name arg1 arg2
. If
execute_direct
=
0
,
command
is passed as argument for
bin/sh -c
. Default value is
0
. Optional parameter.
send_chunk_header
- controls whether to send row count before sending a chunk of data to process. Optional. Default value is
false
.
That dictionary source can be configured only via XML configuration. Creating dictionaries with executable source via DDL is disabled; otherwise, the DB user would be able to execute arbitrary binaries on the ClickHouse node.
Executable Pool {#executable-pool}
Executable pool allows loading data from pool of processes. This source does not work with dictionary layouts that need to load all data from source. Executable pool works if the dictionary
is stored
using
cache
,
complex_key_cache
,
ssd_cache
,
complex_key_ssd_cache
,
direct
, or
complex_key_direct
layouts.
Executable pool will spawn a pool of processes with the specified command and keep them running until they exit. The program should read data from STDIN while it is available and output the result to STDOUT. It can wait for the next block of data on STDIN. ClickHouse will not close STDIN after processing a block of data, but will pipe another chunk of data when needed. The executable script should be ready for this way of data processing β it should poll STDIN and flush data to STDOUT early.
Example of settings:
xml
<source>
<executable_pool>
<command><command>while read key; do printf "$key\tData for key $key\n"; done</command</command>
<format>TabSeparated</format>
<pool_size>10</pool_size>
<max_command_execution_time>10<max_command_execution_time>
<implicit_key>false</implicit_key>
</executable_pool>
</source>
Setting fields: | {"source_file": "index.md"} | [
0.032278332859277725,
0.03386807069182396,
-0.1235131099820137,
0.018001314252614975,
-0.05426691472530365,
-0.02546129934489727,
-0.027327420189976692,
0.09913813322782516,
-0.03182487562298775,
0.014508342370390892,
0.01825992949306965,
0.013049651868641376,
-0.029524490237236023,
-0.074... |
2d75745f-6039-45fe-b90d-3a14216678d4 | Setting fields:
command
β The absolute path to the executable file, or the file name (if the program directory is written to
PATH
).
format
β The file format. All the formats described in "
Formats
" are supported.
pool_size
β Size of pool. If 0 is specified as
pool_size
then there is no pool size restrictions. Default value is
16
.
command_termination_timeout
β executable script should contain main read-write loop. After dictionary is destroyed, pipe is closed, and executable file will have
command_termination_timeout
seconds to shutdown, before ClickHouse will send SIGTERM signal to child process. Specified in seconds. Default value is 10. Optional parameter.
max_command_execution_time
β Maximum executable script command execution time for processing block of data. Specified in seconds. Default value is 10. Optional parameter.
command_read_timeout
- timeout for reading data from command stdout in milliseconds. Default value 10000. Optional parameter.
command_write_timeout
- timeout for writing data to command stdin in milliseconds. Default value 10000. Optional parameter.
implicit_key
β The executable source file can return only values, and the correspondence to the requested keys is determined implicitly β by the order of rows in the result. Default value is false. Optional parameter.
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
. Default value is
1
. Optional parameter.
send_chunk_header
- controls whether to send row count before sending a chunk of data to process. Optional. Default value is
false
.
That dictionary source can be configured only via XML configuration. Creating dictionaries with executable source via DDL is disabled, otherwise, the DB user would be able to execute arbitrary binary on ClickHouse node.
HTTP(S) {#https}
Working with an HTTP(S) server depends on
how the dictionary is stored in memory
. If the dictionary is stored using
cache
and
complex_key_cache
, ClickHouse requests the necessary keys by sending a request via the
POST
method.
Example of settings:
xml
<source>
<http>
<url>http://[::1]/os.tsv</url>
<format>TabSeparated</format>
<credentials>
<user>user</user>
<password>password</password>
</credentials>
<headers>
<header>
<name>API-KEY</name>
<value>key</value>
</header>
</headers>
</http>
</source>
or
sql
SOURCE(HTTP(
url 'http://[::1]/os.tsv'
format 'TabSeparated'
credentials(user 'user' password 'password')
headers(header(name 'API-KEY' value 'key'))
)) | {"source_file": "index.md"} | [
0.03760147839784622,
-0.006688512396067381,
-0.13161662220954895,
0.016388999298214912,
-0.05878030136227608,
-0.02966129593551159,
-0.02505909651517868,
0.13434869050979614,
-0.040730465203523636,
-0.010120001621544361,
0.01183377020061016,
-0.03369007259607315,
-0.0391337089240551,
-0.05... |
33956762-3b56-49d3-afd8-8659a34cb42c | or
sql
SOURCE(HTTP(
url 'http://[::1]/os.tsv'
format 'TabSeparated'
credentials(user 'user' password 'password')
headers(header(name 'API-KEY' value 'key'))
))
In order for ClickHouse to access an HTTPS resource, you must
configure openSSL
in the server configuration.
Setting fields:
url
β The source URL.
format
β The file format. All the formats described in "
Formats
" are supported.
credentials
β Basic HTTP authentication. Optional parameter.
user
β Username required for the authentication.
password
β Password required for the authentication.
headers
β All custom HTTP headers entries used for the HTTP request. Optional parameter.
header
β Single HTTP header entry.
name
β Identifier name used for the header send on the request.
value
β Value set for a specific identifier name.
When creating a dictionary using the DDL command (
CREATE DICTIONARY ...
) remote hosts for HTTP dictionaries are checked against the contents of
remote_url_allow_hosts
section from config to prevent database users to access arbitrary HTTP server.
DBMS {#dbms}
ODBC {#odbc}
You can use this method to connect any database that has an ODBC driver.
Example of settings:
xml
<source>
<odbc>
<db>DatabaseName</db>
<table>ShemaName.TableName</table>
<connection_string>DSN=some_parameters</connection_string>
<invalidate_query>SQL_QUERY</invalidate_query>
<query>SELECT id, value_1, value_2 FROM ShemaName.TableName</query>
</odbc>
</source>
or
sql
SOURCE(ODBC(
db 'DatabaseName'
table 'SchemaName.TableName'
connection_string 'DSN=some_parameters'
invalidate_query 'SQL_QUERY'
query 'SELECT id, value_1, value_2 FROM db_name.table_name'
))
Setting fields:
db
β Name of the database. Omit it if the database name is set in the
<connection_string>
parameters.
table
β Name of the table and schema if exists.
connection_string
β Connection string.
invalidate_query
β Query for checking the dictionary status. Optional parameter. Read more in the section
Refreshing dictionary data using LIFETIME
.
background_reconnect
β Reconnect to replica in background if connection fails. Optional parameter.
query
β The custom query. Optional parameter.
:::note
The
table
and
query
fields cannot be used together. And either one of the
table
or
query
fields must be declared.
:::
ClickHouse receives quoting symbols from ODBC-driver and quote all settings in queries to driver, so it's necessary to set table name accordingly to table name case in database.
If you have a problems with encodings when using Oracle, see the corresponding
FAQ
item.
Known Vulnerability of the ODBC Dictionary Functionality {#known-vulnerability-of-the-odbc-dictionary-functionality} | {"source_file": "index.md"} | [
-0.023101806640625,
-0.017725756391882896,
-0.1615510880947113,
-0.018047505989670753,
-0.0459180623292923,
-0.07122743874788284,
-0.026152849197387695,
-0.015347521752119064,
-0.01629105769097805,
0.017051229253411293,
-0.022661689668893814,
-0.012826953083276749,
0.060959164053201675,
0.... |
9f6d3eff-1800-4c82-bfea-6f422d5cf46d | Known Vulnerability of the ODBC Dictionary Functionality {#known-vulnerability-of-the-odbc-dictionary-functionality}
:::note
When connecting to the database through the ODBC driver connection parameter
Servername
can be substituted. In this case values of
USERNAME
and
PASSWORD
from
odbc.ini
are sent to the remote server and can be compromised.
:::
Example of insecure use
Let's configure unixODBC for PostgreSQL. Content of
/etc/odbc.ini
:
```text
[gregtest]
Driver = /usr/lib/psqlodbca.so
Servername = localhost
PORT = 5432
DATABASE = test_db
OPTION = 3
USERNAME = test
PASSWORD = test
```
If you then make a query such as
sql
SELECT * FROM odbc('DSN=gregtest;Servername=some-server.com', 'test_db');
ODBC driver will send values of
USERNAME
and
PASSWORD
from
odbc.ini
to
some-server.com
.
Example of Connecting Postgresql {#example-of-connecting-postgresql}
Ubuntu OS.
Installing unixODBC and the ODBC driver for PostgreSQL:
bash
$ sudo apt-get install -y unixodbc odbcinst odbc-postgresql
Configuring
/etc/odbc.ini
(or
~/.odbc.ini
if you signed in under a user that runs ClickHouse):
```text
[DEFAULT]
Driver = myconnection
[myconnection]
Description = PostgreSQL connection to my_db
Driver = PostgreSQL Unicode
Database = my_db
Servername = 127.0.0.1
UserName = username
Password = password
Port = 5432
Protocol = 9.3
ReadOnly = No
RowVersioning = No
ShowSystemTables = No
ConnSettings =
```
The dictionary configuration in ClickHouse:
xml
<clickhouse>
<dictionary>
<name>table_name</name>
<source>
<odbc>
<!-- You can specify the following parameters in connection_string: -->
<!-- DSN=myconnection;UID=username;PWD=password;HOST=127.0.0.1;PORT=5432;DATABASE=my_db -->
<connection_string>DSN=myconnection</connection_string>
<table>postgresql_table</table>
</odbc>
</source>
<lifetime>
<min>300</min>
<max>360</max>
</lifetime>
<layout>
<hashed/>
</layout>
<structure>
<id>
<name>id</name>
</id>
<attribute>
<name>some_column</name>
<type>UInt64</type>
<null_value>0</null_value>
</attribute>
</structure>
</dictionary>
</clickhouse>
or
sql
CREATE DICTIONARY table_name (
id UInt64,
some_column UInt64 DEFAULT 0
)
PRIMARY KEY id
SOURCE(ODBC(connection_string 'DSN=myconnection' table 'postgresql_table'))
LAYOUT(HASHED())
LIFETIME(MIN 300 MAX 360)
You may need to edit
odbc.ini
to specify the full path to the library with the driver
DRIVER=/usr/local/lib/psqlodbcw.so
.
Example of Connecting MS SQL Server {#example-of-connecting-ms-sql-server}
Ubuntu OS. | {"source_file": "index.md"} | [
-0.029909584671258926,
-0.025368137285113335,
-0.1989040970802307,
0.05526422709226608,
-0.1215960830450058,
-0.052578698843717575,
0.060887474566698074,
0.04638080671429634,
-0.006891857832670212,
-0.0470576286315918,
-0.04863622412085533,
0.0404762402176857,
0.04067471995949745,
-0.07526... |
b20588b0-fafa-40fd-8036-b40d3fc6383f | Example of Connecting MS SQL Server {#example-of-connecting-ms-sql-server}
Ubuntu OS.
Installing the ODBC driver for connecting to MS SQL:
bash
$ sudo apt-get install tdsodbc freetds-bin sqsh
Configuring the driver:
```bash
$ cat /etc/freetds/freetds.conf
...
[MSSQL]
host = 192.168.56.101
port = 1433
tds version = 7.0
client charset = UTF-8
# test TDS connection
$ sqsh -S MSSQL -D database -U user -P password
$ cat /etc/odbcinst.ini
[FreeTDS]
Description = FreeTDS
Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
Setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so
FileUsage = 1
UsageCount = 5
$ cat /etc/odbc.ini
# $ cat ~/.odbc.ini # if you signed in under a user that runs ClickHouse
[MSSQL]
Description = FreeTDS
Driver = FreeTDS
Servername = MSSQL
Database = test
UID = test
PWD = test
Port = 1433
# (optional) test ODBC connection (to use isql-tool install the [unixodbc](https://packages.debian.org/sid/unixodbc)-package)
$ isql -v MSSQL "user" "password"
```
Remarks:
- to determine the earliest TDS version that is supported by a particular SQL Server version, refer to the product documentation or look at
MS-TDS Product Behavior
Configuring the dictionary in ClickHouse:
```xml
test
dict
DSN=MSSQL;UID=test;PWD=test
<lifetime>
<min>300</min>
<max>360</max>
</lifetime>
<layout>
<flat />
</layout>
<structure>
<id>
<name>k</name>
</id>
<attribute>
<name>s</name>
<type>String</type>
<null_value></null_value>
</attribute>
</structure>
</dictionary>
```
or
sql
CREATE DICTIONARY test (
k UInt64,
s String DEFAULT ''
)
PRIMARY KEY k
SOURCE(ODBC(table 'dict' connection_string 'DSN=MSSQL;UID=test;PWD=test'))
LAYOUT(FLAT())
LIFETIME(MIN 300 MAX 360)
Mysql {#mysql}
Example of settings:
xml
<source>
<mysql>
<port>3306</port>
<user>clickhouse</user>
<password>qwerty</password>
<replica>
<host>example01-1</host>
<priority>1</priority>
</replica>
<replica>
<host>example01-2</host>
<priority>1</priority>
</replica>
<db>db_name</db>
<table>table_name</table>
<where>id=10</where>
<invalidate_query>SQL_QUERY</invalidate_query>
<fail_on_connection_loss>true</fail_on_connection_loss>
<query>SELECT id, value_1, value_2 FROM db_name.table_name</query>
</mysql>
</source>
or
sql
SOURCE(MYSQL(
port 3306
user 'clickhouse'
password 'qwerty'
replica(host 'example01-1' priority 1)
replica(host 'example01-2' priority 1)
db 'db_name'
table 'table_name'
where 'id=10'
invalidate_query 'SQL_QUERY'
fail_on_connection_loss 'true'
query 'SELECT id, value_1, value_2 FROM db_name.table_name'
))
Setting fields: | {"source_file": "index.md"} | [
-0.027198318392038345,
-0.09541037678718567,
-0.07857351750135422,
0.01493033766746521,
-0.0016580134397372603,
-0.04611361026763916,
0.05184221640229225,
0.07532963901758194,
0.046428415924310684,
0.06975236535072327,
0.0008874718332663178,
0.033737439662218094,
0.02636948600411415,
-0.01... |
41f56679-3204-4412-a085-149bbcc7f6a4 | Setting fields:
port
β The port on the MySQL server. You can specify it for all replicas, or for each one individually (inside
<replica>
).
user
β Name of the MySQL user. You can specify it for all replicas, or for each one individually (inside
<replica>
).
password
β Password of the MySQL user. You can specify it for all replicas, or for each one individually (inside
<replica>
).
replica
β Section of replica configurations. There can be multiple sections.
- `replica/host` β The MySQL host.
- `replica/priority` β The replica priority. When attempting to connect, ClickHouse traverses the replicas in order of priority. The lower the number, the higher the priority.
db
β Name of the database.
table
β Name of the table.
where
β The selection criteria. The syntax for conditions is the same as for
WHERE
clause in MySQL, for example,
id > 10 AND id < 20
. Optional parameter.
invalidate_query
β Query for checking the dictionary status. Optional parameter. Read more in the section
Refreshing dictionary data using LIFETIME
.
fail_on_connection_loss
β The configuration parameter that controls behavior of the server on connection loss. If
true
, an exception is thrown immediately if the connection between client and server was lost. If
false
, the ClickHouse server retries to execute the query three times before throwing an exception. Note that retrying leads to increased response times. Default value:
false
.
query
β The custom query. Optional parameter.
:::note
The
table
or
where
fields cannot be used together with the
query
field. And either one of the
table
or
query
fields must be declared.
:::
:::note
There is no explicit parameter
secure
. When establishing an SSL-connection security is mandatory.
:::
MySQL can be connected to on a local host via sockets. To do this, set
host
and
socket
.
Example of settings:
xml
<source>
<mysql>
<host>localhost</host>
<socket>/path/to/socket/file.sock</socket>
<user>clickhouse</user>
<password>qwerty</password>
<db>db_name</db>
<table>table_name</table>
<where>id=10</where>
<invalidate_query>SQL_QUERY</invalidate_query>
<fail_on_connection_loss>true</fail_on_connection_loss>
<query>SELECT id, value_1, value_2 FROM db_name.table_name</query>
</mysql>
</source>
or
sql
SOURCE(MYSQL(
host 'localhost'
socket '/path/to/socket/file.sock'
user 'clickhouse'
password 'qwerty'
db 'db_name'
table 'table_name'
where 'id=10'
invalidate_query 'SQL_QUERY'
fail_on_connection_loss 'true'
query 'SELECT id, value_1, value_2 FROM db_name.table_name'
))
ClickHouse {#clickhouse}
Example of settings: | {"source_file": "index.md"} | [
0.0118901077657938,
-0.05463385954499245,
-0.07245843857526779,
-0.013195252045989037,
-0.08715797960758209,
-0.06961021572351456,
-0.005168613512068987,
-0.0027995400596410036,
-0.02789589948952198,
0.047616615891456604,
-0.023158662021160126,
-0.0008945990703068674,
0.1693652719259262,
0... |
21332986-e50c-4566-ac52-d24680e16235 | ClickHouse {#clickhouse}
Example of settings:
xml
<source>
<clickhouse>
<host>example01-01-1</host>
<port>9000</port>
<user>default</user>
<password></password>
<db>default</db>
<table>ids</table>
<where>id=10</where>
<secure>1</secure>
<query>SELECT id, value_1, value_2 FROM default.ids</query>
</clickhouse>
</source>
or
sql
SOURCE(CLICKHOUSE(
host 'example01-01-1'
port 9000
user 'default'
password ''
db 'default'
table 'ids'
where 'id=10'
secure 1
query 'SELECT id, value_1, value_2 FROM default.ids'
));
Setting fields:
host
β The ClickHouse host. If it is a local host, the query is processed without any network activity. To improve fault tolerance, you can create a
Distributed
table and enter it in subsequent configurations.
port
β The port on the ClickHouse server.
user
β Name of the ClickHouse user.
password
β Password of the ClickHouse user.
db
β Name of the database.
table
β Name of the table.
where
β The selection criteria. May be omitted.
invalidate_query
β Query for checking the dictionary status. Optional parameter. Read more in the section
Refreshing dictionary data using LIFETIME
.
secure
- Use ssl for connection.
query
β The custom query. Optional parameter.
:::note
The
table
or
where
fields cannot be used together with the
query
field. And either one of the
table
or
query
fields must be declared.
:::
MongoDB {#mongodb}
Example of settings:
xml
<source>
<mongodb>
<host>localhost</host>
<port>27017</port>
<user></user>
<password></password>
<db>test</db>
<collection>dictionary_source</collection>
<options>ssl=true</options>
</mongodb>
</source>
or
xml
<source>
<mongodb>
<uri>mongodb://localhost:27017/test?ssl=true</uri>
<collection>dictionary_source</collection>
</mongodb>
</source>
or
sql
SOURCE(MONGODB(
host 'localhost'
port 27017
user ''
password ''
db 'test'
collection 'dictionary_source'
options 'ssl=true'
))
Setting fields:
host
β The MongoDB host.
port
β The port on the MongoDB server.
user
β Name of the MongoDB user.
password
β Password of the MongoDB user.
db
β Name of the database.
collection
β Name of the collection.
options
- MongoDB connection string options (optional parameter).
or
sql
SOURCE(MONGODB(
uri 'mongodb://localhost:27017/clickhouse'
collection 'dictionary_source'
))
Setting fields:
uri
- URI for establish the connection.
collection
β Name of the collection.
More information about the engine
Redis {#redis}
Example of settings:
xml
<source>
<redis>
<host>localhost</host>
<port>6379</port>
<storage_type>simple</storage_type>
<db_index>0</db_index>
</redis>
</source>
or | {"source_file": "index.md"} | [
0.05228814482688904,
-0.043776609003543854,
-0.1045856699347496,
0.014501909725368023,
-0.08669465035200119,
-0.05319890007376671,
0.0592644028365612,
-0.010921796783804893,
-0.05852678790688515,
-0.008313334546983242,
0.04838303104043007,
-0.048242151737213135,
0.13966786861419678,
-0.064... |
8352e8a2-1d89-44b2-b717-1e74a645ab0f | xml
<source>
<redis>
<host>localhost</host>
<port>6379</port>
<storage_type>simple</storage_type>
<db_index>0</db_index>
</redis>
</source>
or
sql
SOURCE(REDIS(
host 'localhost'
port 6379
storage_type 'simple'
db_index 0
))
Setting fields:
host
β The Redis host.
port
β The port on the Redis server.
storage_type
β The structure of internal Redis storage using for work with keys.
simple
is for simple sources and for hashed single key sources,
hash_map
is for hashed sources with two keys. Ranged sources and cache sources with complex key are unsupported. May be omitted, default value is
simple
.
db_index
β The specific numeric index of Redis logical database. May be omitted, default value is 0.
Cassandra {#cassandra}
Example of settings:
xml
<source>
<cassandra>
<host>localhost</host>
<port>9042</port>
<user>username</user>
<password>qwerty123</password>
<keyspase>database_name</keyspase>
<column_family>table_name</column_family>
<allow_filtering>1</allow_filtering>
<partition_key_prefix>1</partition_key_prefix>
<consistency>One</consistency>
<where>"SomeColumn" = 42</where>
<max_threads>8</max_threads>
<query>SELECT id, value_1, value_2 FROM database_name.table_name</query>
</cassandra>
</source>
Setting fields:
host
β The Cassandra host or comma-separated list of hosts.
port
β The port on the Cassandra servers. If not specified, default port 9042 is used.
user
β Name of the Cassandra user.
password
β Password of the Cassandra user.
keyspace
β Name of the keyspace (database).
column_family
β Name of the column family (table).
allow_filtering
β Flag to allow or not potentially expensive conditions on clustering key columns. Default value is 1.
partition_key_prefix
β Number of partition key columns in primary key of the Cassandra table. Required for compose key dictionaries. Order of key columns in the dictionary definition must be the same as in Cassandra. Default value is 1 (the first key column is a partition key and other key columns are clustering key).
consistency
β Consistency level. Possible values:
One
,
Two
,
Three
,
All
,
EachQuorum
,
Quorum
,
LocalQuorum
,
LocalOne
,
Serial
,
LocalSerial
. Default value is
One
.
where
β Optional selection criteria.
max_threads
β The maximum number of threads to use for loading data from multiple partitions in compose key dictionaries.
query
β The custom query. Optional parameter.
:::note
The
column_family
or
where
fields cannot be used together with the
query
field. And either one of the
column_family
or
query
fields must be declared.
:::
PostgreSQL {#postgresql}
Example of settings: | {"source_file": "index.md"} | [
0.0393720418214798,
0.01247902400791645,
-0.12808683514595032,
-0.015895601361989975,
-0.05534416437149048,
-0.07015660405158997,
-0.008652236312627792,
0.04867812991142273,
-0.04309694096446037,
-0.00983826257288456,
0.04360462725162506,
-0.005551333539187908,
0.12098341435194016,
-0.1371... |
779b0ca9-9319-468d-a4df-3dfb782b0d97 | PostgreSQL {#postgresql}
Example of settings:
xml
<source>
<postgresql>
<host>postgresql-hostname</hoat>
<port>5432</port>
<user>clickhouse</user>
<password>qwerty</password>
<db>db_name</db>
<table>table_name</table>
<where>id=10</where>
<invalidate_query>SQL_QUERY</invalidate_query>
<query>SELECT id, value_1, value_2 FROM db_name.table_name</query>
</postgresql>
</source>
or
sql
SOURCE(POSTGRESQL(
port 5432
host 'postgresql-hostname'
user 'postgres_user'
password 'postgres_password'
db 'db_name'
table 'table_name'
replica(host 'example01-1' port 5432 priority 1)
replica(host 'example01-2' port 5432 priority 2)
where 'id=10'
invalidate_query 'SQL_QUERY'
query 'SELECT id, value_1, value_2 FROM db_name.table_name'
))
Setting fields:
host
β The host on the PostgreSQL server. You can specify it for all replicas, or for each one individually (inside
<replica>
).
port
β The port on the PostgreSQL server. You can specify it for all replicas, or for each one individually (inside
<replica>
).
user
β Name of the PostgreSQL user. You can specify it for all replicas, or for each one individually (inside
<replica>
).
password
β Password of the PostgreSQL user. You can specify it for all replicas, or for each one individually (inside
<replica>
).
replica
β Section of replica configurations. There can be multiple sections:
replica/host
β The PostgreSQL host.
replica/port
β The PostgreSQL port.
replica/priority
β The replica priority. When attempting to connect, ClickHouse traverses the replicas in order of priority. The lower the number, the higher the priority.
db
β Name of the database.
table
β Name of the table.
where
β The selection criteria. The syntax for conditions is the same as for
WHERE
clause in PostgreSQL. For example,
id > 10 AND id < 20
. Optional parameter.
invalidate_query
β Query for checking the dictionary status. Optional parameter. Read more in the section
Refreshing dictionary data using LIFETIME
.
background_reconnect
β Reconnect to replica in background if connection fails. Optional parameter.
query
β The custom query. Optional parameter.
:::note
The
table
or
where
fields cannot be used together with the
query
field. And either one of the
table
or
query
fields must be declared.
:::
Null {#null}
A special source that can be used to create dummy (empty) dictionaries. Such dictionaries can useful for tests or with setups with separated data and query nodes at nodes with Distributed tables.
sql
CREATE DICTIONARY null_dict (
id UInt64,
val UInt8,
default_val UInt8 DEFAULT 123,
nullable_val Nullable(UInt8)
)
PRIMARY KEY id
SOURCE(NULL())
LAYOUT(FLAT())
LIFETIME(0);
Dictionary Key and Fields {#dictionary-key-and-fields}
The
structure
clause describes the dictionary key and fields available for queries. | {"source_file": "index.md"} | [
0.01762116141617298,
0.01375051774084568,
-0.07640761882066727,
0.00009902249439619482,
-0.06999856978654861,
-0.009609888307750225,
-0.011496004648506641,
-0.017158370465040207,
-0.03867024928331375,
0.045642152428627014,
0.0616007000207901,
-0.05610428377985954,
0.03705734387040138,
-0.0... |
a0eb798e-d17c-4599-b6bf-998532dc3c08 | Dictionary Key and Fields {#dictionary-key-and-fields}
The
structure
clause describes the dictionary key and fields available for queries.
XML description:
```xml
Id
<attribute>
<!-- Attribute parameters -->
</attribute>
...
</structure>
```
Attributes are described in the elements:
<id>
β Key column
<attribute>
β Data column: there can be a multiple number of attributes.
DDL query:
sql
CREATE DICTIONARY dict_name (
Id UInt64,
-- attributes
)
PRIMARY KEY Id
...
Attributes are described in the query body:
PRIMARY KEY
β Key column
AttrName AttrType
β Data column. There can be a multiple number of attributes.
Key {#key}
ClickHouse supports the following types of keys:
Numeric key.
UInt64
. Defined in the
<id>
tag or using
PRIMARY KEY
keyword.
Composite key. Set of values of different types. Defined in the tag
<key>
or
PRIMARY KEY
keyword.
An xml structure can contain either
<id>
or
<key>
. DDL-query must contain single
PRIMARY KEY
.
:::note
You must not describe key as an attribute.
:::
Numeric Key {#numeric-key}
Type:
UInt64
.
Configuration example:
xml
<id>
<name>Id</name>
</id>
Configuration fields:
name
β The name of the column with keys.
For DDL-query:
sql
CREATE DICTIONARY (
Id UInt64,
...
)
PRIMARY KEY Id
...
PRIMARY KEY
β The name of the column with keys.
Composite Key {#composite-key}
The key can be a
tuple
from any types of fields. The
layout
in this case must be
complex_key_hashed
or
complex_key_cache
.
:::tip
A composite key can consist of a single element. This makes it possible to use a string as the key, for instance.
:::
The key structure is set in the element
<key>
. Key fields are specified in the same format as the dictionary
attributes
. Example:
xml
<structure>
<key>
<attribute>
<name>field1</name>
<type>String</type>
</attribute>
<attribute>
<name>field2</name>
<type>UInt32</type>
</attribute>
...
</key>
...
or
sql
CREATE DICTIONARY (
field1 String,
field2 UInt32
...
)
PRIMARY KEY field1, field2
...
For a query to the
dictGet*
function, a tuple is passed as the key. Example:
dictGetString('dict_name', 'attr_name', tuple('string for field1', num_for_field2))
.
Attributes {#attributes}
Configuration example:
xml
<structure>
...
<attribute>
<name>Name</name>
<type>ClickHouseDataType</type>
<null_value></null_value>
<expression>rand64()</expression>
<hierarchical>true</hierarchical>
<injective>true</injective>
<is_object_id>true</is_object_id>
</attribute>
</structure>
or
sql
CREATE DICTIONARY somename (
Name ClickHouseDataType DEFAULT '' EXPRESSION rand64() HIERARCHICAL INJECTIVE IS_OBJECT_ID
)
Configuration fields: | {"source_file": "index.md"} | [
-0.02382577583193779,
-0.007621205877512693,
-0.08127571642398834,
0.0008080267580226064,
-0.041629042476415634,
-0.058721404522657394,
0.08259841799736023,
-0.04806797578930855,
-0.020330538973212242,
-0.03957020863890648,
0.06732537597417831,
-0.00283147394657135,
0.12907454371452332,
-0... |
6eb05c99-0cb3-4556-8097-ab0a34525b6e | | Tag | Description | Required | | {"source_file": "index.md"} | [
-0.0034570067655295134,
0.07680454850196838,
-0.008665449917316437,
-0.013504531234502792,
0.11089115589857101,
-0.007485589943826199,
0.0341411791741848,
0.020732751116156578,
-0.0027893672231584787,
-0.032130319625139236,
-0.020735464990139008,
-0.1017616018652916,
0.08019524067640305,
0... |
a9a0e20e-6e84-4e04-b54f-35bc2c11867d | |------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------|
|
name | {"source_file": "index.md"} | [
-0.04348547011613846,
0.0023216381669044495,
-0.04704635590314865,
-0.03225376456975937,
-0.09775859862565994,
0.013375223614275455,
-0.001099019660614431,
0.04466715082526207,
-0.002515157451853156,
-0.06045687943696976,
0.06121503561735153,
-0.02469663694500923,
-0.03292921930551529,
-0.... |
d99c3f13-4443-4ace-8e60-24cbf06f171c | |
name
| Column name. | Yes |
|
type
| ClickHouse data type:
UInt8
,
UInt16
,
UInt32
,
UInt64
,
Int8
,
Int16
,
Int32
,
Int64
,
Float32
,
Float64
,
UUID
,
Decimal32
,
Decimal64
,
Decimal128
,
Decimal256
,
Date
,
Date32
,
DateTime
,
DateTime64
,
String
,
Array
.
ClickHouse tries to cast value from dictionary to the specified data type. For example, for MySQL, the field might be
TEXT
,
VARCHAR
, or
BLOB
in the MySQL source table, but it can be uploaded as
String
in ClickHouse.
Nullable
is currently supported for
Flat
,
Hashed
,
ComplexKeyHashed
,
Direct
,
ComplexKeyDirect
,
RangeHashed
, Polygon,
Cache
,
ComplexKeyCache
,
SSDCache
,
SSDComplexKeyCache
dictionaries. In
IPTrie
dictionaries
Nullable
types are not supported. | Yes |
|
null_value
| Default value for a non-existing element.
In the example, it is an empty string.
NULL
value can be used only for the
Nullable | {"source_file": "index.md"} | [
0.011370042338967323,
0.011405706405639648,
-0.12058524042367935,
0.005970833357423544,
-0.08200963586568832,
-0.040373750030994415,
0.05928139388561249,
0.010807713493704796,
-0.05974431708455086,
0.004268669057637453,
0.04306759685277939,
-0.03411256894469261,
0.08217048645019531,
-0.023... |
18b0267c-a05b-4656-8e84-ff11cf73ad80 | |
null_value
| Default value for a non-existing element.
In the example, it is an empty string.
NULL
value can be used only for the
Nullable
types (see the previous line with types description). | Yes |
|
expression
|
Expression
that ClickHouse executes on the value.
The expression can be a column name in the remote SQL database. Thus, you can use it to create an alias for the remote column. | {"source_file": "index.md"} | [
0.021859748288989067,
-0.0060205599293112755,
-0.09110474586486816,
0.03225427493453026,
-0.06533898413181305,
0.017397642135620117,
0.027228035032749176,
0.054254017770290375,
-0.014074069447815418,
0.038373593240976334,
0.054288554936647415,
-0.08396988362073898,
0.05690900236368179,
-0.... |
cde9d302-b351-4b1b-ba14-0cb618daae89 | Expression
that ClickHouse executes on the value.
The expression can be a column name in the remote SQL database. Thus, you can use it to create an alias for the remote column.
Default value: no expression. | No |
|
hierarchical
| If
true
, the attribute contains the value of a parent key for the current key. See
Hierarchical Dictionaries
.
Default value:
false | {"source_file": "index.md"} | [
0.02710483781993389,
-0.019171563908457756,
-0.06481708586215973,
0.02845904603600502,
-0.04878120496869087,
0.0007815329590812325,
0.026970233768224716,
-0.01983133889734745,
0.017298337072134018,
0.04733995720744133,
0.053114600479602814,
-0.07319503277540207,
0.0690433457493782,
0.00810... |
e650dddf-fb8d-4892-bfe4-0340a6de5aff | |
hierarchical
| If
true
, the attribute contains the value of a parent key for the current key. See
Hierarchical Dictionaries
.
Default value:
false
. | No |
|
injective
| Flag that shows whether the
id -> attribute
image is
injective
.
If
true
, ClickHouse can automatically place after the
GROUP BY
clause the requests to dictionaries with injection. Usually it significantly reduces the amount of such requests.
Default value:
false | {"source_file": "index.md"} | [
-0.007895104587078094,
0.029440466314554214,
-0.045691173523664474,
0.03589138388633728,
0.04922634735703468,
-0.06683517247438431,
0.005251809023320675,
-0.09065534174442291,
-0.004336732905358076,
-0.02332267537713051,
0.11326959729194641,
0.0025475830771028996,
0.05558183416724205,
-0.0... |
b83dba24-bf44-4e3b-9d9b-7c2415d90cdd | true
, ClickHouse can automatically place after the
GROUP BY
clause the requests to dictionaries with injection. Usually it significantly reduces the amount of such requests.
Default value:
false
. | No |
|
is_object_id
| Flag that shows whether the query is executed for a MongoDB document by
ObjectID
.
Default value:
false
. | {"source_file": "index.md"} | [
0.02077512815594673,
0.018347594887018204,
-0.0650540292263031,
0.1012209802865982,
-0.012614654377102852,
-0.06623444706201553,
-0.004415392410010099,
-0.1272175908088684,
0.006882460322231054,
-0.04329478368163109,
0.03221270069479942,
0.021502166986465454,
-0.022347966209053993,
-0.0388... |
0e2a0aff-277a-4073-8432-0a22d73991c8 | Hierarchical Dictionaries {#hierarchical-dictionaries}
ClickHouse supports hierarchical dictionaries with a
numeric key
.
Look at the following hierarchical structure:
text
0 (Common parent)
β
βββ 1 (Russia)
β β
β βββ 2 (Moscow)
β β
β βββ 3 (Center)
β
βββ 4 (Great Britain)
β
βββ 5 (London)
This hierarchy can be expressed as the following dictionary table.
| region_id | parent_region | region_name |
|------------|----------------|---------------|
| 1 | 0 | Russia |
| 2 | 1 | Moscow |
| 3 | 2 | Center |
| 4 | 0 | Great Britain |
| 5 | 4 | London |
This table contains a column
parent_region
that contains the key of the nearest parent for the element.
ClickHouse supports the hierarchical property for external dictionary attributes. This property allows you to configure the hierarchical dictionary similar to described above.
The
dictGetHierarchy
function allows you to get the parent chain of an element.
For our example, the structure of dictionary can be the following:
```xml
region_id
<attribute>
<name>parent_region</name>
<type>UInt64</type>
<null_value>0</null_value>
<hierarchical>true</hierarchical>
</attribute>
<attribute>
<name>region_name</name>
<type>String</type>
<null_value></null_value>
</attribute>
</structure>
```
Polygon dictionaries {#polygon-dictionaries}
This dictionary is optimized for point-in-polygon queries, essentially βreverse geocodingβ lookups. Given a coordinate (latitude/longitude), it efficiently finds which polygon/region (from a set of many polygons, such as country or region boundaries) contains that point. Itβs well-suited for mapping location coordinates to their containing region.
Example of a polygon dictionary configuration:
```xml
key
Array(Array(Array(Array(Float64))))
<attribute>
<name>name</name>
<type>String</type>
<null_value></null_value>
</attribute>
<attribute>
<name>value</name>
<type>UInt64</type>
<null_value>0</null_value>
</attribute>
</structure>
<layout>
<polygon>
<store_polygon_key_column>1</store_polygon_key_column>
</polygon>
</layout>
...
```
The corresponding
DDL-query
:
sql
CREATE DICTIONARY polygon_dict_name (
key Array(Array(Array(Array(Float64)))),
name String,
value UInt64
)
PRIMARY KEY key
LAYOUT(POLYGON(STORE_POLYGON_KEY_COLUMN 1))
...
When configuring the polygon dictionary, the key must have one of two types:
A simple polygon. It is an array of points.
MultiPolygon. It is an array of polygons. Each polygon is a two-dimensional array of points. The first element of this array is the outer boundary of the polygon, and subsequent elements specify areas to be excluded from it. | {"source_file": "index.md"} | [
0.06601455062627792,
-0.031319525092840195,
-0.0076703475788235664,
-0.06783508509397507,
0.00040440057637169957,
-0.07036255300045013,
-0.016562987118959427,
-0.05291973799467087,
-0.0277871023863554,
0.004583367612212896,
0.027484608814120293,
-0.046048153191804886,
0.014809366315603256,
... |
d4702916-1504-4e73-b1f2-c222e55c8e09 | Points can be specified as an array or a tuple of their coordinates. In the current implementation, only two-dimensional points are supported.
The user can upload their own data in all formats supported by ClickHouse.
There are 3 types of
in-memory storage
available:
POLYGON_SIMPLE
. This is a naive implementation, where a linear pass through all polygons is made for each query, and membership is checked for each one without using additional indexes.
POLYGON_INDEX_EACH
. A separate index is built for each polygon, which allows you to quickly check whether it belongs in most cases (optimized for geographical regions).
Also, a grid is superimposed on the area under consideration, which significantly narrows the number of polygons under consideration.
The grid is created by recursively dividing the cell into 16 equal parts and is configured with two parameters.
The division stops when the recursion depth reaches
MAX_DEPTH
or when the cell crosses no more than
MIN_INTERSECTIONS
polygons.
To respond to the query, there is a corresponding cell, and the index for the polygons stored in it is accessed alternately.
POLYGON_INDEX_CELL
. This placement also creates the grid described above. The same options are available. For each sheet cell, an index is built on all pieces of polygons that fall into it, which allows you to quickly respond to a request.
POLYGON
. Synonym to
POLYGON_INDEX_CELL
.
Dictionary queries are carried out using standard
functions
for working with dictionaries.
An important difference is that here the keys will be the points for which you want to find the polygon containing them.
Example
Example of working with the dictionary defined above:
sql
CREATE TABLE points (
x Float64,
y Float64
)
...
SELECT tuple(x, y) AS key, dictGet(dict_name, 'name', key), dictGet(dict_name, 'value', key) FROM points ORDER BY x, y;
As a result of executing the last command for each point in the 'points' table, a minimum area polygon containing this point will be found, and the requested attributes will be output.
Example
You can read columns from polygon dictionaries via SELECT query, just turn on the
store_polygon_key_column = 1
in the dictionary configuration or corresponding DDL-query.
Query:
```sql
CREATE TABLE polygons_test_table
(
key Array(Array(Array(Tuple(Float64, Float64)))),
name String
) ENGINE = TinyLog;
INSERT INTO polygons_test_table VALUES ([[[(3, 1), (0, 1), (0, -1), (3, -1)]]], 'Value');
CREATE DICTIONARY polygons_test_dictionary
(
key Array(Array(Array(Tuple(Float64, Float64)))),
name String
)
PRIMARY KEY key
SOURCE(CLICKHOUSE(TABLE 'polygons_test_table'))
LAYOUT(POLYGON(STORE_POLYGON_KEY_COLUMN 1))
LIFETIME(0);
SELECT * FROM polygons_test_dictionary;
```
Result:
text
ββkeyββββββββββββββββββββββββββββββ¬βnameβββ
β [[[(3,1),(0,1),(0,-1),(3,-1)]]] β Value β
βββββββββββββββββββββββββββββββββββ΄ββββββββ | {"source_file": "index.md"} | [
0.05781754106283188,
0.00230203615501523,
-0.11869083344936371,
0.04558980464935303,
0.007241375278681517,
-0.045778561383485794,
0.03251096233725548,
-0.0023838107008486986,
0.04957634583115578,
0.020630117505788803,
-0.05367857217788696,
0.021192533895373344,
0.057642288506031036,
-0.016... |
2119b33e-81c8-458d-b3fe-2d851fc451e0 | SELECT * FROM polygons_test_dictionary;
```
Result:
text
ββkeyββββββββββββββββββββββββββββββ¬βnameβββ
β [[[(3,1),(0,1),(0,-1),(3,-1)]]] β Value β
βββββββββββββββββββββββββββββββββββ΄ββββββββ
Regular Expression Tree Dictionary {#regexp-tree-dictionary}
This dictionary lets you map keys to values based on hierarchical regular-expression patterns. Itβs optimized for pattern-match lookups (e.g. classifying strings like user agent strings by matching regex patterns) rather than exact key matching.
Use Regular Expression Tree Dictionary in ClickHouse Open-Source {#use-regular-expression-tree-dictionary-in-clickhouse-open-source}
Regular expression tree dictionaries are defined in ClickHouse open-source using the YAMLRegExpTree source which is provided the path to a YAML file containing the regular expression tree.
sql
CREATE DICTIONARY regexp_dict
(
regexp String,
name String,
version String
)
PRIMARY KEY(regexp)
SOURCE(YAMLRegExpTree(PATH '/var/lib/clickhouse/user_files/regexp_tree.yaml'))
LAYOUT(regexp_tree)
...
The dictionary source
YAMLRegExpTree
represents the structure of a regexp tree. For example:
```yaml
- regexp: 'Linux/(\d+[.\d]*).+tlinux'
name: 'TencentOS'
version: '\1'
regexp: '\d+/tclwebkit(?:\d+[.\d]*)'
name: 'Android'
versions:
regexp: '33/tclwebkit'
version: '13'
regexp: '3[12]/tclwebkit'
version: '12'
regexp: '30/tclwebkit'
version: '11'
regexp: '29/tclwebkit'
version: '10'
```
This config consists of a list of regular expression tree nodes. Each node has the following structure:
regexp
: the regular expression of the node.
attributes
: a list of user-defined dictionary attributes. In this example, there are two attributes:
name
and
version
. The first node defines both attributes. The second node only defines attribute
name
. Attribute
version
is provided by the child nodes of the second node.
The value of an attribute may contain
back references
, referring to capture groups of the matched regular expression. In the example, the value of attribute
version
in the first node consists of a back-reference
\1
to capture group
(\d+[\.\d]*)
in the regular expression. Back-reference numbers range from 1 to 9 and are written as
$1
or
\1
(for number 1). The back reference is replaced by the matched capture group during query execution.
child nodes
: a list of children of a regexp tree node, each of which has its own attributes and (potentially) children nodes. String matching proceeds in a depth-first fashion. If a string matches a regexp node, the dictionary checks if it also matches the nodes' child nodes. If that is the case, the attributes of the deepest matching node are assigned. Attributes of a child node overwrite equally named attributes of parent nodes. The name of child nodes in YAML files can be arbitrary, e.g.
versions
in above example. | {"source_file": "index.md"} | [
0.05614542216062546,
0.009667536243796349,
0.0352160781621933,
-0.023827770724892616,
-0.019658079370856285,
-0.062017809599637985,
0.11345691978931427,
-0.06037617102265358,
-0.04328029230237007,
0.027126511558890343,
0.037106215953826904,
-0.03196652606129646,
0.05174366012215614,
-0.051... |
7b73f6ed-b2e3-4d6a-a947-35a087a3dd8a | Regexp tree dictionaries only allow access using the functions
dictGet
,
dictGetOrDefault
, and
dictGetAll
.
Example:
sql
SELECT dictGet('regexp_dict', ('name', 'version'), '31/tclwebkit1024');
Result:
text
ββdictGet('regexp_dict', ('name', 'version'), '31/tclwebkit1024')ββ
β ('Android','12') β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
In this case, we first match the regular expression
\d+/tclwebkit(?:\d+[\.\d]*)
in the top layer's second node. The dictionary then continues to look into the child nodes and finds that the string also matches
3[12]/tclwebkit
. As a result, the value of attribute
name
is
Android
(defined in the first layer) and the value of attribute
version
is
12
(defined the child node).
With a powerful YAML configure file, we can use a regexp tree dictionaries as a user agent string parser. We support
uap-core
and demonstrate how to use it in the functional test
02504_regexp_dictionary_ua_parser
Collecting Attribute Values {#collecting-attribute-values}
Sometimes it is useful to return values from multiple regular expressions that matched, rather than just the value of a leaf node. In these cases, the specialized
dictGetAll
function can be used. If a node has an attribute value of type
T
,
dictGetAll
will return an
Array(T)
containing zero or more values.
By default, the number of matches returned per key is unbounded. A bound can be passed as an optional fourth argument to
dictGetAll
. The array is populated in
topological order
, meaning that child nodes come before parent nodes, and sibling nodes follow the ordering in the source.
Example:
sql
CREATE DICTIONARY regexp_dict
(
regexp String,
tag String,
topological_index Int64,
captured Nullable(String),
parent String
)
PRIMARY KEY(regexp)
SOURCE(YAMLRegExpTree(PATH '/var/lib/clickhouse/user_files/regexp_tree.yaml'))
LAYOUT(regexp_tree)
LIFETIME(0)
```yaml
/var/lib/clickhouse/user_files/regexp_tree.yaml
regexp: 'clickhouse.com'
tag: 'ClickHouse'
topological_index: 1
paths:
regexp: 'clickhouse.com/docs(.*)'
tag: 'ClickHouse Documentation'
topological_index: 0
captured: '\1'
parent: 'ClickHouse'
regexp: '/docs(/|$)'
tag: 'Documentation'
topological_index: 2
regexp: 'github.com'
tag: 'GitHub'
topological_index: 3
captured: 'NULL'
```
sql
CREATE TABLE urls (url String) ENGINE=MergeTree ORDER BY url;
INSERT INTO urls VALUES ('clickhouse.com'), ('clickhouse.com/docs/en'), ('github.com/clickhouse/tree/master/docs');
SELECT url, dictGetAll('regexp_dict', ('tag', 'topological_index', 'captured', 'parent'), url, 2) FROM urls;
Result: | {"source_file": "index.md"} | [
-0.06845540553331375,
0.07573086768388748,
0.07429252564907074,
-0.0664229467511177,
-0.0010514773894101381,
-0.06884509325027466,
0.06965900212526321,
-0.07464777678251266,
0.029951734468340874,
0.020884983241558075,
0.0422607846558094,
-0.0710986852645874,
0.062177594751119614,
-0.021755... |
619f7580-3cd4-48fd-a574-9031e8ac2bfd | Result:
text
ββurlβββββββββββββββββββββββββββββββββββββ¬βdictGetAll('regexp_dict', ('tag', 'topological_index', 'captured', 'parent'), url, 2)ββ
β clickhouse.com β (['ClickHouse'],[1],[],[]) β
β clickhouse.com/docs/en β (['ClickHouse Documentation','ClickHouse'],[0,1],['/en'],['ClickHouse']) β
β github.com/clickhouse/tree/master/docs β (['Documentation','GitHub'],[2,3],[NULL],[]) β
ββββββββββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Matching Modes {#matching-modes}
Pattern matching behavior can be modified with certain dictionary settings:
-
regexp_dict_flag_case_insensitive
: Use case-insensitive matching (defaults to
false
). Can be overridden in individual expressions with
(?i)
and
(?-i)
.
-
regexp_dict_flag_dotall
: Allow '.' to match newline characters (defaults to
false
).
Use Regular Expression Tree Dictionary in ClickHouse Cloud {#use-regular-expression-tree-dictionary-in-clickhouse-cloud}
Above used
YAMLRegExpTree
source works in ClickHouse Open Source but not in ClickHouse Cloud. To use regexp tree dictionaries in ClickHouse could, first create a regexp tree dictionary from a YAML file locally in ClickHouse Open Source, then dump this dictionary into a CSV file using the
dictionary
table function and the
INTO OUTFILE
clause.
sql
SELECT * FROM dictionary(regexp_dict) INTO OUTFILE('regexp_dict.csv')
The content of csv file is:
text
1,0,"Linux/(\d+[\.\d]*).+tlinux","['version','name']","['\\1','TencentOS']"
2,0,"(\d+)/tclwebkit(\d+[\.\d]*)","['comment','version','name']","['test $1 and $2','$1','Android']"
3,2,"33/tclwebkit","['version']","['13']"
4,2,"3[12]/tclwebkit","['version']","['12']"
5,2,"3[12]/tclwebkit","['version']","['11']"
6,2,"3[12]/tclwebkit","['version']","['10']"
The schema of dumped file is:
id UInt64
: the id of the RegexpTree node.
parent_id UInt64
: the id of the parent of a node.
regexp String
: the regular expression string.
keys Array(String)
: the names of user-defined attributes.
values Array(String)
: the values of user-defined attributes.
To create the dictionary in ClickHouse Cloud, first create a table
regexp_dictionary_source_table
with below table structure:
sql
CREATE TABLE regexp_dictionary_source_table
(
id UInt64,
parent_id UInt64,
regexp String,
keys Array(String),
values Array(String)
) ENGINE=Memory;
Then update the local CSV by
bash
clickhouse client \
--host MY_HOST \
--secure \
--password MY_PASSWORD \
--query "
INSERT INTO regexp_dictionary_source_table
SELECT * FROM input ('id UInt64, parent_id UInt64, regexp String, keys Array(String), values Array(String)')
FORMAT CSV" < regexp_dict.csv | {"source_file": "index.md"} | [
-0.031578730791807175,
0.053093042224645615,
0.07519197463989258,
-0.013615738600492477,
0.06300201267004013,
-0.11150546371936798,
0.06002284958958626,
-0.066532664000988,
-0.02348468452692032,
-0.02566053345799446,
0.04266905039548874,
-0.00434470409527421,
0.031034186482429504,
0.055774... |
dc49499c-c03b-4b5a-bf87-db4d44e4055b | You can see how to
Insert Local Files
for more details. After we initialize the source table, we can create a RegexpTree by table source:
sql
CREATE DICTIONARY regexp_dict
(
regexp String,
name String,
version String
PRIMARY KEY(regexp)
SOURCE(CLICKHOUSE(TABLE 'regexp_dictionary_source_table'))
LIFETIME(0)
LAYOUT(regexp_tree);
Embedded Dictionaries {#embedded-dictionaries}
ClickHouse contains a built-in feature for working with a geobase.
This allows you to:
Use a region's ID to get its name in the desired language.
Use a region's ID to get the ID of a city, area, federal district, country, or continent.
Check whether a region is part of another region.
Get a chain of parent regions.
All the functions support "translocality," the ability to simultaneously use different perspectives on region ownership. For more information, see the section "Functions for working with web analytics dictionaries".
The internal dictionaries are disabled in the default package.
To enable them, uncomment the parameters
path_to_regions_hierarchy_file
and
path_to_regions_names_files
in the server configuration file.
The geobase is loaded from text files.
Place the
regions_hierarchy*.txt
files into the
path_to_regions_hierarchy_file
directory. This configuration parameter must contain the path to the
regions_hierarchy.txt
file (the default regional hierarchy), and the other files (
regions_hierarchy_ua.txt
) must be located in the same directory.
Put the
regions_names_*.txt
files in the
path_to_regions_names_files
directory.
You can also create these files yourself. The file format is as follows:
regions_hierarchy*.txt
: TabSeparated (no header), columns:
region ID (
UInt32
)
parent region ID (
UInt32
)
region type (
UInt8
): 1 - continent, 3 - country, 4 - federal district, 5 - region, 6 - city; other types do not have values
population (
UInt32
) β optional column
regions_names_*.txt
: TabSeparated (no header), columns:
region ID (
UInt32
)
region name (
String
) β Can't contain tabs or line feeds, even escaped ones.
A flat array is used for storing in RAM. For this reason, IDs shouldn't be more than a million.
Dictionaries can be updated without restarting the server. However, the set of available dictionaries is not updated.
For updates, the file modification times are checked. If a file has changed, the dictionary is updated.
The interval to check for changes is configured in the
builtin_dictionaries_reload_interval
parameter.
Dictionary updates (other than loading at first use) do not block queries. During updates, queries use the old versions of dictionaries. If an error occurs during an update, the error is written to the server log, and queries continue using the old version of dictionaries. | {"source_file": "index.md"} | [
0.07943006604909897,
-0.028120731934905052,
-0.054447486996650696,
0.016579821705818176,
-0.039030127227306366,
-0.01233948115259409,
0.04423242062330246,
-0.04000287130475044,
-0.09179017692804337,
-0.0006077451980672777,
-0.0043656183406710625,
-0.1163346916437149,
0.07878043502569199,
0... |
88b9a31e-8bab-47bf-a36e-5390ca46c87e | We recommend periodically updating the dictionaries with the geobase. During an update, generate new files and write them to a separate location. When everything is ready, rename them to the files used by the server.
There are also functions for working with OS identifiers and search engines, but they shouldn't be used. | {"source_file": "index.md"} | [
0.027961289510130882,
-0.06567435711622238,
0.025439072400331497,
-0.045839134603738785,
-0.0659560039639473,
-0.08221717178821564,
-0.044805314391851425,
-0.03992967680096626,
-0.025505872443318367,
0.010141946375370026,
0.018508942797780037,
0.06246478483080864,
0.027003386989235878,
-0.... |
c4b94cbf-cda2-42dc-9306-ef1dc726132a | description: 'Documentation for the lagInFrame window function'
sidebar_label: 'lagInFrame'
sidebar_position: 9
slug: /sql-reference/window-functions/lagInFrame
title: 'lagInFrame'
doc_type: 'reference'
lagInFrame
Returns a value evaluated at the row that is at a specified physical offset row before the current row within the ordered frame.
:::warning
lagInFrame
behavior differs from the standard SQL
lag
window function.
Clickhouse window function
lagInFrame
respects the window frame.
To get behavior identical to the
lag
, use
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
.
:::
Syntax
sql
lagInFrame(x[, offset[, default]])
OVER ([[PARTITION BY grouping_column] [ORDER BY sorting_column]
[ROWS or RANGE expression_to_bound_rows_withing_the_group]] | [window_name])
FROM table_name
WINDOW window_name as ([[PARTITION BY grouping_column] [ORDER BY sorting_column])
For more detail on window function syntax see:
Window Functions - Syntax
.
Parameters
-
x
β Column name.
-
offset
β Offset to apply.
(U)Int*
. (Optional -
1
by default).
-
default
β Value to return if calculated row exceeds the boundaries of the window frame. (Optional - default value of column type when omitted).
Returned value
Value evaluated at the row that is at a specified physical offset before the current row within the ordered frame.
Example
This example looks at historical data for a specific stock and uses the
lagInFrame
function to calculate a day-to-day delta and percentage change in the closing price of the stock.
Query:
``sql
CREATE TABLE stock_prices
(
date
Date,
open
Float32, -- opening price
high
Float32, -- daily high
low
Float32, -- daily low
close
Float32, -- closing price
volume` UInt32 -- trade volume
)
Engine = Memory;
INSERT INTO stock_prices FORMAT Values
('2024-06-03', 113.62, 115.00, 112.00, 115.00, 438392000),
('2024-06-04', 115.72, 116.60, 114.04, 116.44, 403324000),
('2024-06-05', 118.37, 122.45, 117.47, 122.44, 528402000),
('2024-06-06', 124.05, 125.59, 118.32, 121.00, 664696000),
('2024-06-07', 119.77, 121.69, 118.02, 120.89, 412386000);
```
sql
SELECT
date,
close,
lagInFrame(close, 1, close) OVER (ORDER BY date ASC
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS previous_day_close,
COALESCE(ROUND(close - previous_day_close, 2)) AS delta,
COALESCE(ROUND((delta / previous_day_close) * 100, 2)) AS percent_change
FROM stock_prices
ORDER BY date DESC
Result: | {"source_file": "lagInFrame.md"} | [
0.04263802617788315,
-0.07307042926549911,
-0.04393821954727173,
0.0008238892769441009,
-0.0024672860745340586,
0.07768315821886063,
0.05247729271650314,
0.021875303238630295,
-0.0015752846375107765,
-0.026288317516446114,
0.05765340104699135,
0.029483428224921227,
-0.04043227434158325,
-0... |
9d2e8d41-f911-4512-a58b-23834a5b18f9 | Result:
response
ββββββββdateββ¬ββcloseββ¬βprevious_day_closeββ¬βdeltaββ¬βpercent_changeββ
1. β 2024-06-07 β 120.89 β 121 β -0.11 β -0.09 β
2. β 2024-06-06 β 121 β 122.44 β -1.44 β -1.18 β
3. β 2024-06-05 β 122.44 β 116.44 β 6 β 5.15 β
4. β 2024-06-04 β 116.44 β 115 β 1.44 β 1.25 β
5. β 2024-06-03 β 115 β 115 β 0 β 0 β
ββββββββββββββ΄βββββββββ΄βββββββββββββββββββββ΄ββββββββ΄βββββββββββββββββ | {"source_file": "lagInFrame.md"} | [
-0.03761488199234009,
0.11510123312473297,
0.04617238789796829,
0.06357457488775253,
-0.024647699669003487,
-0.07659503817558289,
0.011167805641889572,
-0.02927033230662346,
0.02835378237068653,
-0.008865779265761375,
0.06831610947847366,
-0.08163052797317505,
-0.021497562527656555,
-0.016... |
01834d56-4836-446f-968b-56bf09dd07ea | description: 'Documentation for the lead window function'
sidebar_label: 'lead'
sidebar_position: 10
slug: /sql-reference/window-functions/lead
title: 'lead'
doc_type: 'reference'
lead
Returns a value evaluated at the row that is offset rows after the current row within the ordered frame.
This function is similar to
leadInFrame
, but always uses the
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
frame.
Syntax
sql
lead(x[, offset[, default]])
OVER ([[PARTITION BY grouping_column] [ORDER BY sorting_column]] | [window_name])
FROM table_name
WINDOW window_name as ([[PARTITION BY grouping_column] [ORDER BY sorting_column])
For more detail on window function syntax see:
Window Functions - Syntax
.
Parameters
x
β Column name.
offset
β Offset to apply.
(U)Int*
. (Optional -
1
by default).
default
β Value to return if calculated row exceeds the boundaries of the window frame. (Optional - default value of column type when omitted).
Returned value
value evaluated at the row that is offset rows after the current row within the ordered frame.
Example
This example looks at
historical data
for Nobel Prize winners and uses the
lead
function to return a list of successive winners in the physics category.
sql title="Query"
CREATE OR REPLACE VIEW nobel_prize_laureates
AS SELECT *
FROM file('nobel_laureates_data.csv');
sql title="Query"
SELECT
fullName,
lead(year, 1, year) OVER (PARTITION BY category ORDER BY year ASC
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS year,
category,
motivation
FROM nobel_prize_laureates
WHERE category = 'physics'
ORDER BY year DESC
LIMIT 9 | {"source_file": "lead.md"} | [
-0.0195371825248003,
0.009349130094051361,
-0.06651952117681503,
-0.0032186629250645638,
-0.013746906071901321,
0.0924215093255043,
0.0322284959256649,
0.05390552058815956,
-0.034060411155223846,
-0.005308415275067091,
0.008572282269597054,
0.047681864351034164,
-0.0236436128616333,
-0.086... |
b8429356-ca2c-4466-96fc-a2798f895c87 | response title="Query"
ββfullNameββββββββββ¬βyearββ¬βcategoryββ¬βmotivationββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
1. β Anne L Huillier β 2023 β physics β for experimental methods that generate attosecond pulses of light for the study of electron dynamics in matter β
2. β Pierre Agostini β 2023 β physics β for experimental methods that generate attosecond pulses of light for the study of electron dynamics in matter β
3. β Ferenc Krausz β 2023 β physics β for experimental methods that generate attosecond pulses of light for the study of electron dynamics in matter β
4. β Alain Aspect β 2022 β physics β for experiments with entangled photons establishing the violation of Bell inequalities and pioneering quantum information science β
5. β Anton Zeilinger β 2022 β physics β for experiments with entangled photons establishing the violation of Bell inequalities and pioneering quantum information science β
6. β John Clauser β 2022 β physics β for experiments with entangled photons establishing the violation of Bell inequalities and pioneering quantum information science β
7. β Giorgio Parisi β 2021 β physics β for the discovery of the interplay of disorder and fluctuations in physical systems from atomic to planetary scales β
8. β Klaus Hasselmann β 2021 β physics β for the physical modelling of Earths climate quantifying variability and reliably predicting global warming β
9. β Syukuro Manabe β 2021 β physics β for the physical modelling of Earths climate quantifying variability and reliably predicting global warming β
ββββββββββββββββββββ΄βββββββ΄βββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | {"source_file": "lead.md"} | [
-0.13364170491695404,
-0.05813859403133392,
0.022627880796790123,
0.10564921796321869,
-0.04686427861452103,
-0.010150594636797905,
-0.022778963670134544,
0.024981804192066193,
-0.06416008621454239,
0.05901974439620972,
0.0008102779393084347,
-0.08008266240358353,
-0.01278737559914589,
-0.... |
75833d04-967d-4930-919d-4ae0cb6c6f4e | description: 'Documentation for the rank window function'
sidebar_label: 'rank'
sidebar_position: 6
slug: /sql-reference/window-functions/rank
title: 'rank'
doc_type: 'reference'
rank
Ranks the current row within its partition with gaps. In other words, if the value of any row it encounters is equal to the value of a previous row then it will receive the same rank as that previous row.
The rank of the next row is then equal to the rank of the previous row plus a gap equal to the number of times the previous rank was given.
The
dense_rank
function provides the same behaviour but without gaps in ranking.
Syntax
sql
rank ()
OVER ([[PARTITION BY grouping_column] [ORDER BY sorting_column]
[ROWS or RANGE expression_to_bound_rows_withing_the_group]] | [window_name])
FROM table_name
WINDOW window_name as ([[PARTITION BY grouping_column] [ORDER BY sorting_column])
For more detail on window function syntax see:
Window Functions - Syntax
.
Returned value
A number for the current row within its partition, including gaps.
UInt64
.
Example
The following example is based on the example provided in the video instructional
Ranking window functions in ClickHouse
.
Query:
``sql
CREATE TABLE salaries
(
team
String,
player
String,
salary
UInt32,
position` String
)
Engine = Memory;
INSERT INTO salaries FORMAT Values
('Port Elizabeth Barbarians', 'Gary Chen', 195000, 'F'),
('New Coreystad Archdukes', 'Charles Juarez', 190000, 'F'),
('Port Elizabeth Barbarians', 'Michael Stanley', 150000, 'D'),
('New Coreystad Archdukes', 'Scott Harrison', 150000, 'D'),
('Port Elizabeth Barbarians', 'Robert George', 195000, 'M'),
('South Hampton Seagulls', 'Douglas Benson', 150000, 'M'),
('South Hampton Seagulls', 'James Henderson', 140000, 'M');
```
sql
SELECT player, salary,
rank() OVER (ORDER BY salary DESC) AS rank
FROM salaries;
Result:
response
ββplayerβββββββββββ¬βsalaryββ¬βrankββ
1. β Gary Chen β 195000 β 1 β
2. β Robert George β 195000 β 1 β
3. β Charles Juarez β 190000 β 3 β
4. β Douglas Benson β 150000 β 4 β
5. β Michael Stanley β 150000 β 4 β
6. β Scott Harrison β 150000 β 4 β
7. β James Henderson β 140000 β 7 β
βββββββββββββββββββ΄βββββββββ΄βββββββ | {"source_file": "rank.md"} | [
-0.06084614619612694,
-0.07241954654455185,
0.008399910293519497,
0.00859243143349886,
-0.010923091322183609,
0.0312870591878891,
0.029368000105023384,
0.04722495377063751,
0.015887340530753136,
-0.010303456336259842,
-0.028415922075510025,
0.01185525767505169,
0.03410044312477112,
-0.0515... |
0008e466-8120-41e3-a95f-ea4474ead7bc | description: 'Documentation for the leadInFrame window function'
sidebar_label: 'leadInFrame'
sidebar_position: 10
slug: /sql-reference/window-functions/leadInFrame
title: 'leadInFrame'
doc_type: 'reference'
leadInFrame
Returns a value evaluated at the row that is offset rows after the current row within the ordered frame.
:::warning
leadInFrame
behavior differs from the standard SQL
lead
window function.
Clickhouse window function
leadInFrame
respects the window frame.
To get behavior identical to the
lead
, use
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
.
:::
Syntax
sql
leadInFrame(x[, offset[, default]])
OVER ([[PARTITION BY grouping_column] [ORDER BY sorting_column]
[ROWS or RANGE expression_to_bound_rows_withing_the_group]] | [window_name])
FROM table_name
WINDOW window_name as ([[PARTITION BY grouping_column] [ORDER BY sorting_column])
For more detail on window function syntax see:
Window Functions - Syntax
.
Parameters
-
x
β Column name.
-
offset
β Offset to apply.
(U)Int*
. (Optional -
1
by default).
-
default
β Value to return if calculated row exceeds the boundaries of the window frame. (Optional - default value of column type when omitted).
Returned value
value evaluated at the row that is offset rows after the current row within the ordered frame.
Example
This example looks at
historical data
for Nobel Prize winners and uses the
leadInFrame
function to return a list of successive winners in the physics category.
Query:
sql
CREATE OR REPLACE VIEW nobel_prize_laureates
AS SELECT *
FROM file('nobel_laureates_data.csv');
sql
SELECT
fullName,
leadInFrame(year, 1, year) OVER (PARTITION BY category ORDER BY year ASC
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS year,
category,
motivation
FROM nobel_prize_laureates
WHERE category = 'physics'
ORDER BY year DESC
LIMIT 9
Result: | {"source_file": "leadInFrame.md"} | [
-0.004920397885143757,
-0.02830425463616848,
-0.06455644965171814,
0.0029354991856962442,
0.0015276470221579075,
0.07845961302518845,
0.0417005829513073,
0.030704256147146225,
-0.03686300292611122,
-0.009447498247027397,
0.012251405045390129,
0.046248454600572586,
-0.0439331941306591,
-0.0... |
84ad6006-ab88-4fa7-928b-16c27fa4dce8 | Result:
response
ββfullNameββββββββββ¬βyearββ¬βcategoryββ¬βmotivationββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
1. β Anne L Huillier β 2023 β physics β for experimental methods that generate attosecond pulses of light for the study of electron dynamics in matter β
2. β Pierre Agostini β 2023 β physics β for experimental methods that generate attosecond pulses of light for the study of electron dynamics in matter β
3. β Ferenc Krausz β 2023 β physics β for experimental methods that generate attosecond pulses of light for the study of electron dynamics in matter β
4. β Alain Aspect β 2022 β physics β for experiments with entangled photons establishing the violation of Bell inequalities and pioneering quantum information science β
5. β Anton Zeilinger β 2022 β physics β for experiments with entangled photons establishing the violation of Bell inequalities and pioneering quantum information science β
6. β John Clauser β 2022 β physics β for experiments with entangled photons establishing the violation of Bell inequalities and pioneering quantum information science β
7. β Giorgio Parisi β 2021 β physics β for the discovery of the interplay of disorder and fluctuations in physical systems from atomic to planetary scales β
8. β Klaus Hasselmann β 2021 β physics β for the physical modelling of Earths climate quantifying variability and reliably predicting global warming β
9. β Syukuro Manabe β 2021 β physics β for the physical modelling of Earths climate quantifying variability and reliably predicting global warming β
ββββββββββββββββββββ΄βββββββ΄βββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | {"source_file": "leadInFrame.md"} | [
-0.13776496052742004,
-0.03256416693329811,
0.02959732711315155,
0.10809742659330368,
-0.040329452604055405,
0.004213058389723301,
-0.0067359465174376965,
0.021112922579050064,
-0.05936373770236969,
0.04581531137228012,
0.009565467946231365,
-0.09350914508104324,
-0.006235672160983086,
-0.... |
132cd7c3-d39c-4143-a697-18d513bde113 | description: 'Documentation for the percent_rank window function'
sidebar_label: 'percent_rank'
sidebar_position: 8
slug: /sql-reference/window-functions/percent_rank
title: 'percent_rank'
doc_type: 'reference'
percent_rank
returns the relative rank (i.e. percentile) of rows within a window partition.
Syntax
Alias:
percentRank
(case-sensitive)
sql
percent_rank ()
OVER ([[PARTITION BY grouping_column] [ORDER BY sorting_column]
[RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING]] | [window_name])
FROM table_name
WINDOW window_name as ([PARTITION BY grouping_column] [ORDER BY sorting_column] RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
The default and required window frame definition is
RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
.
For more detail on window function syntax see:
Window Functions - Syntax
.
Example
Query:
``sql
CREATE TABLE salaries
(
team
String,
player
String,
salary
UInt32,
position` String
)
Engine = Memory;
INSERT INTO salaries FORMAT Values
('Port Elizabeth Barbarians', 'Gary Chen', 195000, 'F'),
('New Coreystad Archdukes', 'Charles Juarez', 190000, 'F'),
('Port Elizabeth Barbarians', 'Michael Stanley', 150000, 'D'),
('New Coreystad Archdukes', 'Scott Harrison', 150000, 'D'),
('Port Elizabeth Barbarians', 'Robert George', 195000, 'M'),
('South Hampton Seagulls', 'Douglas Benson', 150000, 'M'),
('South Hampton Seagulls', 'James Henderson', 140000, 'M');
```
sql
SELECT player, salary,
percent_rank() OVER (ORDER BY salary DESC) AS percent_rank
FROM salaries;
Result:
```response
ββplayerβββββββββββ¬βsalaryββ¬βββββββpercent_rankββ
1. β Gary Chen β 195000 β 0 β
2. β Robert George β 195000 β 0 β
3. β Charles Juarez β 190000 β 0.3333333333333333 β
4. β Michael Stanley β 150000 β 0.5 β
5. β Scott Harrison β 150000 β 0.5 β
6. β Douglas Benson β 150000 β 0.5 β
7. β James Henderson β 140000 β 1 β
βββββββββββββββββββ΄βββββββββ΄βββββββββββββββββββββ
``` | {"source_file": "percent_rank.md"} | [
0.002775783184915781,
0.02044142782688141,
-0.07131755352020264,
-0.000011042631740565412,
-0.04555613547563553,
0.03675279766321182,
0.03598250448703766,
0.10134386271238327,
-0.021107276901602745,
-0.004204204306006432,
0.0003766543813981116,
-0.011904537677764893,
0.039538051933050156,
... |
7731d096-9e59-44b7-8275-d18c52497ec5 | description: 'Documentation for the first_value window function'
sidebar_label: 'first_value'
sidebar_position: 3
slug: /sql-reference/window-functions/first_value
title: 'first_value'
doc_type: 'reference'
first_value
Returns the first value evaluated within its ordered frame. By default, NULL arguments are skipped, however the
RESPECT NULLS
modifier can be used to override this behaviour.
Syntax
sql
first_value (column_name) [[RESPECT NULLS] | [IGNORE NULLS]]
OVER ([[PARTITION BY grouping_column] [ORDER BY sorting_column]
[ROWS or RANGE expression_to_bound_rows_withing_the_group]] | [window_name])
FROM table_name
WINDOW window_name as ([PARTITION BY grouping_column] [ORDER BY sorting_column])
Alias:
any
.
:::note
Using the optional modifier
RESPECT NULLS
after
first_value(column_name)
will ensure that
NULL
arguments are not skipped.
See
NULL processing
for more information.
Alias:
firstValueRespectNulls
:::
For more detail on window function syntax see:
Window Functions - Syntax
.
Returned value
The first value evaluated within its ordered frame.
Example
In this example the
first_value
function is used to find the highest paid footballer from a fictional dataset of salaries of Premier League football players.
Query:
``sql
DROP TABLE IF EXISTS salaries;
CREATE TABLE salaries
(
team
String,
player
String,
salary
UInt32,
position` String
)
Engine = Memory;
INSERT INTO salaries FORMAT VALUES
('Port Elizabeth Barbarians', 'Gary Chen', 196000, 'F'),
('New Coreystad Archdukes', 'Charles Juarez', 190000, 'F'),
('Port Elizabeth Barbarians', 'Michael Stanley', 100000, 'D'),
('New Coreystad Archdukes', 'Scott Harrison', 180000, 'D'),
('Port Elizabeth Barbarians', 'Robert George', 195000, 'M'),
('South Hampton Seagulls', 'Douglas Benson', 150000, 'M'),
('South Hampton Seagulls', 'James Henderson', 140000, 'M');
```
sql
SELECT player, salary,
first_value(player) OVER (ORDER BY salary DESC) AS highest_paid_player
FROM salaries;
Result:
response
ββplayerβββββββββββ¬βsalaryββ¬βhighest_paid_playerββ
1. β Gary Chen β 196000 β Gary Chen β
2. β Robert George β 195000 β Gary Chen β
3. β Charles Juarez β 190000 β Gary Chen β
4. β Scott Harrison β 180000 β Gary Chen β
5. β Douglas Benson β 150000 β Gary Chen β
6. β James Henderson β 140000 β Gary Chen β
7. β Michael Stanley β 100000 β Gary Chen β
βββββββββββββββββββ΄βββββββββ΄ββββββββββββββββββββββ | {"source_file": "first_value.md"} | [
-0.015517989173531532,
0.019495774060487747,
-0.027371296659111977,
0.019758334383368492,
-0.04284827411174774,
0.04848676547408104,
0.09729170799255371,
0.03356228396296501,
0.026657545939087868,
-0.02576623298227787,
0.038249462842941284,
-0.01629728451371193,
-0.02649971842765808,
-0.06... |
35f6920d-5c81-4cd3-80da-ba733079928c | description: 'Documentation for the lag window function'
sidebar_label: 'lag'
sidebar_position: 9
slug: /sql-reference/window-functions/lag
title: 'lag'
doc_type: 'reference'
lag
Returns a value evaluated at the row that is at a specified physical offset before the current row within the ordered frame.
This function is similar to
lagInFrame
, but always uses the
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
frame.
Syntax
sql
lag(x[, offset[, default]])
OVER ([[PARTITION BY grouping_column] [ORDER BY sorting_column]] | [window_name])
FROM table_name
WINDOW window_name as ([[PARTITION BY grouping_column] [ORDER BY sorting_column])
For more detail on window function syntax see:
Window Functions - Syntax
.
Parameters
x
β Column name.
offset
β Offset to apply.
(U)Int*
. (Optional -
1
by default).
default
β Value to return if calculated row exceeds the boundaries of the window frame. (Optional - default value of column type when omitted).
Returned value
Value evaluated at the row that is at a specified physical offset before the current row within the ordered frame.
Example
This example looks at historical data for a specific stock and uses the
lag
function to calculate a day-to-day delta and percentage change in the closing price of the stock.
``sql title="Query"
CREATE TABLE stock_prices
(
date
Date,
open
Float32, -- opening price
high
Float32, -- daily high
low
Float32, -- daily low
close
Float32, -- closing price
volume` UInt32 -- trade volume
)
Engine = Memory;
INSERT INTO stock_prices FORMAT Values
('2024-06-03', 113.62, 115.00, 112.00, 115.00, 438392000),
('2024-06-04', 115.72, 116.60, 114.04, 116.44, 403324000),
('2024-06-05', 118.37, 122.45, 117.47, 122.44, 528402000),
('2024-06-06', 124.05, 125.59, 118.32, 121.00, 664696000),
('2024-06-07', 119.77, 121.69, 118.02, 120.89, 412386000);
```
sql title="Query"
SELECT
date,
close,
lag(close, 1, close) OVER (ORDER BY date ASC) AS previous_day_close,
COALESCE(ROUND(close - previous_day_close, 2)) AS delta,
COALESCE(ROUND((delta / previous_day_close) * 100, 2)) AS percent_change
FROM stock_prices
ORDER BY date DESC
response title="Response"
ββββββββdateββ¬ββcloseββ¬βprevious_day_closeββ¬βdeltaββ¬βpercent_changeββ
1. β 2024-06-07 β 120.89 β 121 β -0.11 β -0.09 β
2. β 2024-06-06 β 121 β 122.44 β -1.44 β -1.18 β
3. β 2024-06-05 β 122.44 β 116.44 β 6 β 5.15 β
4. β 2024-06-04 β 116.44 β 115 β 1.44 β 1.25 β
5. β 2024-06-03 β 115 β 115 β 0 β 0 β
ββββββββββββββ΄βββββββββ΄βββββββββββββββββββββ΄ββββββββ΄βββββββββββββββββ | {"source_file": "lag.md"} | [
0.028579551726579666,
-0.041512373834848404,
-0.048873625695705414,
0.01637144573032856,
-0.008695447817444801,
0.05011390894651413,
0.04333988577127457,
0.03442934900522232,
-0.0008404005784541368,
-0.04019347205758095,
0.04239976033568382,
0.03905022516846657,
-0.04582170769572258,
-0.08... |
d29b572f-12bd-4f41-9bbe-8d717f41ac74 | description: 'Documentation for the last_value window function'
sidebar_label: 'last_value'
sidebar_position: 4
slug: /sql-reference/window-functions/last_value
title: 'last_value'
doc_type: 'reference'
last_value
Returns the last value evaluated within its ordered frame. By default, NULL arguments are skipped, however the
RESPECT NULLS
modifier can be used to override this behaviour.
Syntax
sql
last_value (column_name) [[RESPECT NULLS] | [IGNORE NULLS]]
OVER ([[PARTITION BY grouping_column] [ORDER BY sorting_column]
[ROWS or RANGE expression_to_bound_rows_withing_the_group]] | [window_name])
FROM table_name
WINDOW window_name as ([[PARTITION BY grouping_column] [ORDER BY sorting_column])
Alias:
anyLast
.
:::note
Using the optional modifier
RESPECT NULLS
after
first_value(column_name)
will ensure that
NULL
arguments are not skipped.
See
NULL processing
for more information.
Alias:
lastValueRespectNulls
:::
For more detail on window function syntax see:
Window Functions - Syntax
.
Returned value
The last value evaluated within its ordered frame.
Example
In this example the
last_value
function is used to find the lowest paid footballer from a fictional dataset of salaries of Premier League football players.
Query:
``sql
DROP TABLE IF EXISTS salaries;
CREATE TABLE salaries
(
team
String,
player
String,
salary
UInt32,
position` String
)
Engine = Memory;
INSERT INTO salaries FORMAT VALUES
('Port Elizabeth Barbarians', 'Gary Chen', 196000, 'F'),
('New Coreystad Archdukes', 'Charles Juarez', 190000, 'F'),
('Port Elizabeth Barbarians', 'Michael Stanley', 100000, 'D'),
('New Coreystad Archdukes', 'Scott Harrison', 180000, 'D'),
('Port Elizabeth Barbarians', 'Robert George', 195000, 'M'),
('South Hampton Seagulls', 'Douglas Benson', 150000, 'M'),
('South Hampton Seagulls', 'James Henderson', 140000, 'M');
```
sql
SELECT player, salary,
last_value(player) OVER (ORDER BY salary DESC RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS lowest_paid_player
FROM salaries;
Result:
response
ββplayerβββββββββββ¬βsalaryββ¬βlowest_paid_playerββ
1. β Gary Chen β 196000 β Michael Stanley β
2. β Robert George β 195000 β Michael Stanley β
3. β Charles Juarez β 190000 β Michael Stanley β
4. β Scott Harrison β 180000 β Michael Stanley β
5. β Douglas Benson β 150000 β Michael Stanley β
6. β James Henderson β 140000 β Michael Stanley β
7. β Michael Stanley β 100000 β Michael Stanley β
βββββββββββββββββββ΄βββββββββ΄βββββββββββββββββββββ | {"source_file": "last_value.md"} | [
0.0036911724600940943,
0.0452982634305954,
-0.026703251525759697,
-0.002332191914319992,
-0.026714805513620377,
0.06179897487163544,
0.07399211823940277,
0.04659305140376091,
0.0320243239402771,
-0.004690338391810656,
0.030811013653874397,
-0.002353319665417075,
-0.03088739700615406,
-0.05... |
ddb8d184-c484-49ec-b056-f0d01a70fdf9 | description: 'Overview page for window functions'
sidebar_label: 'Window Functions'
sidebar_position: 1
slug: /sql-reference/window-functions/
title: 'Window Functions'
doc_type: 'reference'
Window functions
Window functions let you perform calculations across a set of rows that are related to the current row.
Some of the calculations that you can do are similar to those that can be done with an aggregate function, but a window function doesn't cause rows to be grouped into a single output - the individual rows are still returned.
Standard window functions {#standard-window-functions}
ClickHouse supports the standard grammar for defining windows and window functions. The table below indicates whether a feature is currently supported. | {"source_file": "index.md"} | [
-0.019833393394947052,
-0.04204539954662323,
-0.03172173723578453,
0.01680314540863037,
-0.07121693342924118,
0.0359375961124897,
0.008811268955469131,
0.019743015989661217,
-0.0682593509554863,
0.018039003014564514,
-0.028926340863108635,
-0.002184935612604022,
0.010078703984618187,
-0.04... |
45036a0d-98be-4df3-9377-21245c232acb | | Feature | Supported? |
|--------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| ad hoc window specification (
count(*) over (partition by id order by time desc)
) | β
|
| expressions involving window functions, e.g.
(count(*) over ()) / 2)
| β
|
|
WINDOW
clause (
select ... from table window w as (partition by id)
) | β
|
|
ROWS
frame | β
|
|
RANGE
frame | β
(the default) |
|
INTERVAL
syntax for
DateTime
RANGE OFFSET
frame | β (specify the number of seconds instead (
RANGE
works with any numeric type).) |
|
GROUPS
frame | β |
| Calculating aggregate functions over a frame (
sum(value) over (order by time)
) | β
(All aggregate functions are supported) |
|
rank()
,
dense_rank()
,
row_number()
| β
Alias:
denseRank() | {"source_file": "index.md"} | [
-0.018640635535120964,
-0.03240098059177399,
-0.04182058572769165,
-0.02038496918976307,
-0.003144376678392291,
0.07564835250377655,
-0.0680965781211853,
0.043568555265665054,
-0.11991782486438751,
-0.0946975126862526,
0.058618735522031784,
-0.02805519476532936,
-0.025649510324001312,
-0.0... |
66ea1fb2-df0f-4272-8a30-c47a49b2a335 | |
rank()
,
dense_rank()
,
row_number()
| β
Alias:
denseRank()
|
|
percent_rank()
| β
Efficiently computes the relative standing of a value within a partition in a dataset. This function effectively replaces the more verbose and computationally intensive manual SQL calculation expressed as
ifNull((rank() OVER(PARTITION BY x ORDER BY y) - 1) / nullif(count(1) OVER(PARTITION BY x) - 1, 0), 0)
Alias:
percentRank()
|
|
cume_dist()
| β
Computes the cumulative distribution of a value within a group of values. Returns the percentage of rows with values less than or equal to the current row's value. |
|
lag/lead(value, offset)
| β
You can also use one of the following workarounds:
1)
any(value) over (.... rows between <offset> preceding and <offset> preceding)
, or
following
for
lead
2)
lagInFrame/leadInFrame
, which are analogous, but respect the window frame. To get behavior identical to
lag/lead
, use
rows between unbounded preceding and unbounded following
|
| ntile(buckets) | β
Specify window like, (partition by x order by y rows between unbounded preceding and unbounded following). | | {"source_file": "index.md"} | [
-0.021059412509202957,
-0.09590313583612442,
-0.047290608286857605,
-0.03952465578913689,
0.018873384222388268,
0.04178230091929436,
0.00925656221807003,
0.05823509022593498,
-0.025073204189538956,
0.01408616453409195,
0.056746166199445724,
-0.03818393498659134,
0.03601288050413132,
-0.020... |
2a2672bc-1c6a-4d4b-9998-3cb4a06ee296 | ClickHouse-specific window functions {#clickhouse-specific-window-functions}
There is also the following ClickHouse specific window function:
nonNegativeDerivative(metric_column, timestamp_column[, INTERVAL X UNITS]) {#nonnegativederivativemetric_column-timestamp_column-interval-x-units}
Finds non-negative derivative for given
metric_column
by
timestamp_column
.
INTERVAL
can be omitted, default is
INTERVAL 1 SECOND
.
The computed value is the following for each row:
-
0
for 1st row,
- ${\text{metric}
i - \text{metric}
{i-1} \over \text{timestamp}
i - \text{timestamp}
{i-1}} * \text{interval}$ for $i_{th}$ row.
Syntax {#syntax}
text
aggregate_function (column_name)
OVER ([[PARTITION BY grouping_column] [ORDER BY sorting_column]
[ROWS or RANGE expression_to_bound_rows_withing_the_group]] | [window_name])
FROM table_name
WINDOW window_name as ([[PARTITION BY grouping_column] [ORDER BY sorting_column]])
PARTITION BY
- defines how to break a resultset into groups.
ORDER BY
- defines how to order rows inside the group during calculation aggregate_function.
ROWS or RANGE
- defines bounds of a frame, aggregate_function is calculated within a frame.
WINDOW
- allows multiple expressions to use the same window definition.
text
PARTITION
βββββββββββββββββββ <-- UNBOUNDED PRECEDING (BEGINNING of the PARTITION)
β β
β β
β=================β <-- N PRECEDING <ββ
β N ROWS β β F
β Before CURRENT β β R
β~~~~~~~~~~~~~~~~~β <-- CURRENT ROW β A
β M ROWS β β M
β After CURRENT β β E
β=================β <-- M FOLLOWING <ββ
β β
β β
βββββββββββββββββββ <--- UNBOUNDED FOLLOWING (END of the PARTITION)
Functions {#functions}
These functions can be used only as a window function.
row_number()
- Number the current row within its partition starting from 1.
first_value(x)
- Return the first value evaluated within its ordered frame.
last_value(x)
- Return the last value evaluated within its ordered frame.
nth_value(x, offset)
- Return the first non-NULL value evaluated against the nth row (offset) in its ordered frame.
rank()
- Rank the current row within its partition with gaps.
dense_rank()
- Rank the current row within its partition without gaps.
lagInFrame(x)
- Return a value evaluated at the row that is at a specified physical offset row before the current row within the ordered frame.
leadInFrame(x)
- Return a value evaluated at the row that is offset rows after the current row within the ordered frame.
Examples {#examples}
Let's have a look at some examples of how window functions can be used.
Numbering rows {#numbering-rows}
``sql
CREATE TABLE salaries
(
team
String,
player
String,
salary
UInt32,
position` String
)
Engine = Memory; | {"source_file": "index.md"} | [
-0.01589454524219036,
0.013439852744340897,
0.027255503460764885,
0.005185549147427082,
-0.042001873254776,
-0.06605325639247894,
0.06536015123128891,
0.032550256699323654,
0.048844899982213974,
-0.008139591664075851,
0.03284969925880432,
-0.08116596192121506,
0.00975461583584547,
-0.01631... |
0c5265e8-7e7a-4298-9009-bcb4ac786c32 | Numbering rows {#numbering-rows}
``sql
CREATE TABLE salaries
(
team
String,
player
String,
salary
UInt32,
position` String
)
Engine = Memory;
INSERT INTO salaries FORMAT Values
('Port Elizabeth Barbarians', 'Gary Chen', 195000, 'F'),
('New Coreystad Archdukes', 'Charles Juarez', 190000, 'F'),
('Port Elizabeth Barbarians', 'Michael Stanley', 150000, 'D'),
('New Coreystad Archdukes', 'Scott Harrison', 150000, 'D'),
('Port Elizabeth Barbarians', 'Robert George', 195000, 'M');
```
sql
SELECT
player,
salary,
row_number() OVER (ORDER BY salary ASC) AS row
FROM salaries;
text
ββplayerβββββββββββ¬βsalaryββ¬βrowββ
β Michael Stanley β 150000 β 1 β
β Scott Harrison β 150000 β 2 β
β Charles Juarez β 190000 β 3 β
β Gary Chen β 195000 β 4 β
β Robert George β 195000 β 5 β
βββββββββββββββββββ΄βββββββββ΄ββββββ
sql
SELECT
player,
salary,
row_number() OVER (ORDER BY salary ASC) AS row,
rank() OVER (ORDER BY salary ASC) AS rank,
dense_rank() OVER (ORDER BY salary ASC) AS denseRank
FROM salaries;
text
ββplayerβββββββββββ¬βsalaryββ¬βrowββ¬βrankββ¬βdenseRankββ
β Michael Stanley β 150000 β 1 β 1 β 1 β
β Scott Harrison β 150000 β 2 β 1 β 1 β
β Charles Juarez β 190000 β 3 β 3 β 2 β
β Gary Chen β 195000 β 4 β 4 β 3 β
β Robert George β 195000 β 5 β 4 β 3 β
βββββββββββββββββββ΄βββββββββ΄ββββββ΄βββββββ΄ββββββββββββ
Aggregation functions {#aggregation-functions}
Compare each player's salary to the average for their team.
sql
SELECT
player,
salary,
team,
avg(salary) OVER (PARTITION BY team) AS teamAvg,
salary - teamAvg AS diff
FROM salaries;
text
ββplayerβββββββββββ¬βsalaryββ¬βteamβββββββββββββββββββββββ¬βteamAvgββ¬βββdiffββ
β Charles Juarez β 190000 β New Coreystad Archdukes β 170000 β 20000 β
β Scott Harrison β 150000 β New Coreystad Archdukes β 170000 β -20000 β
β Gary Chen β 195000 β Port Elizabeth Barbarians β 180000 β 15000 β
β Michael Stanley β 150000 β Port Elizabeth Barbarians β 180000 β -30000 β
β Robert George β 195000 β Port Elizabeth Barbarians β 180000 β 15000 β
βββββββββββββββββββ΄βββββββββ΄ββββββββββββββββββββββββββββ΄ββββββββββ΄βββββββββ
Compare each player's salary to the maximum for their team.
sql
SELECT
player,
salary,
team,
max(salary) OVER (PARTITION BY team) AS teamMax,
salary - teamMax AS diff
FROM salaries;
text
ββplayerβββββββββββ¬βsalaryββ¬βteamβββββββββββββββββββββββ¬βteamMaxββ¬βββdiffββ
β Charles Juarez β 190000 β New Coreystad Archdukes β 190000 β 0 β
β Scott Harrison β 150000 β New Coreystad Archdukes β 190000 β -40000 β
β Gary Chen β 195000 β Port Elizabeth Barbarians β 195000 β 0 β
β Michael Stanley β 150000 β Port Elizabeth Barbarians β 195000 β -45000 β
β Robert George β 195000 β Port Elizabeth Barbarians β 195000 β 0 β
βββββββββββββββββββ΄βββββββββ΄ββββββββββββββββββββββββββββ΄ββββββββββ΄βββββββββ | {"source_file": "index.md"} | [
0.024284616112709045,
-0.02268172614276409,
-0.010341164655983448,
-0.003822376485913992,
-0.08472256362438202,
0.09335401654243469,
0.01994890347123146,
0.05041401460766792,
-0.04972280561923981,
0.024111811071634293,
-0.01144439447671175,
0.010985473170876503,
0.07604818046092987,
-0.036... |
46e89902-3fcc-4f60-9d95-f2353be2f6ca | Partitioning by column {#partitioning-by-column}
``sql
CREATE TABLE wf_partition
(
part_key
UInt64,
value
UInt64,
order` UInt64
)
ENGINE = Memory;
INSERT INTO wf_partition FORMAT Values
(1,1,1), (1,2,2), (1,3,3), (2,0,0), (3,0,0);
SELECT
part_key,
value,
order,
groupArray(value) OVER (PARTITION BY part_key) AS frame_values
FROM wf_partition
ORDER BY
part_key ASC,
value ASC;
ββpart_keyββ¬βvalueββ¬βorderββ¬βframe_valuesββ
β 1 β 1 β 1 β [1,2,3] β <β
β 1 β 2 β 2 β [1,2,3] β β 1-st group
β 1 β 3 β 3 β [1,2,3] β <β
β 2 β 0 β 0 β [0] β <- 2-nd group
β 3 β 0 β 0 β [0] β <- 3-d group
ββββββββββββ΄ββββββββ΄ββββββββ΄βββββββββββββββ
```
Frame bounding {#frame-bounding}
``sql
CREATE TABLE wf_frame
(
part_key
UInt64,
value
UInt64,
order` UInt64
)
ENGINE = Memory;
INSERT INTO wf_frame FORMAT Values
(1,1,1), (1,2,2), (1,3,3), (1,4,4), (1,5,5);
```
```sql
-- Frame is bounded by bounds of a partition (BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
SELECT
part_key,
value,
order,
groupArray(value) OVER (
PARTITION BY part_key
ORDER BY order ASC
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS frame_values
FROM wf_frame
ORDER BY
part_key ASC,
value ASC;
ββpart_keyββ¬βvalueββ¬βorderββ¬βframe_valuesββ
β 1 β 1 β 1 β [1,2,3,4,5] β
β 1 β 2 β 2 β [1,2,3,4,5] β
β 1 β 3 β 3 β [1,2,3,4,5] β
β 1 β 4 β 4 β [1,2,3,4,5] β
β 1 β 5 β 5 β [1,2,3,4,5] β
ββββββββββββ΄ββββββββ΄ββββββββ΄βββββββββββββββ
```
sql
-- short form - no bound expression, no order by,
-- an equalent of `ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING`
SELECT
part_key,
value,
order,
groupArray(value) OVER (PARTITION BY part_key) AS frame_values_short,
groupArray(value) OVER (PARTITION BY part_key
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS frame_values
FROM wf_frame
ORDER BY
part_key ASC,
value ASC;
ββpart_keyββ¬βvalueββ¬βorderββ¬βframe_values_shortββ¬βframe_valuesββ
β 1 β 1 β 1 β [1,2,3,4,5] β [1,2,3,4,5] β
β 1 β 2 β 2 β [1,2,3,4,5] β [1,2,3,4,5] β
β 1 β 3 β 3 β [1,2,3,4,5] β [1,2,3,4,5] β
β 1 β 4 β 4 β [1,2,3,4,5] β [1,2,3,4,5] β
β 1 β 5 β 5 β [1,2,3,4,5] β [1,2,3,4,5] β
ββββββββββββ΄ββββββββ΄ββββββββ΄βββββββββββββββββββββ΄βββββββββββββββ
```sql
-- frame is bounded by the beginning of a partition and the current row
SELECT
part_key,
value,
order,
groupArray(value) OVER (
PARTITION BY part_key
ORDER BY order ASC
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS frame_values
FROM wf_frame
ORDER BY
part_key ASC,
value ASC; | {"source_file": "index.md"} | [
0.04721938073635101,
-0.053794652223587036,
-0.05320371687412262,
0.021117888391017914,
-0.014317587949335575,
-0.012895707972347736,
0.08487959951162338,
0.01755855605006218,
-0.040819574147462845,
-0.0354791097342968,
-0.0415552593767643,
0.04350346699357033,
-0.05592409521341324,
-0.022... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.