Functions for Searching in Strings
All functions in this section search case-sensitively by default. Case-insensitive search is usually provided by separate function variants.
Case-insensitive search follows the lowercase-uppercase rules of the English language. E.g. Uppercased i in the English language is
I whereas in the Turkish language it is İ - results for languages other than English may be unexpected.
Functions in this section also assume that the searched string (referred to in this section as haystack) and the search string (referred to in this section as needle) are single-byte encoded text. If this assumption is
violated, no exception is thrown and results are undefined. Search with UTF-8 encoded strings is usually provided by separate function
variants. Likewise, if a UTF-8 function variant is used and the input strings are not UTF-8 encoded text, no exception is thrown and the
results are undefined. Note that no automatic Unicode normalization is performed, however you can use the
normalizeUTF8*() functions for that.
General strings functions and functions for replacing in strings are described separately.
position
Returns the position (in bytes, starting at 1) of a substring needle in a string haystack.
Syntax
Alias:
position(needle IN haystack)
Arguments
haystack— String in which the search is performed. String or Enum.needle— Substring to be searched. String.start_pos– Position (1-based) inhaystackat which the search starts. UInt. Optional.
Returned value
- Starting position in bytes and counting from 1, if the substring was found. UInt64.
- 0, if the substring was not found. UInt64.
If substring needle is empty, these rules apply:
- if no
start_poswas specified: return1 - if
start_pos = 0: return1 - if
start_pos >= 1andstart_pos <= length(haystack) + 1: returnstart_pos - otherwise: return
0
The same rules also apply to functions locate, positionCaseInsensitive, positionUTF8 and positionCaseInsensitiveUTF8.
Examples
Query:
Result:
Example with start_pos argument:
Query:
Result:
Example for needle IN haystack syntax:
Query:
Result:
Examples with empty needle substring:
Query:
Result:
locate
Like position but with arguments haystack and locate switched.
The behavior of this function depends on the ClickHouse version:
- in versions < v24.3,
locatewas an alias of functionpositionand accepted arguments(haystack, needle[, start_pos]). - in versions >= 24.3,,
locateis an individual function (for better compatibility with MySQL) and accepts arguments(needle, haystack[, start_pos]). The previous behavior can be restored using setting function_locate_has_mysql_compatible_argument_order = false;
Syntax
positionCaseInsensitive
A case insensitive invariant of position.
Example
Query:
Result:
positionUTF8
Like position but assumes haystack and needle are UTF-8 encoded strings.
Examples
Function positionUTF8 correctly counts character ö (represented by two points) as a single Unicode codepoint:
Query:
Result:
positionCaseInsensitiveUTF8
Like positionUTF8 but searches case-insensitively.
multiSearchAllPositions
Like position but returns an array of positions (in bytes, starting at 1) for multiple needle substrings in a haystack string.
All multiSearch*() functions only support up to 28 needles.
Syntax
Arguments
haystack— String in which the search is performed. String.needle— Substrings to be searched. Array.
Returned value
- Array of the starting position in bytes and counting from 1, if the substring was found.
- 0, if the substring was not found.
Example
Query:
Result:
multiSearchAllPositionsCaseInsensitive
Like multiSearchAllPositions but ignores case.
Syntax
Parameters
haystack— String in which the search is performed. String.needle— Substrings to be searched. Array.
Returned value
- Array of the starting position in bytes and counting from 1 (if the substring was found).
- 0 if the substring was not found.
Example
Query:
Result:
multiSearchAllPositionsUTF8
Like multiSearchAllPositions but assumes haystack and the needle substrings are UTF-8 encoded strings.
Syntax
Parameters
haystack— UTF-8 encoded string in which the search is performed. String.needle— UTF-8 encoded substrings to be searched. Array.
Returned value
- Array of the starting position in bytes and counting from 1 (if the substring was found).
- 0 if the substring was not found.
Example
Given ClickHouse as a UTF-8 string, find the positions of C (\x43) and H (\x48).
Query:
Result:
multiSearchAllPositionsCaseInsensitiveUTF8
Like multiSearchAllPositionsUTF8 but ignores case.
Syntax
Parameters
haystack— UTF-8 encoded string in which the search is performed. String.needle— UTF-8 encoded substrings to be searched. Array.
Returned value
- Array of the starting position in bytes and counting from 1 (if the substring was found).
- 0 if the substring was not found.
Example
Given ClickHouse as a UTF-8 string, find the positions of c (\x63) and h (\x68).
Query:
Result:
multiSearchFirstPosition
Like position but returns the leftmost offset in a haystack string which matches any of multiple needle strings.
Functions multiSearchFirstPositionCaseInsensitive, multiSearchFirstPositionUTF8 and multiSearchFirstPositionCaseInsensitiveUTF8 provide case-insensitive and/or UTF-8 variants of this function.
Syntax
Parameters
haystack— String in which the search is performed. String.needle— Substrings to be searched. Array.
Returned value
- Leftmost offset in a
haystackstring which matches any of multipleneedlestrings. - 0, if there was no match.
Example
Query:
Result:
multiSearchFirstPositionCaseInsensitive
Like multiSearchFirstPosition but ignores case.
Syntax
Parameters
haystack— String in which the search is performed. String.needle— Array of substrings to be searched. Array.
Returned value
- Leftmost offset in a
haystackstring which matches any of multipleneedlestrings. - 0, if there was no match.
Example
Query:
Result:
multiSearchFirstPositionUTF8
Like multiSearchFirstPosition but assumes haystack and needle to be UTF-8 strings.
Syntax
Parameters
haystack— UTF-8 string in which the search is performed. String.needle— Array of UTF-8 substrings to be searched. Array.
Returned value
- Leftmost offset in a
haystackstring which matches any of multipleneedlestrings. - 0, if there was no match.
Example
Find the leftmost offset in UTF-8 string hello world which matches any of the given needles.
Query:
Result:
multiSearchFirstPositionCaseInsensitiveUTF8
Like multiSearchFirstPosition but assumes haystack and needle to be UTF-8 strings and ignores case.
Syntax
Parameters
haystack— UTF-8 string in which the search is performed. String.needle— Array of UTF-8 substrings to be searched. Array
Returned value
- Leftmost offset in a
haystackstring which matches any of multipleneedlestrings, ignoring case. - 0, if there was no match.
Example
Find the leftmost offset in UTF-8 string HELLO WORLD which matches any of the given needles.
Query:
Result:
multiSearchFirstIndex
Returns the index i (starting from 1) of the leftmost found needlei in the string haystack and 0 otherwise.
Functions multiSearchFirstIndexCaseInsensitive, multiSearchFirstIndexUTF8 and multiSearchFirstIndexCaseInsensitiveUTF8 provide case-insensitive and/or UTF-8 variants of this function.
Syntax
Parameters
haystack— String in which the search is performed. String.needle— Substrings to be searched. Array.
Returned value
- index (starting from 1) of the leftmost found needle. Otherwise 0, if there was no match. UInt8.
Example
Query:
Result:
multiSearchFirstIndexCaseInsensitive
Returns the index i (starting from 1) of the leftmost found needlei in the string haystack and 0 otherwise. Ignores case.
Syntax
Parameters
haystack— String in which the search is performed. String.needle— Substrings to be searched. Array.
Returned value
- index (starting from 1) of the leftmost found needle. Otherwise 0, if there was no match. UInt8.
Example
Query:
Result:
multiSearchFirstIndexUTF8
Returns the index i (starting from 1) of the leftmost found needlei in the string haystack and 0 otherwise. Assumes haystack and needle are UTF-8 encoded strings.
Syntax
Parameters
haystack— UTF-8 string in which the search is performed. String.needle— Array of UTF-8 substrings to be searched. Array
Returned value
- index (starting from 1) of the leftmost found needle, Otherwise 0, if there was no match. UInt8.
Example
Given Hello World as a UTF-8 string, find the first index of UTF-8 strings Hello and World.
Query:
Result:
multiSearchFirstIndexCaseInsensitiveUTF8
Returns the index i (starting from 1) of the leftmost found needlei in the string haystack and 0 otherwise. Assumes haystack and needle are UTF-8 encoded strings. Ignores case.
Syntax
Parameters
haystack— UTF-8 string in which the search is performed. String.needle— Array of UTF-8 substrings to be searched. Array.
Returned value
- index (starting from 1) of the leftmost found needle. Otherwise 0, if there was no match. UInt8.
Example
Given HELLO WORLD as a UTF-8 string, find the first index of UTF-8 strings hello and world.
Query:
Result:
multiSearchAny
Returns 1, if at least one string needlei matches the string haystack and 0 otherwise.
Functions multiSearchAnyCaseInsensitive, multiSearchAnyUTF8 and multiSearchAnyCaseInsensitiveUTF8 provide case-insensitive and/or UTF-8 variants of this function.
Syntax
Parameters
haystack— String in which the search is performed. String.needle— Substrings to be searched. Array.
Returned value
- 1, if there was at least one match.
- 0, if there was not at least one match.
Example
Query:
Result:
multiSearchAnyCaseInsensitive
Like multiSearchAny but ignores case.
Syntax
Parameters
haystack— String in which the search is performed. String.needle— Substrings to be searched. Array
Returned value
- 1, if there was at least one case-insensitive match.
- 0, if there was not at least one case-insensitive match.
Example
Query:
Result:
multiSearchAnyUTF8
Like multiSearchAny but assumes haystack and the needle substrings are UTF-8 encoded strings.
Syntax*
Parameters
haystack— UTF-8 string in which the search is performed. String.needle— UTF-8 substrings to be searched. Array.
Returned value
- 1, if there was at least one match.
- 0, if there was not at least one match.
Example
Given ClickHouse as a UTF-8 string, check if there are any C ('\x43') or H ('\x48') letters in the word.
Query:
Result:
multiSearchAnyCaseInsensitiveUTF8
Like multiSearchAnyUTF8 but ignores case.
Syntax*
Parameters
haystack— UTF-8 string in which the search is performed. String.needle— UTF-8 substrings to be searched. Array
Returned value
- 1, if there was at least one case-insensitive match.
- 0, if there was not at least one case-insensitive match.
Example
Given ClickHouse as a UTF-8 string, check if there is any letter h(\x68) in the word, ignoring case.
Query:
Result:
hasAnyTokens
Returns 1, if at least one token in the needle string or array matches the input string, and 0 otherwise. If input is a column, returns all rows that satisfy this condition.
Column input should have a text index defined for optimal performance.
If no text index is defined, the function performs a brute-force column scan which is orders of magnitude slower than an index lookup.
Prior to searching, the function tokenizes
- the
inputargument (always), and - the
needleargument (if given as a String) using the tokenizer specified for the text index. If the column has no text index defined, thesplitByNonAlphatokenizer is used instead. If theneedleargument is of type Array(String), each array element is treated as a token — no additional tokenization takes place.
Duplicate tokens are ignored. For example, ['ClickHouse', 'ClickHouse'] is treated the same as ['ClickHouse'].
Syntax
Parameters
input— The input column. String or FixedString.needles— Tokens to be searched. Supports at most 64 tokens. String) or Array(String).
Returned value
Returns 1, if there was at least one match. 0, otherwise.
Example
Query:
Result:
Specify needles to be searched for AS-IS (no tokenization) in an array:
Result:
Generate needles using the tokens function:
Result:
hasAllTokens
Like hasAnyTokens, but returns 1, if all tokens in the needle string or array match the input string, and 0 otherwise. If input is a column, returns all rows that satisfy this condition.
Column input should have a text index defined for optimal performance.
If no text index is defined, the function performs a brute-force column scan which is orders of magnitude slower than an index lookup.
Prior to searching, the function tokenizes
- the
inputargument (always), and - the
needleargument (if given as a String) using the tokenizer specified for the text index. If the column has no text index defined, thesplitByNonAlphatokenizer is used instead. If theneedleargument is of type Array(String), each array element is treated as a token — no additional tokenization takes place.
Duplicate tokens are ignored. For example, needles = ['ClickHouse', 'ClickHouse'] is treated the same as ['ClickHouse'].
Syntax
Parameters
input— The input column. String or FixedString.needles— Tokens to be searched. Supports at most 64 tokens. String) or Array(String).
Returned value
Returns 1, if all needles match. 0, otherwise.
Example
Query:
Result:
Specify needles to be searched for AS-IS (no tokenization) in an array:
Result:
Generate needles using the tokens function:
Result:
match
Returns whether string haystack matches the regular expression pattern in re2 regular expression syntax.
Matching is based on UTF-8, e.g. . matches the Unicode code point ¥ which is represented in UTF-8 using two bytes. The regular
expression must not contain null bytes. If the haystack or the pattern are not valid UTF-8, then the behavior is undefined.
Unlike re2's default behavior, . matches line breaks. To disable this, prepend the pattern with (?-s).
If you only want to search substrings in a string, you can use functions like or position instead - they work much faster than this function.
Syntax
Alias: haystack REGEXP pattern operator
multiMatchAny
Like match but returns 1 if at least one of the patterns match and 0 otherwise.
Functions in the multi[Fuzzy]Match*() family use the the (Vectorscan)[https://github.com/VectorCamp/vectorscan] library. As such, they are only enabled if ClickHouse is compiled with support for vectorscan.
To turn off all functions that use hyperscan, use setting SET allow_hyperscan = 0;.
Due to restrictions of vectorscan, the length of the haystack string must be less than 232 bytes.
Hyperscan is generally vulnerable to regular expression denial of service (ReDoS) attacks (e.g. see (here)[https://www.usenix.org/conference/usenixsecurity22/presentation/turonova], (here)[https://doi.org/10.1007/s10664-021-10033-1] and (here)[https://doi.org/10.1145/3236024.3236027]. Users are adviced to check the provided patterns carefully.
If you only want to search multiple substrings in a string, you can use function multiSearchAny instead - it works much faster than this function.
Syntax
multiMatchAnyIndex
Like multiMatchAny but returns any index that matches the haystack.
Syntax
multiMatchAllIndices
Like multiMatchAny but returns the array of all indices that match the haystack in any order.
Syntax
multiFuzzyMatchAny
Like multiMatchAny but returns 1 if any pattern matches the haystack within a constant edit distance. This function relies on the experimental feature of hyperscan library, and can be slow for some corner cases. The performance depends on the edit distance value and patterns used, but it's always more expensive compared to a non-fuzzy variants.
multiFuzzyMatch*() function family do not support UTF-8 regular expressions (it threats them as a sequence of bytes) due to restrictions of hyperscan.
Syntax
multiFuzzyMatchAnyIndex
Like multiFuzzyMatchAny but returns any index that matches the haystack within a constant edit distance.
Syntax
multiFuzzyMatchAllIndices
Like multiFuzzyMatchAny but returns the array of all indices in any order that match the haystack within a constant edit distance.
Syntax
extract
Returns the first match of a regular expression in a string.
If haystack does not match the pattern regex, an empty string is returned.
If the regular expression has capturing groups, the function matches the input string against the first capturing group.
Syntax
Arguments*
haystack— Input string. String.pattern— Regular expression with re2 regular expression syntax.
Returned value
- The first match of the regular expression in the haystack string. String.
Example
Query:
Result:
extractAll
Returns an array of all matches of a regular expression in a string. If haystack does not match the pattern regex, an empty string is returned.
The behavior with respect to sub-patterns is the same as in function extract.
Syntax
Arguments*
haystack— Input string. String.pattern— Regular expression with re2 regular expression syntax.
Returned value
Example
Query:
Result:
extractAllGroupsHorizontal
Matches all groups of the haystack string using the pattern regular expression. Returns an array of arrays, where the first array includes all fragments matching the first group, the second array - matching the second group, etc.
This function is slower than extractAllGroupsVertical.
Syntax
Arguments
haystack— Input string. String.pattern— Regular expression with re2 regular expression syntax. Must contain groups, each group enclosed in parentheses. Ifpatterncontains no groups, an exception is thrown. String.
Returned value
- Array of arrays of matches. Array.
If haystack does not match the pattern regex, an array of empty arrays is returned.
Example
Result:
extractGroups
Match all groups of given input string with a given regular expression, returns an array of arrays of matches.
Syntax
Arguments
haystack— Input string. String.pattern— Regular expression with re2 regular expression syntax. Must contain groups, each group enclosed in parentheses. Ifpatterncontains no groups, an exception is thrown. String.
Returned value
- Array of arrays of matches. Array.
Example
Result:
extractAllGroupsVertical
Matches all groups of the haystack string using the pattern regular expression. Returns an array of arrays, where each array includes matching fragments from every group. Fragments are grouped in order of appearance in the haystack.
Syntax
Arguments
haystack— Input string. String.pattern— Regular expression with re2 regular expression syntax. Must contain groups, each group enclosed in parentheses. Ifpatterncontains no groups, an exception is thrown. String.
Returned value
- Array of arrays of matches. Array.
If haystack does not match the pattern regex, an empty array is returned.
Example
Result:
like
Returns whether string haystack matches the LIKE expression pattern.
A LIKE expression can contain normal characters and the following metasymbols:
%indicates an arbitrary number of arbitrary characters (including zero characters)._indicates a single arbitrary character.\is for escaping literals%,_and\.
Matching is based on UTF-8, e.g. _ matches the Unicode code point ¥ which is represented in UTF-8 using two bytes.
If the haystack or the LIKE expression are not valid UTF-8, the behavior is undefined.
No automatic Unicode normalization is performed, you can use the normalizeUTF8*() functions for that.
To match against literal %, _ and \ (which are LIKE metacharacters), prepend them with a backslash: \%, \_ and \\.
The backslash loses its special meaning (i.e. is interpreted literally) if it prepends a character different than %, _ or \.
Note that ClickHouse requires backslashes in strings to be quoted as well, so you would actually need to write \\%, \\_ and \\\\.
For LIKE expressions of the form %needle%, the function is as fast as the position function.
All other LIKE expressions are internally converted to a regular expression and executed with a performance similar to function match.
Syntax
Alias: haystack LIKE pattern (operator)
notLike
Like like but negates the result.
Alias: haystack NOT LIKE pattern (operator)
ilike
Like like but searches case-insensitively.
Alias: haystack ILIKE pattern (operator)
notILike
Like ilike but negates the result.
Alias: haystack NOT ILIKE pattern (operator)
ngramDistance
Calculates the 4-gram distance between a haystack string and a needle string. For this, it counts the symmetric difference between two multisets of 4-grams and normalizes it by the sum of their cardinalities. Returns a Float32 between 0 and 1. The smaller the result is, the more similar the strings are to each other.
Functions ngramDistanceCaseInsensitive, ngramDistanceUTF8, ngramDistanceCaseInsensitiveUTF8 provide case-insensitive and/or UTF-8 variants of this function.
Syntax
Parameters
haystack: First comparison string. String literalneedle: Second comparison string. String literal
Returned value
- Value between 0 and 1 representing the similarity between the two strings. Float32
Implementation details
This function will throw an exception if constant needle or haystack arguments are more than 32Kb in size. If any non-constant haystack or needle arguments are more than 32Kb in size, then the distance is always 1.
Examples
The more similar two strings are to each other, the closer the result will be to 0 (identical).
Query:
Result:
The less similar two strings are to each, the larger the result will be. Query:
Result:
ngramDistanceCaseInsensitive
Provides a case-insensitive variant of ngramDistance.
Syntax
Parameters
haystack: First comparison string. String literalneedle: Second comparison string. String literal
Returned value
- Value between 0 and 1 representing the similarity between the two strings. Float32
Examples
With ngramDistance differences in case will affect the similarity value:
Query:
Result:
With ngramDistanceCaseInsensitive case is ignored so two identical strings differing only in case will now return a low similarity value:
Query:
Result:
ngramDistanceUTF8
Provides a UTF-8 variant of ngramDistance. Assumes that needle and haystack strings are UTF-8 encoded strings.
Syntax
Parameters
haystack: First UTF-8 encoded comparison string. String literalneedle: Second UTF-8 encoded comparison string. String literal
Returned value
- Value between 0 and 1 representing the similarity between the two strings. Float32
Example
Query:
Result:
ngramDistanceCaseInsensitiveUTF8
Provides a case-insensitive variant of ngramDistanceUTF8.
Syntax
Parameters
haystack: First UTF-8 encoded comparison string. String literalneedle: Second UTF-8 encoded comparison string. String literal
Returned value
- Value between 0 and 1 representing the similarity between the two strings. Float32
Example
Query:
Result:
ngramSearch
Like ngramDistance but calculates the non-symmetric difference between a needle string and a haystack string, i.e. the number of n-grams from the needle minus the common number of n-grams normalized by the number of needle n-grams. Returns a Float32 between 0 and 1. The bigger the result is, the more likely needle is in the haystack. This function is useful for fuzzy string search. Also see function soundex.
Functions ngramSearchCaseInsensitive, ngramSearchUTF8, ngramSearchCaseInsensitiveUTF8 provide case-insensitive and/or UTF-8 variants of this function.
Syntax
Parameters
haystack: First comparison string. String literalneedle: Second comparison string. String literal
Returned value
- Value between 0 and 1 representing the likelihood of the
needlebeing in thehaystack. Float32
Implementation details
The UTF-8 variants use the 3-gram distance. These are not perfectly fair n-gram distances. We use 2-byte hashes to hash n-grams and then calculate the (non-)symmetric difference between these hash tables – collisions may occur. With UTF-8 case-insensitive format we do not use fair tolower function – we zero the 5-th bit (starting from zero) of each codepoint byte and first bit of zeroth byte if bytes more than one – this works for Latin and mostly for all Cyrillic letters.
Example
Query:
Result:
ngramSearchCaseInsensitive
Provides a case-insensitive variant of ngramSearch.
Syntax
Parameters
haystack: First comparison string. String literalneedle: Second comparison string. String literal
Returned value
- Value between 0 and 1 representing the likelihood of the
needlebeing in thehaystack. Float32
The bigger the result is, the more likely needle is in the haystack.
Example
Query:
Result:
ngramSearchUTF8
Provides a UTF-8 variant of ngramSearch in which needle and haystack are assumed to be UTF-8 encoded strings.
Syntax
Parameters
haystack: First UTF-8 encoded comparison string. String literalneedle: Second UTF-8 encoded comparison string. String literal
Returned value
- Value between 0 and 1 representing the likelihood of the
needlebeing in thehaystack. Float32
The bigger the result is, the more likely needle is in the haystack.
Example
Query:
Result:
ngramSearchCaseInsensitiveUTF8
Provides a case-insensitive variant of ngramSearchUTF8 in which needle and haystack.
Syntax
Parameters
haystack: First UTF-8 encoded comparison string. String literalneedle: Second UTF-8 encoded comparison string. String literal
Returned value
- Value between 0 and 1 representing the likelihood of the
needlebeing in thehaystack. Float32
The bigger the result is, the more likely needle is in the haystack.
Example
Query:
Result:
countSubstrings
Returns how often a substring needle occurs in a string haystack.
Functions countSubstringsCaseInsensitive and countSubstringsCaseInsensitiveUTF8 provide case-insensitive and case-insensitive + UTF-8 variants of this function respectively.
Syntax
Arguments
haystack— String in which the search is performed. String or Enum.needle— Substring to be searched. String.start_pos– Position (1-based) inhaystackat which the search starts. UInt. Optional.
Returned value
- The number of occurrences. UInt64.
Examples
Result:
Example with start_pos argument:
Result:
countSubstringsCaseInsensitive
Returns how often a substring needle occurs in a string haystack. Ignores case.
Syntax
Arguments
haystack— String in which the search is performed. String or Enum.needle— Substring to be searched. String.start_pos– Position (1-based) inhaystackat which the search starts. UInt. Optional.
Returned value
- The number of occurrences. UInt64.
Examples
Query:
Result:
Example with start_pos argument:
Query:
Result:
countSubstringsCaseInsensitiveUTF8
Returns how often a substring needle occurs in a string haystack. Ignores case and assumes that haystack is a UTF8 string.
Syntax
Arguments
haystack— UTF-8 string in which the search is performed. String or Enum.needle— Substring to be searched. String.start_pos– Position (1-based) inhaystackat which the search starts. UInt. Optional.
Returned value
- The number of occurrences. UInt64.
Examples
Query:
Result:
Example with start_pos argument:
Query:
Result:
countMatches
Returns the number of regular expression matches for a pattern in a haystack.
The behavior of this function depends on the ClickHouse version:
- in versions < v25.6,
countMatcheswould stop counting at the first empty match even if a pattern accepts. - in versions >= 25.6,
countMatcheswould continue its execution when an empty match occurs. The legacy behavior can be restored using setting count_matches_stop_at_empty_match = true;
Syntax
Arguments
haystack— The string to search in. String.pattern— The regular expression with re2 regular expression syntax. String.
Returned value
- The number of matches. UInt64.
Examples
Result:
Result:
countMatchesCaseInsensitive
Returns the number of regular expression matches for a pattern in a haystack like countMatches but matching ignores the case.
Syntax
Arguments
haystack— The string to search in. String.pattern— The regular expression with re2 regular expression syntax. String.
Returned value
- The number of matches. UInt64.
Examples
Query:
Result:
regexpExtract
Extracts the first string in haystack that matches the regexp pattern and corresponds to the regex group index.
Syntax
Alias: REGEXP_EXTRACT(haystack, pattern[, index]).
Arguments
haystack— String, in which regexp pattern will to be matched. String.pattern— String, regexp expression, must be constant. String.index– An integer number greater or equal 0 with default 1. It represents which regex group to extract. UInt or Int. Optional.
Returned value
pattern may contain multiple regexp groups, index indicates which regex group to extract. An index of 0 means matching the entire regular expression. String.
Examples
Result:
hasSubsequence
Returns 1 if needle is a subsequence of haystack, or 0 otherwise.
A subsequence of a string is a sequence that can be derived from the given string by deleting zero or more elements without changing the order of the remaining elements.
Syntax
Arguments
haystack— String in which the search is performed. String.needle— Subsequence to be searched. String.
Returned value
- 1, if needle is a subsequence of haystack, 0 otherwise. UInt8.
Examples
Query:
Result:
hasSubsequenceCaseInsensitive
Like hasSubsequence but searches case-insensitively.
Syntax
Arguments
haystack— String in which the search is performed. String.needle— Subsequence to be searched. String.
Returned value
- 1, if needle is a subsequence of haystack, 0 otherwise UInt8.
Examples
Query:
Result:
hasSubsequenceUTF8
Like hasSubsequence but assumes haystack and needle are UTF-8 encoded strings.
Syntax
Arguments
haystack— String in which the search is performed. UTF-8 encoded String.needle— Subsequence to be searched. UTF-8 encoded String.
Returned value
- 1, if needle is a subsequence of haystack, 0, otherwise. UInt8.
Query:
Examples
Result:
hasSubsequenceCaseInsensitiveUTF8
Like hasSubsequenceUTF8 but searches case-insensitively.
Syntax
Arguments
haystack— String in which the search is performed. UTF-8 encoded String.needle— Subsequence to be searched. UTF-8 encoded String.
Returned value
- 1, if needle is a subsequence of haystack, 0 otherwise. UInt8.
Examples
Query:
Result:
hasToken
Returns 1 if a given token is present in a haystack, or 0 otherwise.
Syntax
Parameters
haystack: String in which the search is performed. String or Enum.token: Maximal length substring between two non alphanumeric ASCII characters (or boundaries of haystack).
Returned value
- 1, if the token is present in the haystack, 0 otherwise. UInt8.
Implementation details
Token must be a constant string. Supported by tokenbf_v1 index specialization.
Example
Query:
hasTokenOrNull
Returns 1 if a given token is present, 0 if not present, and null if the token is ill-formed.
Syntax
Parameters
haystack: String in which the search is performed. String or Enum.token: Maximal length substring between two non alphanumeric ASCII characters (or boundaries of haystack).
Returned value
- 1, if the token is present in the haystack, 0 if it is not present, and null if the token is ill formed.
Implementation details
Token must be a constant string. Supported by tokenbf_v1 index specialization.
Example
Where hasToken would throw an error for an ill-formed token, hasTokenOrNull returns null for an ill-formed token.
Query:
hasTokenCaseInsensitive
Returns 1 if a given token is present in a haystack, 0 otherwise. Ignores case.
Syntax
Parameters
haystack: String in which the search is performed. String or Enum.token: Maximal length substring between two non alphanumeric ASCII characters (or boundaries of haystack).
Returned value
- 1, if the token is present in the haystack, 0 otherwise. UInt8.
Implementation details
Token must be a constant string. Supported by tokenbf_v1 index specialization.
Example
Query:
hasTokenCaseInsensitiveOrNull
Returns 1 if a given token is present in a haystack, 0 otherwise. Ignores case and returns null if the token is ill-formed.
Syntax
Parameters
haystack: String in which the search is performed. String or Enum.token: Maximal length substring between two non alphanumeric ASCII characters (or boundaries of haystack).
Returned value
- 1, if the token is present in the haystack, 0 if the token is not present, otherwise
nullif the token is ill-formed. UInt8.
Implementation details
Token must be a constant string. Supported by tokenbf_v1 index specialization.
Example
Where hasTokenCaseInsensitive would throw an error for an ill-formed token, hasTokenCaseInsensitiveOrNull returns null for an ill-formed token.
Query:
countMatches
Introduced in: v21.1
Returns number of matches of a regular expression in a string.
The behavior of this function depends on the ClickHouse version:
- in versions < v25.6, the function stops counting at the first empty match even if a pattern accepts.
- in versions >= 25.6, the function continues execution when an empty match occurs. The legacy behavior can be restored using setting
count_matches_stop_at_empty_match = true;
Syntax
Arguments
Returned value
Returns the number of matches found. UInt64
Examples
Count digit sequences
countMatchesCaseInsensitive
Introduced in: v21.1
Like countMatches but performs case-insensitive matching.
Syntax
Arguments
haystack— The string to search in.Stringpattern— Regular expression pattern.const String
Returned value
Returns the number of matches found. UInt64
Examples
Case insensitive count
extract
Introduced in: v1.1
Extracts the first match of a regular expression in a string. If 'haystack' doesn't match 'pattern', an empty string is returned.
This function uses the RE2 regular expression library. Please refer to re2 for supported syntax.
If the regular expression has capturing groups (sub-patterns), the function matches the input string against the first capturing group.
Syntax
Arguments
haystack— String from which to extract.Stringpattern— Regular expression, typically containing a capturing group.const String
Returned value
Returns extracted fragment as a string. String
Examples
Extract domain from email
No match returns empty string
extractAll
Introduced in: v1.1
Like extract, but returns an array of all matches of a regular expression in a string.
If 'haystack' doesn't match the 'pattern' regex, an empty array is returned.
If the regular expression has capturing groups (sub-patterns), the function matches the input string against the first capturing group.
Syntax
Arguments
haystack— String from which to extract fragments.Stringpattern— Regular expression, optionally containing capturing groups.const String
Returned value
Returns array of extracted fragments. Array(String)
Examples
Extract all numbers
Extract using capturing group
hasAllTokens
Introduced in: v25.7
Like hasAnyTokens, but returns 1, if all tokens in the needle string or array match the input string, and 0 otherwise. If input is a column, returns all rows that satisfy this condition.
Column input should have a text index defined for optimal performance.
If no text index is defined, the function performs a brute-force column scan which is orders of magnitude slower than an index lookup.
Prior to searching, the function tokenizes
- the
inputargument (always), and - the
needleargument (if given as a String) using the tokenizer specified for the text index. If the column has no text index defined, thesplitByNonAlphatokenizer is used instead. If theneedleargument is of type Array(String), each array element is treated as a token — no additional tokenization takes place.
Duplicate tokens are ignored. For example, needles = ['ClickHouse', 'ClickHouse'] is treated the same as ['ClickHouse'].
Syntax
Aliases: hasAllToken
Arguments
input— The input column.StringorFixedStringneedles— Tokens to be searched. Supports at most 64 tokens.StringorArray(String)
Returned value
Returns 1, if all needles match. 0, otherwise. UInt8
Examples
Usage example
Specify needles to be searched for AS-IS (no tokenization) in an array
Generate needles using the tokens function
hasAnyTokens
Introduced in: v25.7
Returns 1, if at least one token in the needle string or array matches the input string, and 0 otherwise. If input is a column, returns all rows that satisfy this condition.
Column input should have a text index defined for optimal performance.
If no text index is defined, the function performs a brute-force column scan which is orders of magnitude slower than an index lookup.
Prior to searching, the function tokenizes
- the
inputargument (always), and - the
needleargument (if given as a String) using the tokenizer specified for the text index. If the column has no text index defined, thesplitByNonAlphatokenizer is used instead. If theneedleargument is of type Array(String), each array element is treated as a token — no additional tokenization takes place.
Duplicate tokens are ignored. For example, ['ClickHouse', 'ClickHouse'] is treated the same as ['ClickHouse'].
Syntax
Aliases: hasAnyToken
Arguments
input— The input column.StringorFixedStringneedles— Tokens to be searched. Supports at most 64 tokens.StringorArray(String)
Returned value
Returns 1, if there was at least one match. 0, otherwise. UInt8
Examples
Usage example
Specify needles to be searched for AS-IS (no tokenization) in an array
Generate needles using the tokens function
hasSubsequence
Introduced in: v23.7
Checks if a needle is a subsequence of a haystack. A subsequence of a string is a sequence that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
Syntax
Arguments
haystack— String in which to search for the subsequence.Stringneedle— Subsequence to be searched.String
Returned value
Returns 1 if needle is a subsequence of haystack, 0 otherwise. UInt8
Examples
Basic subsequence check
No subsequence found
hasToken
Introduced in: v20.1
Checks if the given token is present in the haystack.
A token is defined as the longest possible sub-sequence of consecutive characters [0-9A-Za-z_], i.e. numbers, ASCII letters and underscore.
Syntax
Arguments
haystack— String to be searched.Stringtoken— Token to search for.const String
Returned value
Returns 1 if the token is found, 0 otherwise. UInt8
Examples
Token search
hasTokenCaseInsensitive
Introduced in: v
Performs case insensitive lookup of needle in haystack using tokenbf_v1 index.
Syntax
Arguments
- None.
Returned value
Examples
hasTokenCaseInsensitiveOrNull
Introduced in: v
Performs case insensitive lookup of needle in haystack using tokenbf_v1 index. Returns null if needle is ill-formed.
Syntax
Arguments
- None.
Returned value
Examples
hasTokenOrNull
Introduced in: v20.1
Like hasToken but returns null if token is ill-formed.
Syntax
Arguments
haystack— String to be searched. Must be constant.Stringtoken— Token to search for.const String
Returned value
Returns 1 if the token is found, 0 otherwise, null if token is ill-formed. Nullable(UInt8)
Examples
Usage example
locate
Introduced in: v18.16
Like position but with arguments haystack and locate switched.
The behavior of this function depends on the ClickHouse version:
- in versions < v24.3,
locatewas an alias of functionpositionand accepted arguments(haystack, needle[, start_pos]). - in versions >= 24.3,
locateis an individual function (for better compatibility with MySQL) and accepts arguments(needle, haystack[, start_pos]). The previous behavior can be restored using settingfunction_locate_has_mysql_compatible_argument_order = false.
Syntax
Arguments
needle— Substring to be searched.Stringhaystack— String in which the search is performed.StringorEnumstart_pos— Optional. Position (1-based) inhaystackat which the search starts.UInt
Returned value
Returns starting position in bytes and counting from 1, if the substring was found, 0, if the substring was not found. UInt64
Examples
Basic usage
match
Introduced in: v1.1
Checks if a provided string matches the provided regular expression pattern.
This function uses the RE2 regular expression library. Please refer to re2 for supported syntax.
Matching works under UTF-8 assumptions, e.g. ¥ uses two bytes internally but matching treats it as a single codepoint.
The regular expression must not contain NULL bytes.
If the haystack or the pattern are not valid UTF-8, the behavior is undefined.
Unlike re2's default behavior, . matches line breaks. To disable this, prepend the pattern with (?-s).
The pattern is automatically anchored at both ends (as if the pattern started with '^' and ended with '$').
If you only like to find substrings, you can use functions like or position instead - they work much faster than this function.
Alternative operator syntax: haystack REGEXP pattern.
Syntax
Aliases: REGEXP_MATCHES
Arguments
haystack— String in which the pattern is searched.Stringpattern— Regular expression pattern.const String
Returned value
Returns 1 if the pattern matches, 0 otherwise. UInt8
Examples
Basic pattern matching
Pattern not matching
multiMatchAny
Introduced in: v20.1
Check if at least one of multiple regular expression patterns matches a haystack.
If you only want to search multiple substrings in a string, you can use function multiSearchAny instead - it works much faster than this function.
Syntax
Arguments
haystack— String in which patterns are searched.Stringpattern1[, pattern2, ...]— An array of one or more regular expression patterns.Array(String)
Returned value
Returns 1 if any pattern matches, 0 otherwise. UInt8
Examples
Multiple pattern matching
No patterns match
multiSearchAllPositions
Introduced in: v20.1
Like position but returns an array of positions (in bytes, starting at 1) for multiple needle substrings in a haystack string.
All multiSearch*() functions only support up to 2^8 needles.
Syntax
Arguments
haystack— String in which the search is performed.Stringneedle1[, needle2, ...]— An array of one or more substrings to be searched.Array(String)
Returned value
Returns array of the starting position in bytes and counting from 1, if the substring was found, 0, if the substring was not found. Array(UInt64)
Examples
Multiple needle search
multiSearchAllPositionsCaseInsensitive
Introduced in: v20.1
Like multiSearchAllPositions but ignores case.
Syntax
Arguments
haystack— String in which the search is performed.Stringneedle1[, needle2, ...]— An array of one or more substrings to be searched.Array(String)
Returned value
Returns array of the starting position in bytes and counting from 1 (if the substring was found), 0 if the substring was not found. Array(UInt64)
Examples
Case insensitive multi-search
multiSearchAllPositionsUTF8
Introduced in: v20.1
Like multiSearchAllPositions but assumes haystack and the needle substrings are UTF-8 encoded strings.
Syntax
Arguments
haystack— UTF-8 encoded string in which the search is performed.Stringneedle1[, needle2, ...]— An array of UTF-8 encoded substrings to be searched.Array(String)
Returned value
Returns array of the starting position in bytes and counting from 1 (if the substring was found), 0 if the substring was not found. Array
Examples
UTF-8 multi-search
multiSearchAny
Introduced in: v20.1
Checks if at least one of a number of needle strings matches the haystack string.
Functions multiSearchAnyCaseInsensitive, multiSearchAnyUTF8 and multiSearchAnyCaseInsensitiveUTF8 provide case-insensitive and/or UTF-8 variants of this function.
Syntax
Arguments
haystack— String in which the search is performed.Stringneedle1[, needle2, ...]— An array of substrings to be searched.Array(String)
Returned value
Returns 1, if there was at least one match, otherwise 0, if there was not at least one match. UInt8
Examples
Any match search
multiSearchAnyCaseInsensitive
Introduced in: v20.1
Like multiSearchAny but ignores case.
Syntax
Arguments
haystack— String in which the search is performed.Stringneedle— Substrings to be searched.Array(String)
Returned value
Returns 1, if there was at least one case-insensitive match, otherwise 0, if there was not at least one case-insensitive match. UInt8
Examples
Case insensitive search
multiSearchAnyCaseInsensitiveUTF8
Introduced in: v20.1
Like multiSearchAnyUTF8 but ignores case.
Syntax
Arguments
haystack— UTF-8 string in which the search is performed.Stringneedle— UTF-8 substrings to be searched.Array(String)
Returned value
Returns 1, if there was at least one case-insensitive match, otherwise 0, if there was not at least one case-insensitive match. UInt8
Examples
Given a UTF-8 string 'Здравствуйте', check if character 'з' (lowercase) is present
multiSearchAnyUTF8
Introduced in: v20.1
Like multiSearchAny but assumes haystack and the needle substrings are UTF-8 encoded strings.
Syntax
Arguments
haystack— UTF-8 string in which the search is performed.Stringneedle— UTF-8 substrings to be searched.Array(String)
Returned value
Returns 1, if there was at least one match, otherwise 0, if there was not at least one match. UInt8
Examples
Given '你好,世界' ('Hello, world') as a UTF-8 string, check if there are any 你 or 界 characters in the string
multiSearchFirstPosition
Introduced in: v20.1
Like position but returns the leftmost offset in a haystack string which matches any of multiple needle strings.
Functions multiSearchFirstPositionCaseInsensitive, multiSearchFirstPositionUTF8 and multiSearchFirstPositionCaseInsensitiveUTF8 provide case-insensitive and/or UTF-8 variants of this function.
Syntax
Arguments
haystack— String in which the search is performed.Stringneedle1[, needle2, ...]— An array of one or more substrings to be searched.Array(String)
Returned value
Returns the leftmost offset in a haystack string which matches any of multiple needle strings, otherwise 0, if there was no match. UInt64
Examples
First position search
multiSearchFirstPositionCaseInsensitive
Introduced in: v20.1
Like multiSearchFirstPosition but ignores case.
Syntax
Arguments
haystack— String in which the search is performed.Stringneedle— Array of substrings to be searched.Array(String)
Returned value
Returns the leftmost offset in a haystack string which matches any of multiple needle strings. Returns 0, if there was no match. UInt64
Examples
Case insensitive first position
multiSearchFirstPositionCaseInsensitiveUTF8
Introduced in: v20.1
Like multiSearchFirstPosition but assumes haystack and needle to be UTF-8 strings and ignores case.
Syntax
Arguments
haystack— UTF-8 string in which the search is performed.Stringneedle— Array of UTF-8 substrings to be searched.Array(String)
Returned value
Returns the leftmost offset in a haystack string which matches any of multiple needle strings, ignoring case. Returns 0, if there was no match. UInt64
Examples
Find the leftmost offset in UTF-8 string 'Здравствуй, мир' ('Hello, world') which matches any of the given needles
multiSearchFirstPositionUTF8
Introduced in: v20.1
Like multiSearchFirstPosition but assumes haystack and needle to be UTF-8 strings.
Syntax
Arguments
haystack— UTF-8 string in which the search is performed.Stringneedle— Array of UTF-8 substrings to be searched.Array(String)
Returned value
Leftmost offset in a haystack string which matches any of multiple needle strings. Returns 0, if there was no match. UInt64
Examples
Find the leftmost offset in UTF-8 string 'Здравствуй, мир' ('Hello, world') which matches any of the given needles
ngramDistance
Introduced in: v20.1
Calculates the 4-gram distance between two strings. For this, it counts the symmetric difference between two multisets of 4-grams and normalizes it by the sum of their cardinalities. The smaller the returned value, the more similar the strings are.
For case-insensitive search or/and in UTF8 format use functions ngramDistanceCaseInsensitive, ngramDistanceUTF8, ngramDistanceCaseInsensitiveUTF8.
Syntax
Arguments
Returned value
Returns a Float32 number between 0 and 1. The smaller the returned value, the more similar the strings are. Float32
Examples
Calculate 4-gram distance
ngramDistanceCaseInsensitive
Introduced in: v20.1
Provides a case-insensitive variant of ngramDistance.
Calculates the 4-gram distance between two strings, ignoring case.
The smaller the returned value, the more similar the strings are.
Syntax
Arguments
Returned value
Returns a Float32 number between 0 and 1. Float32
Examples
Case-insensitive 4-gram distance
ngramDistanceCaseInsensitiveUTF8
Introduced in: v20.1
Provides a case-insensitive UTF-8 variant of ngramDistance.
Assumes that needle and haystack strings are UTF-8 encoded strings and ignores case.
Calculates the 3-gram distance between two UTF-8 strings, ignoring case.
The smaller the returned value, the more similar the strings are.
Syntax
Arguments
haystack— First UTF-8 encoded comparison string.Stringneedle— Second UTF-8 encoded comparison string.String
Returned value
Returns a Float32 number between 0 and 1. Float32
Examples
Case-insensitive UTF-8 3-gram distance
ngramDistanceUTF8
Introduced in: v20.1
Provides a UTF-8 variant of ngramDistance.
Assumes that needle and haystack strings are UTF-8 encoded strings.
Calculates the 3-gram distance between two UTF-8 strings.
The smaller the returned value, the more similar the strings are.
Syntax
Arguments
haystack— First UTF-8 encoded comparison string.Stringneedle— Second UTF-8 encoded comparison string.String
Returned value
Returns a Float32 number between 0 and 1. Float32
Examples
UTF-8 3-gram distance
ngramSearch
Introduced in: v20.1
Checks if the 4-gram distance between two strings is less than or equal to a given threshold.
For case-insensitive search or/and in UTF8 format use functions ngramSearchCaseInsensitive, ngramSearchUTF8, ngramSearchCaseInsensitiveUTF8.
Syntax
Arguments
Returned value
Returns 1 if the 4-gram distance between the strings is less than or equal to a threshold (1.0 by default), 0 otherwise. UInt8
Examples
Search using 4-grams
ngramSearchCaseInsensitive
Introduced in: v20.1
Provides a case-insensitive variant of ngramSearch.
Calculates the non-symmetric difference between a needle string and a haystack string, i.e. the number of n-grams from the needle minus the common number of n-grams normalized by the number of needle n-grams.
Checks if the 4-gram distance between two strings is less than or equal to a given threshold, ignoring case.
Syntax
Arguments
Returned value
Returns 1 if the 4-gram distance between the strings is less than or equal to a threshold (1.0 by default), 0 otherwise. UInt8
Examples
Case-insensitive search using 4-grams
ngramSearchCaseInsensitiveUTF8
Introduced in: v20.1
Provides a case-insensitive UTF-8 variant of ngramSearch.
Assumes haystack and needle to be UTF-8 strings and ignores case.
Checks if the 3-gram distance between two UTF-8 strings is less than or equal to a given threshold, ignoring case.
Syntax
Arguments
Returned value
Returns 1 if the 3-gram distance between the strings is less than or equal to a threshold (1.0 by default), 0 otherwise. UInt8
Examples
Case-insensitive UTF-8 search using 3-grams
ngramSearchUTF8
Introduced in: v20.1
Provides a UTF-8 variant of ngramSearch.
Assumes haystack and needle to be UTF-8 strings.
Checks if the 3-gram distance between two UTF-8 strings is less than or equal to a given threshold.
Syntax
Arguments
Returned value
Returns 1 if the 3-gram distance between the strings is less than or equal to a threshold (1.0 by default), 0 otherwise. UInt8
Examples
UTF-8 search using 3-grams
position
Introduced in: v1.1
Returns the position (in bytes, starting at 1) of a substring needle in a string haystack.
If substring needle is empty, these rules apply:
- if no
start_poswas specified: return1 - if
start_pos = 0: return1 - if
start_pos >= 1andstart_pos <= length(haystack) + 1: returnstart_pos - otherwise: return
0
The same rules also apply to functions locate, positionCaseInsensitive, positionUTF8 and positionCaseInsensitiveUTF8.
Syntax
Arguments
haystack— String in which the search is performed.StringorEnumneedle— Substring to be searched.Stringstart_pos— Position (1-based) inhaystackat which the search starts. Optional.UInt
Returned value
Returns starting position in bytes and counting from 1, if the substring was found, otherwise 0, if the substring was not found. UInt64
Examples
Basic usage
With start_pos argument
Needle IN haystack syntax
Empty needle substring
positionCaseInsensitive
Introduced in: v1.1
Like position but case-insensitive.
Syntax
Aliases: instr
Arguments
haystack— String in which the search is performed.StringorEnumneedle— Substring to be searched.Stringstart_pos— Optional. Position (1-based) inhaystackat which the search starts.UInt*
Returned value
Returns starting position in bytes and counting from 1, if the substring was found, otherwise 0, if the substring was not found. UInt64
Examples
Case insensitive search
positionCaseInsensitiveUTF8
Introduced in: v1.1
Like positionUTF8 but searches case-insensitively.
Syntax
Arguments
haystack— String in which the search is performed.StringorEnumneedle— Substring to be searched.Stringstart_pos— Optional. Position (1-based) inhaystackat which the search starts.UInt*
Returned value
Returns starting position in bytes and counting from 1, if the substring was found, otherwise 0, if the substring was not found. UInt64
Examples
Case insensitive UTF-8 search
positionUTF8
Introduced in: v1.1
Like position but assumes haystack and needle are UTF-8 encoded strings.
Syntax
Arguments
haystack— String in which the search is performed.StringorEnumneedle— Substring to be searched.Stringstart_pos— Optional. Position (1-based) inhaystackat which the search starts.UInt*
Returned value
Returns starting position in bytes and counting from 1, if the substring was found, otherwise 0, if the substring was not found. UInt64
Examples
UTF-8 character counting
regexpExtract
Introduced in: v
Extracts the first string in haystack that matches the regexp pattern and corresponds to the regex group index.
Syntax
Aliases: REGEXP_EXTRACT
Arguments
- None.
Returned value
Examples