Other Functions
hostName
Returns the name of the host on which this function was executed. If the function executes on a remote server (distributed processing), the remote server name is returned. If the function executes in the context of a distributed table, it generates a normal column with values relevant to each shard. Otherwise it produces a constant value.
Syntax
Returned value
- Host name. String.
getMacro
Returns a named value from the macros section of the server configuration.
Syntax
Arguments
name
— Macro name to retrieve from the<macros>
section. String.
Returned value
- Value of the specified macro. String.
Example
Example <macros>
section in the server configuration file:
Query:
Result:
The same value can be retrieved as follows:
fqdn
Returns the fully qualified domain name of the ClickHouse server.
Syntax
Aliases: fullHostName
, FQDN
.
Returned value
- String with the fully qualified domain name. String.
Example
Result:
basename
Extracts the tail of a string following its last slash or backslash. This function if often used to extract the filename from a path.
Arguments
expr
— A value of type String. Backslashes must be escaped.
Returned Value
A string that contains:
- The tail of the input string after its last slash or backslash. If the input string ends with a slash or backslash (e.g.
/
orc:\
), the function returns an empty string. - The original string if there are no slashes or backslashes.
Example
Query:
Result:
Query:
Result:
Query:
Result:
visibleWidth
Calculates the approximate width when outputting values to the console in text format (tab-separated). This function is used by the system to implement Pretty formats.
NULL
is represented as a string corresponding to NULL
in Pretty
formats.
Syntax
Example
Query:
Result:
toTypeName
Returns the type name of the passed argument.
If NULL
is passed, the function returns type Nullable(Nothing)
, which corresponds to ClickHouse's internal NULL
representation.
Syntax
Arguments
value
— A value of arbitrary type.
Returned value
- The data type name of the input value. String.
Example
Query:
Result:
blockSize
In ClickHouse, queries are processed in blocks (chunks). This function returns the size (row count) of the block the function is called on.
Syntax
Example
Query:
Result:
byteSize
Returns an estimation of uncompressed byte size of its arguments in memory.
Syntax
Arguments
argument
— Value.
Returned value
- Estimation of byte size of the arguments in memory. UInt64.
Examples
For String arguments, the function returns the string length + 9 (terminating zero + length).
Query:
Result:
Query:
Result:
If the function has multiple arguments, the function accumulates their byte sizes.
Query:
Result:
materialize
Turns a constant into a full column containing a single value. Full columns and constants are represented differently in memory. Functions usually execute different code for normal and constant arguments, although the result should typically be the same. This function can be used to debug this behavior.
Syntax
Parameters
x
— A constant. Constant.
Returned value
- A column containing a single value
x
.
Example
In the example below the countMatches
function expects a constant second argument.
This behaviour can be debugged by using the materialize
function to turn a constant into a full column,
verifying that the function throws an error for a non-constant argument.
Query:
Result:
ignore
Accepts arbitrary arguments and unconditionally returns 0
.
The argument is still evaluated internally, making it useful for eg. benchmarking.
Syntax
Arguments
- Accepts arbitrarily many arguments of arbitrary type, including
NULL
.
Returned value
- Returns
0
.
Example
Query:
Result:
sleep
Used to introduce a delay or pause in the execution of a query. It is primarily used for testing and debugging purposes.
Syntax
Arguments
seconds
: UInt* or Float The number of seconds to pause the query execution to a maximum of 3 seconds. It can be a floating-point value to specify fractional seconds.
Returned value
This function does not return any value.
Example
This function does not return any value. However, if you run the function with clickhouse client
you will see something similar to:
This query will pause for 2 seconds before completing. During this time, no results will be returned, and the query will appear to be hanging or unresponsive.
Implementation details
The sleep()
function is generally not used in production environments, as it can negatively impact query performance and system responsiveness. However, it can be useful in the following scenarios:
- Testing: When testing or benchmarking ClickHouse, you may want to simulate delays or introduce pauses to observe how the system behaves under certain conditions.
- Debugging: If you need to examine the state of the system or the execution of a query at a specific point in time, you can use
sleep()
to introduce a pause, allowing you to inspect or collect relevant information. - Simulation: In some cases, you may want to simulate real-world scenarios where delays or pauses occur, such as network latency or external system dependencies.
It's important to use the sleep()
function judiciously and only when necessary, as it can potentially impact the overall performance and responsiveness of your ClickHouse system.
sleepEachRow
Pauses the execution of a query for a specified number of seconds for each row in the result set.
Syntax
Arguments
seconds
: UInt* or Float* The number of seconds to pause the query execution for each row in the result set to a maximum of 3 seconds. It can be a floating-point value to specify fractional seconds.
Returned value
This function returns the same input values as it receives, without modifying them.
Example
But the output will be delayed, with a 0.5-second pause between each row.
The sleepEachRow()
function is primarily used for testing and debugging purposes, similar to the sleep()
function. It allows you to simulate delays or introduce pauses in the processing of each row, which can be useful in scenarios such as:
- Testing: When testing or benchmarking ClickHouse's performance under specific conditions, you can use
sleepEachRow()
to simulate delays or introduce pauses for each row processed. - Debugging: If you need to examine the state of the system or the execution of a query for each row processed, you can use
sleepEachRow()
to introduce pauses, allowing you to inspect or collect relevant information. - Simulation: In some cases, you may want to simulate real-world scenarios where delays or pauses occur for each row processed, such as when dealing with external systems or network latencies.
Like the sleep()
function, it's important to use sleepEachRow()
judiciously and only when necessary, as it can significantly impact the overall performance and responsiveness of your ClickHouse system, especially when dealing with large result sets.
currentDatabase
Returns the name of the current database.
Useful in table engine parameters of CREATE TABLE
queries where you need to specify the database.
Syntax
Returned value
- Returns the current database name. String.
Example
Query:
Result:
currentUser
Returns the name of the current user. In case of a distributed query, the name of the user who initiated the query is returned.
Syntax
Aliases: user()
, USER()
, current_user()
. Aliases are case insensitive.
Returned values
- The name of the current user. String.
- In distributed queries, the login of the user who initiated the query. String.
Example
Result:
currentSchemas
Returns a single-element array with the name of the current database schema.
Syntax
Alias: current_schemas
.
Arguments
bool
: A boolean value. Bool.
The boolean argument is ignored. It only exists for the sake of compatibility with the implementation of this function in PostgreSQL.
Returned values
- Returns a single-element array with the name of the current database
Example
Result:
isConstant
Returns whether the argument is a constant expression.
A constant expression is an expression whose result is known during query analysis, i.e. before execution. For example, expressions over literals are constant expressions.
This function is mostly intended for development, debugging and demonstration.
Syntax
Arguments
x
— Expression to check.
Returned values
Examples
Query:
Result:
Query:
Result:
Query:
Result:
hasColumnInTable
Given the database name, the table name, and the column name as constant strings, returns 1 if the given column exists, otherwise 0.
Syntax
Parameters
database
: name of the database. String literaltable
: name of the table. String literalcolumn
: name of the column. String literalhostname
: remote server name to perform the check on. String literalusername
: username for remote server. String literalpassword
: password for remote server. String literal
Returned value
1
if the given column exists.0
, otherwise.
Implementation details
For elements in a nested data structure, the function checks for the existence of a column. For the nested data structure itself, the function returns 0.
Example
Query:
hasThreadFuzzer
Returns whether Thread Fuzzer is effective. It can be used in tests to prevent runs from being too long.
Syntax
bar
Builds a bar chart.
bar(x, min, max, width)
draws a band with width proportional to (x - min)
and equal to width
characters when x = max
.
Arguments
x
— Size to display.min, max
— Integer constants. The value must fit inInt64
.width
— Constant, positive integer, can be fractional.
The band is drawn with accuracy to one eighth of a symbol.
Example:
transform
Transforms a value according to the explicitly defined mapping of some elements to other ones. There are two variations of this function:
transform(x, array_from, array_to, default)
x
– What to transform.
array_from
– Constant array of values to convert.
array_to
– Constant array of values to convert the values in 'from’ to.
default
– Which value to use if 'x’ is not equal to any of the values in 'from’.
array_from
and array_to
must have equally many elements.
Signature:
For x
equal to one of the elements in array_from
, the function returns the corresponding element in array_to
, i.e. the one at the same array index. Otherwise, it returns default
. If multiple matching elements exist array_from
, it returns the element corresponding to the first of them.
transform(T, Array(T), Array(U), U) -> U
T
and U
can be numeric, string, or Date or DateTime types.
The same letter (T or U) means that types must be mutually compatible and not necessarily equal.
For example, the first argument could have type Int64
, while the second argument could have type Array(UInt16)
.
Example:
transform(x, array_from, array_to)
Similar to the other variation but has no 'default’ argument. In case no match can be found, x
is returned.
Example:
formatReadableDecimalSize
Given a size (number of bytes), this function returns a readable, rounded size with suffix (KB, MB, etc.) as string.
The opposite operations of this function are parseReadableSize, parseReadableSizeOrZero, and parseReadableSizeOrNull.
Syntax
Example
Query:
Result:
formatReadableSize
Given a size (number of bytes), this function returns a readable, rounded size with suffix (KiB, MiB, etc.) as string.
The opposite operations of this function are parseReadableSize, parseReadableSizeOrZero, and parseReadableSizeOrNull.
Syntax
Alias: FORMAT_BYTES
.
This function accepts any numeric type as input, but internally it casts them to Float64. Results might be suboptimal with large values
Example
Query:
Result:
formatReadableQuantity
Given a number, this function returns a rounded number with suffix (thousand, million, billion, etc.) as string.
Syntax
This function accepts any numeric type as input, but internally it casts them to Float64. Results might be suboptimal with large values
Example
Query:
Result:
formatReadableTimeDelta
Given a time interval (delta) in seconds, this function returns a time delta with year/month/day/hour/minute/second/millisecond/microsecond/nanosecond as string.
Syntax
This function accepts any numeric type as input, but internally it casts them to Float64. Results might be suboptimal with large values
Arguments
column
— A column with a numeric time delta.maximum_unit
— Optional. Maximum unit to show.- Acceptable values:
nanoseconds
,microseconds
,milliseconds
,seconds
,minutes
,hours
,days
,months
,years
. - Default value:
years
.
- Acceptable values:
minimum_unit
— Optional. Minimum unit to show. All smaller units are truncated.- Acceptable values:
nanoseconds
,microseconds
,milliseconds
,seconds
,minutes
,hours
,days
,months
,years
. - If explicitly specified value is bigger than
maximum_unit
, an exception will be thrown. - Default value:
seconds
ifmaximum_unit
isseconds
or bigger,nanoseconds
otherwise.
- Acceptable values:
Example
parseReadableSize
Given a string containing a byte size and B
, KiB
, KB
, MiB
, MB
, etc. as a unit (i.e. ISO/IEC 80000-13 or decimal byte unit), this function returns the corresponding number of bytes.
If the function is unable to parse the input value, it throws an exception.
The inverse operations of this function are formatReadableSize and formatReadableDecimalSize.
Syntax
Arguments
x
: Readable size with ISO/IEC 80000-13 or decimal byte unit (String).
Returned value
- Number of bytes, rounded up to the nearest integer (UInt64).
Example
parseReadableSizeOrNull
Given a string containing a byte size and B
, KiB
, KB
, MiB
, MB
, etc. as a unit (i.e. ISO/IEC 80000-13 or decimal byte unit), this function returns the corresponding number of bytes.
If the function is unable to parse the input value, it returns NULL
.
The inverse operations of this function are formatReadableSize and formatReadableDecimalSize.
Syntax
Arguments
x
: Readable size with ISO/IEC 80000-13 or decimal byte unit (String).
Returned value
- Number of bytes, rounded up to the nearest integer, or NULL if unable to parse the input (Nullable(UInt64)).
Example
parseReadableSizeOrZero
Given a string containing a byte size and B
, KiB
, KB
, MiB
, MB
, etc. as a unit (i.e. ISO/IEC 80000-13 or decimal byte unit), this function returns the corresponding number of bytes. If the function is unable to parse the input value, it returns 0
.
The inverse operations of this function are formatReadableSize and formatReadableDecimalSize.
Syntax
Arguments
x
: Readable size with ISO/IEC 80000-13 or decimal byte unit (String).
Returned value
- Number of bytes, rounded up to the nearest integer, or 0 if unable to parse the input (UInt64).
Example
parseTimeDelta
Parse a sequence of numbers followed by something resembling a time unit.
Syntax
Arguments
timestr
— A sequence of numbers followed by something resembling a time unit.
Returned value
- A floating-point number with the number of seconds.
Example
least
Returns the smallest arguments of one or more input arguments. NULL
arguments are ignored.
Syntax
Version 24.12 introduced a backwards-incompatible change such that NULL
values are ignored, while previously it returned NULL
if one of the arguments was NULL
. To retain the previous behavior, set setting least_greatest_legacy_null_behavior
(default: false
) to true
.
greatest
Returns the largest arguments of one or more input arguments. NULL
arguments are ignored.
Syntax
Version 24.12 introduced a backwards-incompatible change such that NULL
values are ignored, while previously it returned NULL
if one of the arguments was NULL
. To retain the previous behavior, set setting least_greatest_legacy_null_behavior
(default: false
) to true
.
uptime
Returns the server’s uptime in seconds. If executed in the context of a distributed table, this function generates a normal column with values relevant to each shard. Otherwise it produces a constant value.
Syntax
Returned value
- Time value of seconds. UInt32.
Example
Query:
Result:
version
Returns the current version of ClickHouse as a string in the form of:
- Major version
- Minor version
- Patch version
- Number of commits since the previous stable release.
If executed in the context of a distributed table, this function generates a normal column with values relevant to each shard. Otherwise, it produces a constant value.
Syntax
Arguments
None.
Returned value
- Current version of ClickHouse. String.
Implementation details
None.
Example
Query:
Result:
buildId
Returns the build ID generated by a compiler for the running ClickHouse server binary. If executed in the context of a distributed table, this function generates a normal column with values relevant to each shard. Otherwise it produces a constant value.
Syntax
blockNumber
Returns a monotonically increasing sequence number of the block containing the row. The returned block number is updated on a best-effort basis, i.e. it may not be fully accurate.
Syntax
Returned value
- Sequence number of the data block where the row is located. UInt64.
Example
Query:
Result:
rowNumberInBlock
Returns for each block processed by rowNumberInBlock
the number of the current row.
The returned number starts for each block at 0.
Syntax
Returned value
- Ordinal number of the row in the data block starting from 0. UInt64.
Example
Query:
Result:
rowNumberInAllBlocks
Returns a unique row number for each row processed by rowNumberInAllBlocks
. The returned numbers start at 0.
Syntax
Returned value
- Ordinal number of the row in the data block starting from 0. UInt64.
Example
Query:
Result:
neighbor
The window function that provides access to a row at a specified offset before or after the current row of a given column.
Syntax
The result of the function depends on the affected data blocks and the order of data in the block.
Only returns neighbor inside the currently processed data block. Because of this error-prone behavior the function is DEPRECATED, please use proper window functions instead.
The order of rows during calculation of neighbor()
can differ from the order of rows returned to the user.
To prevent that you can create a subquery with ORDER BY and call the function from outside the subquery.
Arguments
column
— A column name or scalar expression.offset
— The number of rows to look before or ahead of the current row incolumn
. Int64.default_value
— Optional. The returned value if offset is beyond the block boundaries. Type of data blocks affected.
Returned values
- Value of
column
withoffset
distance from current row, ifoffset
is not outside the block boundaries. - The default value of
column
ordefault_value
(if given), ifoffset
is outside the block boundaries.
The return type will be that of the data blocks affected or the default value type.
Example
Query:
Result:
Query:
Result:
This function can be used to compute year-over-year metric value:
Query:
Result:
runningDifference
Calculates the difference between two consecutive row values in the data block. Returns 0 for the first row, and for subsequent rows the difference to the previous row.
Only returns differences inside the currently processed data block. Because of this error-prone behavior the function is DEPRECATED, please use proper window functions instead.
The result of the function depends on the affected data blocks and the order of data in the block.
The order of rows during calculation of runningDifference()
can differ from the order of rows returned to the user.
To prevent that you can create a subquery with ORDER BY and call the function from outside the subquery.
Syntax
Example
Query:
Result:
Please note that the block size affects the result. The internal state of runningDifference
state is reset for each new block.
Query:
Result:
Query:
Result:
runningDifferenceStartingWithFirstValue
This function is DEPRECATED (see the note for runningDifference
).
Same as runningDifference, but returns the value of the first row as the value on the first row.
runningConcurrency
Calculates the number of concurrent events. Each event has a start time and an end time. The start time is included in the event, while the end time is excluded. Columns with a start time and an end time must be of the same data type. The function calculates the total number of active (concurrent) events for each event start time.
Events must be ordered by the start time in ascending order. If this requirement is violated the function raises an exception. Every data block is processed separately. If events from different data blocks overlap then they can not be processed correctly.
Syntax
Arguments
start
— A column with the start time of events. Date, DateTime, or DateTime64.end
— A column with the end time of events. Date, DateTime, or DateTime64.
Returned values
- The number of concurrent events at each event start time. UInt32
Example
Consider the table:
Query:
Result:
MACNumToString
Interprets a UInt64 number as a MAC address in big endian format. Returns the corresponding MAC address in format AA:BB:CC:DD:EE:FF (colon-separated numbers in hexadecimal form) as string.
Syntax
MACStringToNum
The inverse function of MACNumToString. If the MAC address has an invalid format, it returns 0.
Syntax
MACStringToOUI
Given a MAC address in format AA:BB:CC:DD:EE:FF (colon-separated numbers in hexadecimal form), returns the first three octets as a UInt64 number. If the MAC address has an invalid format, it returns 0.
Syntax
getSizeOfEnumType
Returns the number of fields in Enum.
An exception is thrown if the type is not Enum
.
Syntax
Arguments:
value
— Value of typeEnum
.
Returned values
- The number of fields with
Enum
input values.
Example
blockSerializedSize
Returns the size on disk without considering compression.
Arguments
value
— Any value.
Returned values
- The number of bytes that will be written to disk for block of values without compression.
Example
Query:
Result:
toColumnTypeName
Returns the internal name of the data type that represents the value.
Syntax
Arguments:
value
— Any type of value.
Returned values
- The internal data type name used to represent
value
.
Example
Difference between toTypeName
and toColumnTypeName
:
Result:
Query:
Result:
The example shows that the DateTime
data type is internally stored as Const(UInt32)
.
dumpColumnStructure
Outputs a detailed description of data structures in RAM
Arguments:
value
— Any type of value.
Returned values
- A description of the column structure used for representing
value
.
Example
defaultValueOfArgumentType
Returns the default value for the given data type.
Does not include default values for custom columns set by the user.
Syntax
Arguments:
expression
— Arbitrary type of value or an expression that results in a value of an arbitrary type.
Returned values
0
for numbers.- Empty string for strings.
ᴺᵁᴸᴸ
for Nullable.
Example
Query:
Result:
Query:
Result:
defaultValueOfTypeName
Returns the default value for the given type name.
Does not include default values for custom columns set by the user.
Arguments:
type
— A string representing a type name.
Returned values
0
for numbers.- Empty string for strings.
ᴺᵁᴸᴸ
for Nullable.
Example
Query:
Result:
Query:
Result:
indexHint
This function is intended for debugging and introspection. It ignores its argument and always returns 1. The arguments are not evaluated.
But during index analysis, the argument of this function is assumed to be not wrapped in indexHint
. This allows to select data in index ranges by the corresponding condition but without further filtering by this condition. The index in ClickHouse is sparse and using indexHint
will yield more data than specifying the same condition directly.
Syntax
Returned value
1
. Uint8.
Example
Here is the example of test data from the table ontime.
Table:
The table has indexes on the fields (FlightDate, (Year, FlightDate))
.
Create a query which does not use the index:
ClickHouse processed the entire table (Processed 4.28 million rows
).
Result:
To apply the index, select a specific date:
ClickHouse now uses the index to process a significantly smaller number of rows (Processed 32.74 thousand rows
).
Result:
Now wrap the expression k = '2017-09-15'
in function indexHint
:
Query:
ClickHouse used the index the same way as previously (Processed 32.74 thousand rows
).
The expression k = '2017-09-15'
was not used when generating the result.
In example, the indexHint
function allows to see adjacent dates.
Result:
replicate
Creates an array with a single value.
This function is used for the internal implementation of arrayJoin.
Syntax
Arguments
x
— The value to fill the result array with.arr
— An array. Array.
Returned value
An array of the lame length as arr
filled with value x
. Array.
Example
Query:
Result:
revision
Returns the current ClickHouse server revision.
Syntax
Returned value
- The current ClickHouse server revision. UInt32.
Example
Query:
Result:
filesystemAvailable
Returns the amount of free space in the filesystem hosting the database persistence. The returned value is always smaller than total free space (filesystemUnreserved) because some space is reserved for the operating system.
Syntax
Returned value
- The amount of remaining space available in bytes. UInt64.
Example
Query:
Result:
filesystemUnreserved
Returns the total amount of the free space on the filesystem hosting the database persistence. (previously filesystemFree
). See also filesystemAvailable
.
Syntax
Returned value
- The amount of free space in bytes. UInt64.
Example
Query:
Result:
filesystemCapacity
Returns the capacity of the filesystem in bytes. Needs the path to the data directory to be configured.
Syntax
Returned value
- Capacity of the filesystem in bytes. UInt64.
Example
Query:
Result:
initializeAggregation
Calculates the result of an aggregate function based on a single value. This function can be used to initialize aggregate functions with combinator -State. You can create states of aggregate functions and insert them to columns of type AggregateFunction or use initialized aggregates as default values.
Syntax
Arguments
aggregate_function
— Name of the aggregation function to initialize. String.arg
— Arguments of aggregate function.
Returned value(s)
- Result of aggregation for every row passed to the function.
The return type is the same as the return type of function, that initializeAggregation
takes as first argument.
Example
Query:
Result:
Query:
Result:
Example with AggregatingMergeTree
table engine and AggregateFunction
column:
See Also
finalizeAggregation
Given a state of aggregate function, this function returns the result of aggregation (or finalized state when using a -State combinator).
Syntax
Arguments
state
— State of aggregation. AggregateFunction.
Returned value(s)
- Value/values that was aggregated.
The return type is equal to that of any types which were aggregated.
Examples
Query:
Result:
Query:
Result:
Note that NULL
values are ignored.
Query:
Result:
Combined example:
Query:
Result:
See Also
runningAccumulate
Accumulates the states of an aggregate function for each row of a data block.
The state is reset for each new block of data. Because of this error-prone behavior the function is DEPRECATED, please use proper window functions instead.
Syntax
Arguments
agg_state
— State of the aggregate function. AggregateFunction.grouping
— Grouping key. Optional. The state of the function is reset if thegrouping
value is changed. It can be any of the supported data types for which the equality operator is defined.
Returned value
- Each resulting row contains a result of the aggregate function, accumulated for all the input rows from 0 to the current position.
runningAccumulate
resets states for each new data block or when thegrouping
value changes.
Type depends on the aggregate function used.
Examples
Consider how you can use runningAccumulate
to find the cumulative sum of numbers without and with grouping.
Query:
Result:
The subquery generates sumState
for every number from 0
to 9
. sumState
returns the state of the sum function that contains the sum of a single number.
The whole query does the following:
- For the first row,
runningAccumulate
takessumState(0)
and returns0
. - For the second row, the function merges
sumState(0)
andsumState(1)
resulting insumState(0 + 1)
, and returns1
as a result. - For the third row, the function merges
sumState(0 + 1)
andsumState(2)
resulting insumState(0 + 1 + 2)
, and returns3
as a result. - The actions are repeated until the block ends.
The following example shows the groupping
parameter usage:
Query:
Result:
As you can see, runningAccumulate
merges states for each group of rows separately.
joinGet
The function lets you extract data from the table the same way as from a dictionary. Gets the data from Join tables using the specified join key.
Only supports tables created with the ENGINE = Join(ANY, LEFT, <join_keys>)
statement.
Syntax
Arguments
join_storage_table_name
— an identifier indicating where the search is performed.value_column
— name of the column of the table that contains required data.join_keys
— list of keys.
The identifier is searched for in the default database (see setting default_database
in the config file). To override the default database, use USE db_name
or specify the database and the table through the separator db_name.db_table
as in the example.
Returned value
- Returns a list of values corresponded to the list of keys.
If a certain key does not exist in source table then 0
or null
will be returned based on join_use_nulls setting during table creation.
More info about join_use_nulls
in Join operation.
Example
Input table:
Query:
Result:
Setting join_use_nulls
can be used during table creation to change the behaviour of what gets returned if no key exists in the source table.
Query:
Result:
joinGetOrNull
Like joinGet but returns NULL
when the key is missing instead of returning the default value.
Syntax
Arguments
join_storage_table_name
— an identifier indicating where the search is performed.value_column
— name of the column of the table that contains required data.join_keys
— list of keys.
The identifier is searched for in the default database (see setting default_database
in the config file). To override the default database, use USE db_name
or specify the database and the table through the separator db_name.db_table
as in the example.
Returned value
- Returns a list of values corresponded to the list of keys.
If a certain key does not exist in source table then NULL
is returned for that key.
Example
Input table:
Query:
Result:
catboostEvaluate
This function is not available in ClickHouse Cloud.
Evaluate an external catboost model. CatBoost is an open-source gradient boosting library developed by Yandex for machine learning. Accepts a path to a catboost model and model arguments (features). Returns Float64.
Syntax
Example
Prerequisites
- Build the catboost evaluation library
Before evaluating catboost models, the libcatboostmodel.<so|dylib>
library must be made available. See CatBoost documentation how to compile it.
Next, specify the path to libcatboostmodel.<so|dylib>
in the clickhouse configuration:
For security and isolation reasons, the model evaluation does not run in the server process but in the clickhouse-library-bridge process.
At the first execution of catboostEvaluate()
, the server starts the library bridge process if it is not running already. Both processes
communicate using a HTTP interface. By default, port 9012
is used. A different port can be specified as follows - this is useful if port
9012
is already assigned to a different service.
- Train a catboost model using libcatboost
See Training and applying models for how to train catboost models from a training data set.
throwIf
Throw an exception if argument x
is true.
Syntax
Arguments
x
- the condition to check.message
- a constant string providing a custom error message. Optional.error_code
- A constant integer providing a custom error code. Optional.
To use the error_code
argument, configuration parameter allow_custom_error_code_in_throwif
must be enabled.
Example
Result:
identity
Returns its argument. Intended for debugging and testing. Allows to cancel using index, and get the query performance of a full scan. When the query is analyzed for possible use of an index, the analyzer ignores everything in identity
functions. Also disables constant folding.
Syntax
Example
Query:
Result:
getSetting
Returns the current value of a custom setting.
Syntax
Parameter
custom_setting
— The setting name. String.
Returned value
- The setting's current value.
Example
Result:
See Also
getSettingOrDefault
Returns the current value of a custom setting or returns the default value specified in the 2nd argument if the custom setting is not set in the current profile.
Syntax
Parameter
custom_setting
— The setting name. String.default_value
— Value to return if custom_setting is not set. Value may be of any data type or Null.
Returned value
- The setting's current value or default_value if setting is not set.
Example
Result:
See Also
isDecimalOverflow
Checks whether the Decimal value is outside its precision or outside the specified precision.
Syntax
Arguments
d
— value. Decimal.p
— precision. Optional. If omitted, the initial precision of the first argument is used. This parameter can be helpful to migrate data from/to another database or file. UInt8.
Returned values
1
— Decimal value has more digits then allowed by its precision,0
— Decimal value satisfies the specified precision.
Example
Query:
Result:
countDigits
Returns number of decimal digits need to represent a value.
Syntax
Arguments
Returned value
- Number of digits. UInt8.
For Decimal
values takes into account their scales: calculates result over underlying integer type which is (value * scale)
. For example: countDigits(42) = 2
, countDigits(42.000) = 5
, countDigits(0.04200) = 4
. I.e. you may check decimal overflow for Decimal64
with countDecimal(x) > 18
. It's a slow variant of isDecimalOverflow.
Example
Query:
Result:
errorCodeToName
- The textual name of an error code. LowCardinality(String).
Syntax
Result:
tcpPort
Returns native interface TCP port number listened by this server. If executed in the context of a distributed table, this function generates a normal column with values relevant to each shard. Otherwise it produces a constant value.
Syntax
Arguments
- None.
Returned value
- The TCP port number. UInt16.
Example
Query:
Result:
See Also
currentProfiles
Returns a list of the current settings profiles for the current user.
The command SET PROFILE could be used to change the current setting profile. If the command SET PROFILE
was not used the function returns the profiles specified at the current user's definition (see CREATE USER).
Syntax
Returned value
enabledProfiles
Returns settings profiles, assigned to the current user both explicitly and implicitly. Explicitly assigned profiles are the same as returned by the currentProfiles function. Implicitly assigned profiles include parent profiles of other assigned profiles, profiles assigned via granted roles, profiles assigned via their own settings, and the main default profile (see the default_profile
section in the main server configuration file).
Syntax
Returned value
defaultProfiles
Returns all the profiles specified at the current user's definition (see CREATE USER statement).
Syntax
Returned value
currentRoles
Returns the roles assigned to the current user. The roles can be changed by the SET ROLE statement. If no SET ROLE
statement was not, the function currentRoles
returns the same as defaultRoles
.
Syntax
Returned value
enabledRoles
Returns the names of the current roles and the roles, granted to some of the current roles.
Syntax
Returned value
defaultRoles
Returns the roles which are enabled by default for the current user when he logs in. Initially these are all roles granted to the current user (see GRANT), but that can be changed with the SET DEFAULT ROLE statement.
Syntax
Returned value
getServerPort
Returns the server port number. When the port is not used by the server, throws an exception.
Syntax
Arguments
-
port_name
— The name of the server port. String. Possible values:- 'tcp_port'
- 'tcp_port_secure'
- 'http_port'
- 'https_port'
- 'interserver_http_port'
- 'interserver_https_port'
- 'mysql_port'
- 'postgresql_port'
- 'grpc_port'
- 'prometheus.port'
Returned value
- The number of the server port. UInt16.
Example
Query:
Result:
queryID
Returns the ID of the current query. Other parameters of a query can be extracted from the system.query_log table via query_id
.
In contrast to initialQueryID function, queryID
can return different results on different shards (see the example).
Syntax
Returned value
- The ID of the current query. String
Example
Query:
Result:
initialQueryID
Returns the ID of the initial current query. Other parameters of a query can be extracted from the system.query_log table via initial_query_id
.
In contrast to queryID function, initialQueryID
returns the same results on different shards (see example).
Syntax
Returned value
- The ID of the initial current query. String
Example
Query:
Result:
initialQueryStartTime
Returns the start time of the initial current query.
initialQueryStartTime
returns the same results on different shards (see example).
Syntax
Returned value
- The start time of the initial current query. DateTime
Example
Query:
Result:
partitionID
Computes the partition ID.
This function is slow and should not be called for large amount of rows.
Syntax
Arguments
x
— Column for which to return the partition ID.y, ...
— Remaining N columns for which to return the partition ID (optional).
Returned Value
- Partition ID that the row would belong to. String.
Example
Query:
Result:
shardNum
Returns the index of a shard which processes a part of data in a distributed query. Indices are started from 1
.
If a query is not distributed then constant value 0
is returned.
Syntax
Returned value
- Shard index or constant
0
. UInt32.
Example
In the following example a configuration with two shards is used. The query is executed on the system.one table on every shard.
Query:
Result:
See Also
shardCount
Returns the total number of shards for a distributed query.
If a query is not distributed then constant value 0
is returned.
Syntax
Returned value
- Total number of shards or
0
. UInt32.
See Also
- shardNum() function example also contains
shardCount()
function call.
getOSKernelVersion
Returns a string with the current OS kernel version.
Syntax
Arguments
- None.
Returned value
- The current OS kernel version. String.
Example
Query:
Result:
zookeeperSessionUptime
Returns the uptime of the current ZooKeeper session in seconds.
Syntax
Arguments
- None.
Returned value
- Uptime of the current ZooKeeper session in seconds. UInt32.
Example
Query:
Result:
generateRandomStructure
Generates random table structure in a format column1_name column1_type, column2_name column2_type, ...
.
Syntax
Arguments
number_of_columns
— The desired number of columns in the result table structure. If set to 0 orNull
, the number of columns will be random from 1 to 128. Default value:Null
.seed
- Random seed to produce stable results. If seed is not specified or set toNull
, it is randomly generated.
All arguments must be constant.
Returned value
- Randomly generated table structure. String.
Examples
Query:
Result:
Query:
Result:
Query:
Result:
Note: the maximum nesting depth of complex types (Array, Tuple, Map, Nested) is limited to 16.
This function can be used together with generateRandom to generate completely random tables.
structureToCapnProtoSchema
Converts ClickHouse table structure to CapnProto schema.
Syntax
Arguments
structure
— Table structure in a formatcolumn1_name column1_type, column2_name column2_type, ...
.root_struct_name
— Name for root struct in CapnProto schema. Default value -Message
;
Returned value
- CapnProto schema. String.
Examples
Query:
Result:
Query:
Result:
Query:
Result:
structureToProtobufSchema
Converts ClickHouse table structure to Protobuf schema.
Syntax
Arguments
structure
— Table structure in a formatcolumn1_name column1_type, column2_name column2_type, ...
.root_message_name
— Name for root message in Protobuf schema. Default value -Message
;
Returned value
- Protobuf schema. String.
Examples
Query:
Result:
Query:
Result:
Query:
Result:
formatQuery
Returns a formatted, possibly multi-line, version of the given SQL query.
Throws an exception if the query is not well-formed. To return NULL
instead, function formatQueryOrNull()
may be used.
Syntax
Arguments
query
- The SQL query to be formatted. String
Returned value
- The formatted query. String.
Example
Result:
formatQuerySingleLine
Like formatQuery() but the returned formatted string contains no line breaks.
Throws an exception if the query is not well-formed. To return NULL
instead, function formatQuerySingleLineOrNull()
may be used.
Syntax
Arguments
query
- The SQL query to be formatted. String
Returned value
- The formatted query. String.
Example
Result:
variantElement
Extracts a column with specified type from a Variant
column.
Syntax
Arguments
variant
— Variant column. Variant.type_name
— The name of the variant type to extract. String.default_value
- The default value that will be used if variant doesn't have variant with specified type. Can be any type. Optional.
Returned value
- Subcolumn of a
Variant
column with specified type.
Example
variantType
Returns the variant type name for each row of Variant
column. If row contains NULL, it returns 'None'
for it.
Syntax
Arguments
variant
— Variant column. Variant.
Returned value
- Enum8 column with variant type name for each row.
Example
minSampleSizeConversion
Calculates minimum required sample size for an A/B test comparing conversions (proportions) in two samples.
Syntax
Uses the formula described in this article. Assumes equal sizes of treatment and control groups. Returns the sample size required for one group (i.e. the sample size required for the whole experiment is twice the returned value).
Arguments
baseline
— Baseline conversion. Float.mde
— Minimum detectable effect (MDE) as percentage points (e.g. for a baseline conversion 0.25 the MDE 0.03 means an expected change to 0.25 ± 0.03). Float.power
— Required statistical power of a test (1 - probability of Type II error). Float.alpha
— Required significance level of a test (probability of Type I error). Float.
Returned value
A named Tuple with 3 elements:
"minimum_sample_size"
— Required sample size. Float64."detect_range_lower"
— Lower bound of the range of values not detectable with the returned required sample size (i.e. all values less than or equal to"detect_range_lower"
are detectable with the providedalpha
andpower
). Calculated asbaseline - mde
. Float64."detect_range_upper"
— Upper bound of the range of values not detectable with the returned required sample size (i.e. all values greater than or equal to"detect_range_upper"
are detectable with the providedalpha
andpower
). Calculated asbaseline + mde
. Float64.
Example
The following query calculates the required sample size for an A/B test with baseline conversion of 25%, MDE of 3%, significance level of 5%, and the desired statistical power of 80%:
Result:
minSampleSizeContinuous
Calculates minimum required sample size for an A/B test comparing means of a continuous metric in two samples.
Syntax
Alias: minSampleSizeContinous
Uses the formula described in this article. Assumes equal sizes of treatment and control groups. Returns the required sample size for one group (i.e. the sample size required for the whole experiment is twice the returned value). Also assumes equal variance of the test metric in treatment and control groups.
Arguments
baseline
— Baseline value of a metric. Integer or Float.sigma
— Baseline standard deviation of a metric. Integer or Float.mde
— Minimum detectable effect (MDE) as percentage of the baseline value (e.g. for a baseline value 112.25 the MDE 0.03 means an expected change to 112.25 ± 112.25*0.03). Integer or Float.power
— Required statistical power of a test (1 - probability of Type II error). Integer or Float.alpha
— Required significance level of a test (probability of Type I error). Integer or Float.
Returned value
A named Tuple with 3 elements:
"minimum_sample_size"
— Required sample size. Float64."detect_range_lower"
— Lower bound of the range of values not detectable with the returned required sample size (i.e. all values less than or equal to"detect_range_lower"
are detectable with the providedalpha
andpower
). Calculated asbaseline * (1 - mde)
. Float64."detect_range_upper"
— Upper bound of the range of values not detectable with the returned required sample size (i.e. all values greater than or equal to"detect_range_upper"
are detectable with the providedalpha
andpower
). Calculated asbaseline * (1 + mde)
. Float64.
Example
The following query calculates the required sample size for an A/B test on a metric with baseline value of 112.25, standard deviation of 21.1, MDE of 3%, significance level of 5%, and the desired statistical power of 80%:
Result:
connectionId
Retrieves the connection ID of the client that submitted the current query and returns it as a UInt64 integer.
Syntax
Alias: connection_id
.
Parameters
None.
Returned value
The current connection ID. UInt64.
Implementation details
This function is most useful in debugging scenarios or for internal purposes within the MySQL handler. It was created for compatibility with MySQL's CONNECTION_ID
function It is not typically used in production queries.
Example
Query:
getClientHTTPHeader
Get the value of an HTTP header.
If there is no such header or the current request is not performed via the HTTP interface, the function returns an empty string.
Certain HTTP headers (e.g., Authentication
and X-ClickHouse-*
) are restricted.
The function requires the setting allow_get_client_http_header
to be enabled.
The setting is not enabled by default for security reasons, because some headers, such as Cookie
, could contain sensitive info.
HTTP headers are case sensitive for this function.
If the function is used in the context of a distributed query, it returns non-empty result only on the initiator node.
showCertificate
Shows information about the current server's Secure Sockets Layer (SSL) certificate if it has been configured. See Configuring SSL-TLS for more information on how to configure ClickHouse to use OpenSSL certificates to validate connections.
Syntax
Returned value
Example
Query:
Result:
lowCardinalityIndices
Returns the position of a value in the dictionary of a LowCardinality column. Positions start at 1. Since LowCardinality have per-part dictionaries, this function may return different positions for the same value in different parts.
Syntax
Arguments
col
— a low cardinality column. LowCardinality.
Returned value
- The position of the value in the dictionary of the current part. UInt64.
Example
Query:
Result:
lowCardinalityKeys
Returns the dictionary values of a LowCardinality column. If the block is smaller or larger than the dictionary size, the result will be truncated or extended with default values. Since LowCardinality have per-part dictionaries, this function may return different dictionary values in different parts.
Syntax
Arguments
col
— a low cardinality column. LowCardinality.
Returned value
- The dictionary keys. UInt64.
Example
Query:
Result:
displayName
Returns the value of display_name
from config or server Fully Qualified Domain Name (FQDN) if not set.
Syntax
Returned value
- Value of
display_name
from config or server FQDN if not set. String.
Example
The display_name
can be set in config.xml
. Taking for example a server with display_name
configured to 'production':
Query:
Result:
transactionID
Returns the ID of a transaction.
This function is part of an experimental feature set. Enable experimental transaction support by adding this setting to your configuration:
For more information see the page Transactional (ACID) support.
Syntax
Returned value
-
Returns a tuple consisting of
start_csn
,local_tid
andhost_id
. Tuple. -
start_csn
: Global sequential number, the newest commit timestamp that was seen when this transaction began. UInt64. -
local_tid
: Local sequential number that is unique for each transaction started by this host within a specific start_csn. UInt64. -
host_id
: UUID of the host that has started this transaction. UUID.
Example
Query:
Result:
transactionLatestSnapshot
Returns the newest snapshot (Commit Sequence Number) of a transaction that is available for reading.
This function is part of an experimental feature set. Enable experimental transaction support by adding this setting to your configuration:
For more information see the page Transactional (ACID) support.
Syntax
Returned value
- Returns the latest snapshot (CSN) of a transaction. UInt64
Example
Query:
Result:
transactionOldestSnapshot
Returns the oldest snapshot (Commit Sequence Number) that is visible for some running transaction.
This function is part of an experimental feature set. Enable experimental transaction support by adding this setting to your configuration:
For more information see the page Transactional (ACID) support.
Syntax
Returned value
- Returns the oldest snapshot (CSN) of a transaction. UInt64
Example
Query:
Result:
getSubcolumn
Takes a table expression or identifier and constant string with the name of the sub-column, and returns the requested sub-column extracted from the expression.
Syntax
Arguments
col_name
— Table expression or identifier. Expression, Identifier.subcol_name
— The name of the sub-column. String.
Returned value
- Returns the extracted sub-column.
Example
Query:
Result:
getTypeSerializationStreams
Enumerates stream paths of a data type.
This function is intended for use by developers.
Syntax
Arguments
col
— Column or string representation of a data-type from which the data type will be detected.
Returned value
Examples
Query:
Result:
Query:
Result:
globalVariable
Takes a constant string argument and returns the value of the global variable with that name. This function is intended for compatibility with MySQL and not needed or useful for normal operation of ClickHouse. Only few dummy global variables are defined.
Syntax
Arguments
name
— Global variable name. String.
Returned value
- Returns the value of variable
name
.
Example
Query:
Result:
getMaxTableNameLengthForDatabase
Returns the maximum table name length in a specified database.
Syntax
Arguments
database_name
— The name of the specified database. String.
Returned value
- Returns the length of the maximum table name.
Example
Query:
Result: