id stringlengths 36 36 | document stringlengths 3 3k | metadata stringlengths 23 69 | embeddings listlengths 384 384 |
|---|---|---|---|
cfe2015b-fac9-4257-a23c-60de6d80a190 | Introduced in: v20.1
Adds a specified number of quarters to a date, a date with time or a string-encoded date or date with time.
Syntax
sql
addQuarters(datetime, num)
Arguments
datetime
β Date or date with time to add specified number of quarters to.
Date
or
Date32
or
DateTime
or
DateTime64
or
String
num
β Number of quarters to add.
(U)Int*
or
Float*
Returned value
Returns
datetime
plus
num
quarters
Date
or
Date32
or
DateTime
or
DateTime64
Examples
Add quarters to different date types
sql title=Query
WITH
toDate('2024-01-01') AS date,
toDateTime('2024-01-01 00:00:00') AS date_time,
'2024-01-01 00:00:00' AS date_time_string
SELECT
addQuarters(date, 1) AS add_quarters_with_date,
addQuarters(date_time, 1) AS add_quarters_with_date_time,
addQuarters(date_time_string, 1) AS add_quarters_with_date_time_string
response title=Response
ββadd_quarters_with_dateββ¬βadd_quarters_with_date_timeββ¬βadd_quarters_with_date_time_stringββ
β 2024-04-01 β 2024-04-01 00:00:00 β 2024-04-01 00:00:00.000 β
ββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββ
Using alternative INTERVAL syntax
sql title=Query
SELECT dateAdd('1998-06-16'::Date, INTERVAL 10 quarter)
response title=Response
ββplus(CAST('1β―uarter(10))ββ
β 2000-12-16 β
ββββββββββββββββββββββββββββ
addSeconds {#addSeconds}
Introduced in: v1.1
Adds a specified number of seconds to a date, a date with time or a string-encoded date or date with time.
Syntax
sql
addSeconds(datetime, num)
Arguments
datetime
β Date or date with time to add specified number of seconds to.
Date
or
Date32
or
DateTime
or
DateTime64
or
String
num
β Number of seconds to add.
(U)Int*
or
Float*
Returned value
Returns
datetime
plus
num
seconds
DateTime
or
DateTime64(3)
Examples
Add seconds to different date types
sql title=Query
WITH
toDate('2024-01-01') AS date,
toDateTime('2024-01-01 00:00:00') AS date_time,
'2024-01-01 00:00:00' AS date_time_string
SELECT
addSeconds(date, 30) AS add_seconds_with_date,
addSeconds(date_time, 30) AS add_seconds_with_date_time,
addSeconds(date_time_string, 30) AS add_seconds_with_date_time_string
response title=Response
ββadd_seconds_with_dateββ¬βadd_seconds_with_date_timeββ¬βadd_seconds_with_date_time_stringββ
β 2024-01-01 00:00:30 β 2024-01-01 00:00:30 β 2024-01-01 00:00:30.000 β
βββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββ
Using alternative INTERVAL syntax
sql title=Query
SELECT dateAdd('1998-06-16'::Date, INTERVAL 10 second)
response title=Response
ββdateAdd('1998-06-16'::Date, INTERVAL 10 second)ββ
β 1998-06-16 00:00:10 β
βββββββββββββββββββββββββββββββββββββββββββββββββββ
addTupleOfIntervals {#addTupleOfIntervals}
Introduced in: v22.11 | {"source_file": "date-time-functions.md"} | [
0.024902256205677986,
0.012101779691874981,
-0.02603720687329769,
0.07405232638120651,
-0.11551982164382935,
0.055309709161520004,
-0.029636669903993607,
0.004250951111316681,
-0.035106413066387177,
0.037272002547979355,
0.047785814851522446,
-0.13822412490844727,
-0.034195173531770706,
-0... |
f7d6c308-9911-4e7f-b396-ced137562c0c | addTupleOfIntervals {#addTupleOfIntervals}
Introduced in: v22.11
Consecutively adds a tuple of intervals to a date or a date with time.
Syntax
sql
addTupleOfIntervals(datetime, intervals)
Arguments
datetime
β Date or date with time to add intervals to.
Date
or
Date32
or
DateTime
or
DateTime64
intervals
β Tuple of intervals to add to
datetime
.
Tuple(Interval)
Returned value
Returns
date
with added
intervals
Date
or
Date32
or
DateTime
or
DateTime64
Examples
Add tuple of intervals to date
sql title=Query
WITH toDate('2018-01-01') AS date
SELECT addTupleOfIntervals(date, (INTERVAL 1 DAY, INTERVAL 1 MONTH, INTERVAL 1 YEAR))
response title=Response
ββaddTupleOfIntervals(date, (toIntervalDay(1), toIntervalMonth(1), toIntervalYear(1)))ββ
β 2019-02-02 β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
addWeeks {#addWeeks}
Introduced in: v1.1
Adds a specified number of weeks to a date, a date with time or a string-encoded date or date with time.
Syntax
sql
addWeeks(datetime, num)
Arguments
datetime
β Date or date with time to add specified number of weeks to.
Date
or
Date32
or
DateTime
or
DateTime64
or
String
num
β Number of weeks to add.
(U)Int*
or
Float*
Returned value
Returns
datetime
plus
num
weeks
Date
or
Date32
or
DateTime
or
DateTime64
Examples
Add weeks to different date types
sql title=Query
WITH
toDate('2024-01-01') AS date,
toDateTime('2024-01-01 00:00:00') AS date_time,
'2024-01-01 00:00:00' AS date_time_string
SELECT
addWeeks(date, 5) AS add_weeks_with_date,
addWeeks(date_time, 5) AS add_weeks_with_date_time,
addWeeks(date_time_string, 5) AS add_weeks_with_date_time_string
response title=Response
ββadd_weeks_with_dateββ¬βadd_weeks_with_date_timeββ¬βadd_weeks_with_date_time_stringββ
β 2024-02-05 β 2024-02-05 00:00:00 β 2024-02-05 00:00:00.000 β
βββββββββββββββββββββββ΄βββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββ
Using alternative INTERVAL syntax
sql title=Query
SELECT dateAdd('1998-06-16'::Date, INTERVAL 10 week)
response title=Response
ββplus(CAST('1β―alWeek(10))ββ
β 1998-08-25 β
ββββββββββββββββββββββββββββ
addYears {#addYears}
Introduced in: v1.1
Adds a specified number of years to a date, a date with time or a string-encoded date or date with time.
Syntax
sql
addYears(datetime, num)
Arguments
datetime
β Date or date with time to add specified number of years to.
Date
or
Date32
or
DateTime
or
DateTime64
or
String
num
β Number of years to add.
(U)Int*
or
Float*
Returned value
Returns
datetime
plus
num
years
Date
or
Date32
or
DateTime
or
DateTime64
Examples
Add years to different date types | {"source_file": "date-time-functions.md"} | [
-0.06884794682264328,
-0.032780613750219345,
-0.0011472468031570315,
0.09852084517478943,
-0.061835870146751404,
0.07670015841722488,
-0.008548072539269924,
-0.013138559646904469,
-0.06311939656734467,
-0.021581143140792847,
0.042757175862789154,
-0.10783727467060089,
-0.0017537957755848765,... |
9c163f73-c018-47fd-bf1d-a57119bded7a | Returned value
Returns
datetime
plus
num
years
Date
or
Date32
or
DateTime
or
DateTime64
Examples
Add years to different date types
sql title=Query
WITH
toDate('2024-01-01') AS date,
toDateTime('2024-01-01 00:00:00') AS date_time,
'2024-01-01 00:00:00' AS date_time_string
SELECT
addYears(date, 1) AS add_years_with_date,
addYears(date_time, 1) AS add_years_with_date_time,
addYears(date_time_string, 1) AS add_years_with_date_time_string
response title=Response
ββadd_years_with_dateββ¬βadd_years_with_date_timeββ¬βadd_years_with_date_time_stringββ
β 2025-01-01 β 2025-01-01 00:00:00 β 2025-01-01 00:00:00.000 β
βββββββββββββββββββββββ΄βββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββ
Using alternative INTERVAL syntax
sql title=Query
SELECT dateAdd('1998-06-16'::Date, INTERVAL 10 year)
response title=Response
ββplus(CAST('1β―alYear(10))ββ
β 2008-06-16 β
ββββββββββββββββββββββββββββ
age {#age}
Introduced in: v23.1
Returns the unit component of the difference between
startdate
and
enddate
.
The difference is calculated using a precision of 1 nanosecond.
For example, the difference between 2021-12-29 and 2022-01-01 is 3 days for the day unit,
0 months for the month unit, and 0 years for the year unit.
For an alternative to age, see function
dateDiff
.
Syntax
sql
age('unit', startdate, enddate, [timezone])
Arguments
unit
β The type of interval for result.
| Unit | Possible values |
|-------------|------------------------------------------|
| nanosecond |
nanosecond
,
nanoseconds
,
ns
|
| microsecond |
microsecond
,
microseconds
,
us
,
u
|
| millisecond |
millisecond
,
milliseconds
,
ms
|
| second |
second
,
seconds
,
ss
,
s
|
| minute |
minute
,
minutes
,
mi
,
n
|
| hour |
hour
,
hours
,
hh
,
h
|
| day |
day
,
days
,
dd
,
d
|
| week |
week
,
weeks
,
wk
,
ww
|
| month |
month
,
months
,
mm
,
m
|
| quarter |
quarter
,
quarters
,
qq
,
q
|
| year |
year
,
years
,
yyyy
,
yy
|
-
startdate
β The first time value to subtract (the subtrahend).
Date
or
Date32
or
DateTime
or
DateTime64
-
enddate
β The second time value to subtract from (the minuend).
Date
or
Date32
or
DateTime
or
DateTime64
-
timezone
β Optional. Timezone name. If specified, it is applied to both startdate and enddate. If not specified, timezones of startdate and enddate are used. If they are not the same, the result is unspecified.
String
Returned value
Returns the difference between enddate and startdate expressed in unit.
Int32
Examples
Calculate age in hours
sql title=Query
SELECT age('hour', toDateTime('2018-01-01 22:30:00'), toDateTime('2018-01-02 23:00:00')) | {"source_file": "date-time-functions.md"} | [
-0.02262466959655285,
0.01149055641144514,
0.02476535178720951,
0.04485534131526947,
-0.044337376952171326,
0.03137432783842087,
-0.01166491862386465,
0.015017544850707054,
-0.03664400056004524,
-0.019393883645534515,
0.048211704939603806,
-0.12299859523773193,
-0.003642205148935318,
0.019... |
e76aa924-083c-41b5-a487-a751eba557f1 | Examples
Calculate age in hours
sql title=Query
SELECT age('hour', toDateTime('2018-01-01 22:30:00'), toDateTime('2018-01-02 23:00:00'))
response title=Response
ββage('hour', toDateTime('2018-01-01 22:30:00'), toDateTime('2018-01-02 23:00:00'))ββ
β 24 β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Calculate age in different units
sql title=Query
SELECT
toDate('2022-01-01') AS e,
toDate('2021-12-29') AS s,
age('day', s, e) AS day_age,
age('month', s, e) AS month_age,
age('year', s, e) AS year_age
response title=Response
βββββββββββeββ¬ββββββββββsββ¬βday_ageββ¬βmonth_ageββ¬βyear_ageββ
β 2022-01-01 β 2021-12-29 β 3 β 0 β 0 β
ββββββββββββββ΄βββββββββββββ΄ββββββββββ΄ββββββββββββ΄βββββββββββ
changeDay {#changeDay}
Introduced in: v24.7
Changes the day component of a date or date time.
Syntax
sql
changeDay(date_or_datetime, value)
Arguments
date_or_datetime
β The value to change.
Date
or
Date32
or
DateTime
or
DateTime64
value
β The new value.
(U)Int*
Returned value
Returns a value of the same type as
date_or_datetime
with modified day component.
Date
or
Date32
or
DateTime
or
DateTime64
Examples
Usage example
sql title=Query
SELECT changeDay('2024-01-31'::DateTime, 15)
response title=Response
2024-01-15 00:00:00
changeHour {#changeHour}
Introduced in: v24.7
Changes the hour component of a date or date time.
Syntax
sql
changeHour(date_or_datetime, value)
Arguments
date_or_datetime
β The value to change.
Date
or
Date32
or
DateTime
or
DateTime64
value
β The new value.
(U)Int*
Returned value
Returns a value of the same type as
date_or_datetime
with modified hour component.
DateTime
or
DateTime64
Examples
Usage example
sql title=Query
SELECT changeHour('2024-01-01 12:00:00'::DateTime, 5)
response title=Response
2024-01-01 05:00:00
changeMinute {#changeMinute}
Introduced in: v24.7
Changes the minute component of a
date or date time
.
Syntax
sql
changeMinute(date_or_datetime, value)
Arguments
date_or_datetime
β The value to change.
Date
or
Date32
or
DateTime
or
DateTime64
value
β The new value.
(U)Int*
Returned value
Returns a value of the same type as
date_or_datetime
with modified minute component.
DateTime
or
DateTime64
Examples
Usage example
sql title=Query
SELECT changeMinute('2024-01-01 12:30:00'::DateTime, 45)
response title=Response
2024-01-01 12:45:00
changeMonth {#changeMonth}
Introduced in: v24.7
Changes the month component of a date or date time.
Syntax
sql
changeMonth(date_or_datetime, value)
Arguments
date_or_datetime
β The value to change.
Date
or
Date32
or
DateTime
or
DateTime64
value
β The new value.
(U)Int*
Returned value | {"source_file": "date-time-functions.md"} | [
0.029225939884781837,
0.06331998854875565,
0.045778512954711914,
0.08457746356725693,
-0.0528092198073864,
-0.03042449615895748,
0.014064607210457325,
0.010009977966547012,
-0.07782531529664993,
0.044483259320259094,
0.07683174312114716,
-0.1410343497991562,
0.011735287494957447,
0.0139972... |
56722826-efba-4021-a35e-b0ad6b87f630 | Arguments
date_or_datetime
β The value to change.
Date
or
Date32
or
DateTime
or
DateTime64
value
β The new value.
(U)Int*
Returned value
Returns a value of the same type as
date_or_datetime
with modified month component.
Date
or
Date32
or
DateTime
or
DateTime64
Examples
Usage example
sql title=Query
SELECT changeMonth('2024-01-01'::DateTime, 12)
response title=Response
2024-12-01 00:00:00
changeSecond {#changeSecond}
Introduced in: v24.7
Changes the second component of a date or date time.
Syntax
sql
changeSecond(date_or_datetime, value)
Arguments
date_or_datetime
β The value to change.
Date
or
Date32
or
DateTime
or
DateTime64
value
β The new value.
(U)Int*
Returned value
Returns a value of the same type as
date_or_datetime
with modified seconds component.
DateTime
or
DateTime64
Examples
Usage example
sql title=Query
SELECT changeSecond('2024-01-01 12:30:45'::DateTime, 15)
response title=Response
2024-01-01 12:30:15
changeYear {#changeYear}
Introduced in: v24.7
Changes the year component of a date or date time.
Syntax
sql
changeYear(date_or_datetime, value)
Arguments
date_or_datetime
β The value to change.
Date
or
Date32
or
DateTime
or
DateTime64
value
β The new value.
(U)Int*
Returned value
Returns a value of the same type as
date_or_datetime
with modified year component.
Date
or
Date32
or
DateTime
or
DateTime64
Examples
Usage example
sql title=Query
SELECT changeYear('2024-01-01'::DateTime, 2023)
response title=Response
2023-01-01 00:00:00
dateDiff {#dateDiff}
Introduced in: v23.4
Returns the count of the specified
unit
boundaries crossed between the
startdate
and the
enddate
.
The difference is calculated using relative units. For example, the difference between 2021-12-29 and 2022-01-01 is 3 days for unit day
(see
toRelativeDayNum
), 1 month for unit month (see
toRelativeMonthNum
) and 1 year for unit year
(see
toRelativeYearNum
).
If the unit
week
was specified, then
dateDiff
assumes that weeks start on Monday.
Note that this behavior is different from that of function
toWeek()
in which weeks start by default on Sunday.
For an alternative to
dateDiff
, see function
age
.
Syntax
sql
dateDiff(unit, startdate, enddate, [timezone])
Aliases
:
timestampDiff
,
TIMESTAMP_DIFF
,
DATE_DIFF
,
date_diff
,
timestamp_diff
Arguments
unit
β The type of interval for result. | {"source_file": "date-time-functions.md"} | [
-0.004865275230258703,
0.0036045906599611044,
-0.035738181322813034,
0.053499363362789154,
-0.013964050449430943,
0.011149575002491474,
0.015020581893622875,
0.04208538681268692,
0.022584734484553337,
0.06639280170202255,
-0.0020064085256308317,
-0.0757773146033287,
-0.037900183349847794,
... |
3d493295-5bbd-424b-a7d3-d42f1a725762 | Aliases
:
timestampDiff
,
TIMESTAMP_DIFF
,
DATE_DIFF
,
date_diff
,
timestamp_diff
Arguments
unit
β The type of interval for result.
| Unit | Possible values |
|-------------|-------------------------------------------|
| nanosecond |
nanosecond
,
nanoseconds
,
ns
|
| microsecond |
microsecond
,
microseconds
,
us
,
u
|
| millisecond |
millisecond
,
milliseconds
,
ms
|
| second |
second
,
seconds
,
ss
,
s
|
| minute |
minute
,
minutes
,
mi
,
n
|
| hour |
hour
,
hours
,
hh
,
h
|
| day |
day
,
days
,
dd
,
d
|
| week |
week
,
weeks
,
wk
,
ww
|
| month |
month
,
months
,
mm
,
m
|
| quarter |
quarter
,
quarters
,
qq
,
q
|
| year |
year
,
years
,
yyyy
,
yy
|
-
startdate
β The first time value to subtract (the subtrahend).
Date
or
Date32
or
DateTime
or
DateTime64
-
enddate
β The second time value to subtract from (the minuend).
Date
or
Date32
or
DateTime
or
DateTime64
-
timezone
β Optional. Timezone name. If specified, it is applied to both
startdate
and
enddate
. If not specified, timezones of
startdate
and
enddate
are used. If they are not the same, the result is unspecified.
String
Returned value
Returns the difference between
enddate
and
startdate
expressed in
unit
.
Int64
Examples
Calculate date difference in hours
sql title=Query
SELECT dateDiff('hour', toDateTime('2018-01-01 22:00:00'), toDateTime('2018-01-02 23:00:00')) AS res
response title=Response
ββresββ
β 25 β
βββββββ
Calculate date difference in different units
sql title=Query
SELECT
toDate('2022-01-01') AS e,
toDate('2021-12-29') AS s,
dateDiff('day', s, e) AS day_diff,
dateDiff('month', s, e) AS month_diff,
dateDiff('year', s, e) AS year_diff
response title=Response
βββββββββββeββ¬ββββββββββsββ¬βday_diffββ¬βmonth_diffββ¬βyear_diffββ
β 2022-01-01 β 2021-12-29 β 3 β 1 β 1 β
ββββββββββββββ΄βββββββββββββ΄βββββββββββ΄βββββββββββββ΄ββββββββββββ
dateName {#dateName}
Introduced in: v21.7
Returns the specified part of the date.
Possible values:
- 'year'
- 'quarter'
- 'month'
- 'week'
- 'dayofyear'
- 'day'
- 'weekday'
- 'hour'
- 'minute'
- 'second'
Syntax
sql
dateName(date_part, date[, timezone])
Arguments
date_part
β The part of the date that you want to extract.
String
datetime
β A date or date with time value.
Date
or
Date32
or
DateTime
or
DateTime64
timezone
β Optional. Timezone.
String
Returned value
Returns the specified part of date.
String
Examples
Extract different date parts
sql title=Query
WITH toDateTime('2021-04-14 11:22:33') AS date_value
SELECT
dateName('year', date_value),
dateName('month', date_value),
dateName('day', date_value) | {"source_file": "date-time-functions.md"} | [
0.006658875849097967,
-0.005870324093848467,
-0.07163051515817642,
-0.013543317094445229,
-0.043245017528533936,
-0.08781329542398453,
-0.02469080686569214,
0.0890519842505455,
-0.042135316878557205,
-0.0060193478129804134,
0.04128143563866615,
-0.11196882277727127,
0.05505303665995598,
-0... |
bc83f244-efe5-44ee-811b-515368d032d8 | sql title=Query
WITH toDateTime('2021-04-14 11:22:33') AS date_value
SELECT
dateName('year', date_value),
dateName('month', date_value),
dateName('day', date_value)
response title=Response
ββdateName('year', date_value)ββ¬βdateName('month', date_value)ββ¬βdateName('day', date_value)ββ
β 2021 β April β 14 β
ββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββ
dateTrunc {#dateTrunc}
Introduced in: v20.8
Truncates a date and time value to the specified part of the date.
Syntax
sql
dateTrunc(unit, datetime[, timezone])
Aliases
:
DATE_TRUNC
Arguments
unit
β
The type of interval to truncate the result.
unit
argument is case-insensitive.
| Unit | Compatibility |
|--------------|---------------------------------|
|
nanosecond
| Compatible only with DateTime64 |
|
microsecond
| Compatible only with DateTime64 |
|
millisecond
| Compatible only with DateTime64 |
|
second
| |
|
minute
| |
|
hour
| |
|
day
| |
|
week
| |
|
month
| |
|
quarter
| |
|
year
| |
String
datetime
β Date and time.
Date
or
Date32
or
DateTime
or
DateTime64
timezone
β Optional. Timezone name for the returned datetime. If not specified, the function uses the timezone of the
datetime
parameter.
String
Returned value
Returns the truncated date and time value.
| Unit Argument |
datetime
Argument | Return Type |
|-----------------------------|---------------------------------------|----------------------------------------------------------------------------------------|
| Year, Quarter, Month, Week |
Date32
or
DateTime64
or
Date
or
DateTime
|
Date32
or
Date
|
| Day, Hour, Minute, Second |
Date32
,
DateTime64
,
Date
, or
DateTime
|
DateTime64
or
DateTime
|
| Millisecond, Microsecond, | Any |
DateTime64
|
| Nanosecond | | with scale 3, 6, or 9 |
Examples
Truncate without timezone
sql title=Query
SELECT now(), dateTrunc('hour', now());
response title=Response
ββββββββββββββββnow()ββ¬βdateTrunc('hour', now())βββ
β 2020-09-28 10:40:45 β 2020-09-28 10:00:00 β
βββββββββββββββββββββββ΄ββββββββββββββββββββββββββββ
Truncate with specified timezone
sql title=Query
SELECT now(), dateTrunc('hour', now(), 'Asia/Istanbul'); | {"source_file": "date-time-functions.md"} | [
0.01932656019926071,
0.03188323229551315,
0.007885034196078777,
0.09277521073818207,
-0.09399482607841492,
-0.032218240201473236,
0.003920502029359341,
0.03708036243915558,
-0.06896010041236877,
-0.011605658568441868,
0.05326396971940994,
-0.09607618302106857,
0.03248876333236694,
-0.00112... |
eca328bf-52f5-4235-92b7-56be2a010760 | Truncate with specified timezone
sql title=Query
SELECT now(), dateTrunc('hour', now(), 'Asia/Istanbul');
response title=Response
ββββββββββββββββnow()ββ¬βdateTrunc('hour', now(), 'Asia/Istanbul')βββ
β 2020-09-28 10:46:26 β 2020-09-28 13:00:00 β
βββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββ
formatDateTime {#formatDateTime}
Introduced in: v1.1
Formats a date or date with time according to the given format string.
format
is a constant expression, so you cannot have multiple formats for a single result column.
formatDateTime
uses MySQL datetime format style, refer to the
mysql docs
.
The opposite operation of this function is
parseDateTime
.
Using replacement fields, you can define a pattern for the resulting string.
The example column in the table below shows formatting result for
2018-01-02 22:33:44
.
Replacement fields:
| Placeholder | Description | Example |
|-------------|-------------|---------|
| %a | abbreviated weekday name (Mon-Sun) | Mon |
| %b | abbreviated month name (Jan-Dec) | Jan |
| %c | month as an integer number (01-12) | 01 |
| %C | year divided by 100 and truncated to integer (00-99) | 20 |
| %d | day of the month, zero-padded (01-31) | 02 |
| %D | Short MM/DD/YY date, equivalent to %m/%d/%y | 01/02/18 |
| %e | day of the month, space-padded (1-31) | 2 |
| %f | fractional second | 123456 |
| %F | short YYYY-MM-DD date, equivalent to %Y-%m-%d | 2018-01-02 |
| %g | two-digit year format, aligned to ISO 8601 | 18 |
| %G | four-digit year format for ISO week number | 2018 |
| %h | hour in 12h format (01-12) | 09 |
| %H | hour in 24h format (00-23) | 22 |
| %i | minute (00-59) | 33 |
| %I | hour in 12h format (01-12) | 10 |
| %j | day of the year (001-366) | 002 |
| %k | hour in 24h format (00-23) | 14 |
| %l | hour in 12h format (01-12) | 09 |
| %m | month as an integer number (01-12) | 01 |
| %M | full month name (January-December) | January |
| %n | new-line character | |
| %p | AM or PM designation | PM |
| %Q | Quarter (1-4) | 1 |
| %r | 12-hour HH:MM AM/PM time, equivalent to %h:%i %p | 10:30 PM |
| %R | 24-hour HH:MM time, equivalent to %H:%i | 22:33 |
| %s | second (00-59) | 44 |
| %S | second (00-59) | 44 |
| %t | horizontal-tab character | |
| %T | ISO 8601 time format (HH:MM:SS), equivalent to %H:%i:%S | 22:33:44 |
| %u | ISO 8601 weekday as number with Monday as 1 (1-7) | 2 |
| %V | ISO 8601 week number (01-53) | 01 |
| %w | weekday as a integer number with Sunday as 0 (0-6) | 2 |
| %W | full weekday name (Monday-Sunday) | Monday |
| %y | Year, last two digits (00-99) | 18 |
| %Y | Year | 2018 |
| %z | Time offset from UTC as +HHMM or -HHMM | -0500 |
| %% | a % sign | % |
In ClickHouse versions earlier than v23.4,
%f
prints a single zero (0) if the formatted value is a Date, Date32 or DateTime (which have no fractional seconds) or a DateTime64 with a precision of 0. | {"source_file": "date-time-functions.md"} | [
0.05634477734565735,
0.08323419839143753,
0.0537065714597702,
0.04498304799199104,
-0.05242495611310005,
-0.027115844190120697,
0.048543062061071396,
0.06042250245809555,
0.03095064125955105,
-0.01807566173374653,
-0.025867655873298645,
-0.05258931964635849,
0.0026766606606543064,
0.016868... |
e7f6433b-a769-446f-aa54-668abfa66505 | In ClickHouse versions earlier than v25.1,
%f
prints as many digits as specified by the scale of the DateTime64 instead of fixed 6 digits.
In ClickHouse versions earlier than v23.4,
%M
prints the minute (00-59) instead of the full month name (January-December).
Syntax
sql
formatDateTime(datetime, format[, timezone])
Aliases
:
DATE_FORMAT
Arguments
datetime
β A date or date time to format.
Date
or
Date32
or
DateTime
or
DateTime64
format
β Format string with replacement fields.
String
timezone
β Optional. Timezone name for the formatted time.
String
Returned value
Returns time and date values according to the determined format.
String
Examples
Format date with year placeholder
sql title=Query
SELECT formatDateTime(toDate('2010-01-04'), '%g')
response title=Response
ββformatDateTime(toDate('2010-01-04'), '%g')ββ
β 10 β
ββββββββββββββββββββββββββββββββββββββββββββββ
Format DateTime64 with fractional seconds
sql title=Query
SELECT formatDateTime(toDateTime64('2010-01-04 12:34:56.123456', 7), '%f')
response title=Response
ββformatDateTime(toDateTime64('2010-01-04 12:34:56.123456', 7), '%f')ββ
β 1234560 β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Format with timezone
sql title=Query
SELECT
now() AS ts,
time_zone,
formatDateTime(ts, '%T', time_zone) AS str_tz_time
FROM system.time_zones
WHERE time_zone LIKE 'Europe%'
LIMIT 10
response title=Response
βββββββββββββββββββtsββ¬βtime_zoneββββββββββ¬βstr_tz_timeββ
β 2023-09-08 19:13:40 β Europe/Amsterdam β 21:13:40 β
β 2023-09-08 19:13:40 β Europe/Andorra β 21:13:40 β
β 2023-09-08 19:13:40 β Europe/Astrakhan β 23:13:40 β
β 2023-09-08 19:13:40 β Europe/Athens β 22:13:40 β
β 2023-09-08 19:13:40 β Europe/Belfast β 20:13:40 β
β 2023-09-08 19:13:40 β Europe/Belgrade β 21:13:40 β
β 2023-09-08 19:13:40 β Europe/Berlin β 21:13:40 β
β 2023-09-08 19:13:40 β Europe/Bratislava β 21:13:40 β
β 2023-09-08 19:13:40 β Europe/Brussels β 21:13:40 β
β 2023-09-08 19:13:40 β Europe/Bucharest β 22:13:40 β
βββββββββββββββββββββββ΄ββββββββββββββββββββ΄ββββββββββββββ
formatDateTimeInJodaSyntax {#formatDateTimeInJodaSyntax}
Introduced in: v20.1
Similar to
formatDateTime
, except that it formats datetime in Joda style instead of MySQL style. Refer to
Joda Time documentation
.
The opposite operation of this function is
parseDateTimeInJodaSyntax
.
Using replacement fields, you can define a pattern for the resulting string.
Replacement fields: | {"source_file": "date-time-functions.md"} | [
0.06410744786262512,
-0.0082505838945508,
-0.0501469150185585,
0.05443244054913521,
-0.04431035742163658,
-0.011443974450230598,
-0.004324694629758596,
0.02737266570329666,
-0.02734399400651455,
-0.018752869218587875,
0.0029928633011877537,
-0.058548908680677414,
-0.0219448022544384,
-0.03... |
c6c1de88-d2f8-4720-8008-feeed25bde78 | The opposite operation of this function is
parseDateTimeInJodaSyntax
.
Using replacement fields, you can define a pattern for the resulting string.
Replacement fields:
| Placeholder | Description | Presentation | Examples |
|-------------|-------------|-------------|----------|
| G | era | text | AD |
| C | century of era (>=0) | number | 20 |
| Y | year of era (>=0) | year | 1996 |
| x | weekyear (not supported yet) | year | 1996 |
| w | week of weekyear (not supported yet) | number | 27 |
| e | day of week | number | 2 |
| E | day of week | text | Tuesday; Tue |
| y | year | year | 1996 |
| D | day of year | number | 189 |
| M | month of year | month | July; Jul; 07 |
| d | day of month | number | 10 |
| a | halfday of day | text | PM |
| K | hour of halfday (0~11) | number | 0 |
| h | clockhour of halfday (1~12) | number | 12 |
| H | hour of day (0~23) | number | 0 |
| k | clockhour of day (1~24) | number | 24 |
| m | minute of hour | number | 30 |
| s | second of minute | number | 55 |
| S | fraction of second | number | 978 |
| z | time zone | text | Eastern Standard Time; EST |
| Z | time zone offset | zone | -0800; -0812 |
| ' | escape for text | delimiter | |
| '' | single quote | literal | ' |
Syntax
sql
formatDateTimeInJodaSyntax(datetime, format[, timezone])
Arguments
datetime
β A date or date time to format.
DateTime
or
Date
or
Date32
or
DateTime64
format
β Format string with Joda-style replacement fields.
String
timezone
β Optional. Timezone name for the formatted time.
String
Returned value
Returns time and date values according to the determined format.
String
Examples
Format datetime using Joda syntax
sql title=Query
SELECT formatDateTimeInJodaSyntax(toDateTime('2010-01-04 12:34:56'), 'yyyy-MM-dd HH:mm:ss')
response title=Response
ββformatDateTimeInJodaSyntax(toDateTime('2010-01-04 12:34:56'), 'yyyy-MM-dd HH:mm:ss')ββ
β 2010-01-04 12:34:56 β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
fromDaysSinceYearZero {#fromDaysSinceYearZero}
Introduced in: v23.11
For a given number of days elapsed since
1 January 0000
, returns the corresponding date in the
proleptic Gregorian calendar defined by ISO 8601
.
The calculation is the same as in MySQL's
FROM_DAYS()
function. The result is undefined if it cannot be represented within the bounds of the
Date
type.
Syntax
sql
fromDaysSinceYearZero(days)
Aliases
:
FROM_DAYS
Arguments
days
β The number of days passed since year zero.
UInt32
Returned value
Returns the date corresponding to the number of days passed since year zero.
Date
Examples
Convert days since year zero to dates
sql title=Query
SELECT
fromDaysSinceYearZero(739136) AS date1,
fromDaysSinceYearZero(toDaysSinceYearZero(toDate('2023-09-08'))) AS date2 | {"source_file": "date-time-functions.md"} | [
0.01698252186179161,
0.07652264088392258,
0.054870449006557465,
0.018069051206111908,
-0.06927622109651566,
0.06260430067777634,
-0.04292001947760582,
0.005189078859984875,
-0.06470969319343567,
-0.035800788551568985,
-0.01826167106628418,
-0.10580895096063614,
-0.055791351944208145,
-0.03... |
ae58358f-3fce-469a-989b-772e5ce74db4 | Examples
Convert days since year zero to dates
sql title=Query
SELECT
fromDaysSinceYearZero(739136) AS date1,
fromDaysSinceYearZero(toDaysSinceYearZero(toDate('2023-09-08'))) AS date2
response title=Response
βββββββdate1ββ¬ββββββdate2ββ
β 2023-09-08 β 2023-09-08 β
ββββββββββββββ΄βββββββββββββ
fromDaysSinceYearZero32 {#fromDaysSinceYearZero32}
Introduced in: v23.11
For a given number of days elapsed since
1 January 0000
, returns the corresponding date in the
proleptic Gregorian calendar defined by ISO 8601
.
The calculation is the same as in MySQL's
FROM_DAYS()
function. The result is undefined if it cannot be represented within the bounds of the
Date32
type.
Syntax
sql
fromDaysSinceYearZero32(days)
Arguments
days
β The number of days passed since year zero.
UInt32
Returned value
Returns the date corresponding to the number of days passed since year zero.
Date32
Examples
Convert days since year zero to dates
sql title=Query
SELECT
fromDaysSinceYearZero32(739136) AS date1,
fromDaysSinceYearZero32(toDaysSinceYearZero(toDate('2023-09-08'))) AS date2
response title=Response
βββββββdate1ββ¬ββββββdate2ββ
β 2023-09-08 β 2023-09-08 β
ββββββββββββββ΄βββββββββββββ
fromModifiedJulianDay {#fromModifiedJulianDay}
Introduced in: v21.1
Converts a
Modified Julian Day
number to a
Proleptic Gregorian calendar
date in text form
YYYY-MM-DD
. This function supports day number from
-678941
to
2973483
(which represent 0000-01-01 and 9999-12-31 respectively). It raises an exception if the day number is outside of the supported range.
Syntax
sql
fromModifiedJulianDay(day)
Arguments
day
β Modified Julian Day number.
(U)Int*
Returned value
Returns date in text form.
String
Examples
Convert Modified Julian Day to date
sql title=Query
SELECT fromModifiedJulianDay(58849)
response title=Response
ββfromModifiedJulianDay(58849)ββ
β 2020-01-01 β
ββββββββββββββββββββββββββββββββ
fromModifiedJulianDayOrNull {#fromModifiedJulianDayOrNull}
Introduced in: v21.1
Similar to
fromModifiedJulianDay()
, but instead of raising exceptions it returns
NULL
.
Syntax
sql
fromModifiedJulianDayOrNull(day)
Arguments
day
β Modified Julian Day number.
(U)Int*
Returned value
Returns date in text form for valid
day
argument, otherwise
null
.
Nullable(String)
Examples
Convert Modified Julian Day to date with null handling
sql title=Query
SELECT fromModifiedJulianDayOrNull(58849);
SELECT fromModifiedJulianDayOrNull(60000000); -- invalid argument, returns NULL
response title=Response
ββfromModifiedβ―Null(58849)ββ
β 2020-01-01 β
ββββββββββββββββββββββββββββ
ββfromModifiedβ―l(60000000)ββ
β α΄Ία΅α΄Έα΄Έ β
ββββββββββββββββββββββββββββ
fromUTCTimestamp {#fromUTCTimestamp}
Introduced in: v22.1 | {"source_file": "date-time-functions.md"} | [
-0.006306370720267296,
0.04641358181834221,
-0.014563411474227905,
0.06401929259300232,
-0.10360120236873627,
-0.03764693811535835,
0.00156048231292516,
0.0637228786945343,
-0.07281437516212463,
-0.031689517199993134,
0.0009940552990883589,
-0.13704097270965576,
0.030355332419276237,
-0.00... |
af474f83-d911-4926-a630-48b2665e4db2 | fromUTCTimestamp {#fromUTCTimestamp}
Introduced in: v22.1
Converts a date or date with time value from UTC timezone to a date or date with time value with the specified time zone. This function is mainly included for compatibility with Apache Spark and similar frameworks.
Syntax
sql
fromUTCTimestamp(datetime, time_zone)
Aliases
:
from_utc_timestamp
Arguments
datetime
β A date or date with time const value or an expression.
DateTime
or
DateTime64
time_zone
β A String type const value or an expression representing the time zone.
String
Returned value
Returns DateTime/DateTime64 in the specified timezone.
DateTime
or
DateTime64
Examples
Convert UTC timezone to specified timezone
sql title=Query
SELECT fromUTCTimestamp(toDateTime64('2023-03-16 10:00:00', 3), 'Asia/Shanghai')
response title=Response
ββfromUTCTimestamp(toDateTime64('2023-03-16 10:00:00',3), 'Asia/Shanghai')ββ
β 2023-03-16 18:00:00.000 β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
fromUnixTimestamp {#fromUnixTimestamp}
Introduced in: v20.8
This function converts a Unix timestamp to a calendar date and a time of a day.
It can be called in two ways:
When given a single argument of type
Integer
, it returns a value of type
DateTime
, i.e. behaves like
toDateTime
.
When given two or three arguments where the first argument is a value of type
Integer
,
Date
,
Date32
,
DateTime
or
DateTime64
, the second argument is a constant format string and the third argument is an optional constant time zone string, the function returns a value of type
String
, i.e. it behaves like
formatDateTime
.
In this case,
MySQL's datetime format style
is used.
Syntax
sql
fromUnixTimestamp(timestamp)
fromUnixTimestamp(timestamp[, format[, timezone]])
Aliases
:
FROM_UNIXTIME
Arguments
timestamp
β Unix timestamp or date/date with time value.
(U)Int*
or
Date
or
Date32
or
DateTime
or
DateTime64
format
β Optional. Constant format string for output formatting.
String
timezone
β Optional. Constant time zone string.
String
Returned value
Returns
DateTime
of the timestamp when called with one argument, or a String when called with two or three arguments.
DateTime
or
String
Examples
Convert Unix timestamp to DateTime
sql title=Query
SELECT fromUnixTimestamp(423543535)
response title=Response
ββfromUnixTimestamp(423543535)ββ
β 1983-06-04 10:58:55 β
ββββββββββββββββββββββββββββββββ
Convert Unix timestamp with format
sql title=Query
SELECT fromUnixTimestamp(1234334543, '%Y-%m-%d %R:%S') AS DateTime
response title=Response
ββDateTimeβββββββββββββ
β 2009-02-11 14:42:23 β
βββββββββββββββββββββββ
fromUnixTimestampInJodaSyntax {#fromUnixTimestampInJodaSyntax}
Introduced in: v23.1
This function converts a Unix timestamp to a calendar date and a time of a day.
It can be called in two ways: | {"source_file": "date-time-functions.md"} | [
0.0058148265816271305,
-0.0013699809787794948,
-0.03364970162510872,
0.01770772598683834,
0.022751523181796074,
-0.013655115850269794,
0.028993038460612297,
0.039426758885383606,
0.003766933223232627,
0.009237934835255146,
-0.004867365583777428,
-0.12367258965969086,
-0.07972609251737595,
... |
f01d26b6-2216-4182-ba74-2e4afc0e570a | Introduced in: v23.1
This function converts a Unix timestamp to a calendar date and a time of a day.
It can be called in two ways:
When given a single argument of type
Integer
, it returns a value of type
DateTime
, i.e. behaves like
toDateTime
.
When given two or three arguments where the first argument is a value of type
Integer
,
Date
,
Date32
,
DateTime
or
DateTime64
, the second argument is a constant format string and the third argument is an optional constant time zone string, the function returns a value of type
String
, i.e. it behaves like
formatDateTimeInJodaSyntax
. In this case,
Joda datetime format style
is used.
Syntax
sql
fromUnixTimestampInJodaSyntax(timestamp)
fromUnixTimestampInJodaSyntax(timestamp, format[, timezone])
Arguments
timestamp
β Unix timestamp or date/time value.
(U)Int*
or
Date
or
Date32
or
DateTime
or
DateTime64
format
β Optional. Constant format string using Joda syntax for output formatting.
String
timezone
β Optional. Constant time zone string.
String
Returned value
Returns a date with time when called with one argument, or a String when called with two or three arguments.}
DateTime
or
String
Examples
Convert Unix timestamp with Joda format
sql title=Query
SELECT fromUnixTimestampInJodaSyntax(1234334543, 'yyyy-MM-dd HH:mm:ss', 'UTC') AS DateTime
response title=Response
ββDateTimeβββββββββββββ
β 2009-02-11 06:42:23 β
βββββββββββββββββββββββ
makeDate {#makeDate}
Introduced in: v22.6
Creates a
Date
from either:
- a year, month and day
- a year and day of year
Syntax
sql
makeDate(year, month, day)
makeDate(year, day_of_year)
Arguments
year
β Year number.
(U)Int*
or
Float*
or
Decimal
month
β Month number (1-12).
(U)Int*
or
Float*
or
Decimal
day
β Day of the month (1-31).
(U)Int*
or
Float*
or
Decimal
day_of_year
β Day of the year (1-365).
(U)Int*
or
Float*
or
Decimal
Returned value
Returns a
Date
value constructed from the provided arguments
Date
Examples
Date from a year, month, day
sql title=Query
SELECT makeDate(2023, 2, 28) AS date;
response title=Response
ββββββββdateββ
β 2023-02-28 β
ββββββββββββββ
Date from year and day of year
sql title=Query
SELECT makeDate(2023, 42) AS date;
response title=Response
ββββββββdateββ
β 2023-02-11 β
ββββββββββββββ
makeDate32 {#makeDate32}
Introduced in: v22.6
Creates a
Date32
from either:
- a year, month and day
- a year and day of year
Syntax
sql
makeDate32(year, month, day)
makeDate32(year, day_of_year)
Arguments
year
β Year number.
(U)Int*
or
Float*
or
Decimal
month
β Month number (1-12).
(U)Int*
or
Float*
or
Decimal
day
β Day of the month (1-31).
(U)Int*
or
Float*
or
Decimal
day_of_year
β Day of the year (1-365).
(U)Int*
or
Float*
or
Decimal
Returned value
Returns a
Date32
value constructed from the provided arguments
Date32
Examples
Date32 from a year, month, day | {"source_file": "date-time-functions.md"} | [
0.01438522431999445,
0.061267632991075516,
-0.05208491533994675,
0.015438073314726353,
0.004769227933138609,
0.01619209162890911,
0.01578289084136486,
0.07234791666269302,
0.025521857663989067,
-0.046383824199438095,
-0.0618511326611042,
-0.08069624751806259,
-0.043512776494026184,
-0.0310... |
702d11fe-c8af-4e08-b280-fb089c1a928b | Returned value
Returns a
Date32
value constructed from the provided arguments
Date32
Examples
Date32 from a year, month, day
sql title=Query
SELECT makeDate(2023, 2, 28) AS date;
response title=Response
ββββββββdateββ
β 2023-02-28 β
ββββββββββββββ
Date32 from year and day of year
sql title=Query
SELECT makeDate(2023, 42) AS date;
response title=Response
ββββββββdateββ
β 2023-02-11 β
ββββββββββββββ
makeDateTime {#makeDateTime}
Introduced in: v22.6
Creates a
DateTime
from year, month, day, hour, minute, and second, with optional timezone.
Syntax
sql
makeDateTime(year, month, day, hour, minute, second[, timezone])
Arguments
year
β Year number.
(U)Int*
or
Float*
or
Decimal
month
β Month number (1-12).
(U)Int*
or
Float*
or
Decimal
day
β Day of the month (1-31).
(U)Int*
or
Float*
or
Decimal
hour
β Hour (0-23).
(U)Int*
or
Float*
or
Decimal
minute
β Minute (0-59).
(U)Int*
or
Float*
or
Decimal
second
β Second (0-59).
(U)Int*
or
Float*
or
Decimal
timezone
β Timezone name.
String
Returned value
Returns a
DateTime
value constructed from the provided arguments
DateTime
Examples
DateTime from year, month, day, hour, minute, second
sql title=Query
SELECT makeDateTime(2023, 2, 28, 17, 12, 33) AS DateTime;
response title=Response
βββββββββββββDateTimeββ
β 2023-02-28 17:12:33 β
βββββββββββββββββββββββ
makeDateTime64 {#makeDateTime64}
Introduced in: v22.6
Creates a
DateTime64
from year, month, day, hour, minute, second, with optional fraction, precision, and timezone.
Syntax
sql
makeDateTime64(year, month, day, hour, minute, second[, fraction[, precision[, timezone]]])
Arguments
year
β Year number.
(U)Int*
or
Float*
or
Decimal
month
β Month number (1-12).
(U)Int*
or
Float*
or
Decimal
day
β Day of the month (1-31).
(U)Int*
or
Float*
or
Decimal
hour
β Hour (0-23).
(U)Int*
or
Float*
or
Decimal
minute
β Minute (0-59).
(U)Int*
or
Float*
or
Decimal
second
β Second (0-59).
(U)Int*
or
Float*
or
Decimal
fraction
β Fractional part of the second.
(U)Int*
or
Float*
or
Decimal
precision
β Precision for the fractional part (0-9).
UInt8
timezone
β Timezone name.
String
Returned value
Returns a
DateTime64
value constructed from the provided arguments
DateTime64
Examples
DateTime64 from year, month, day, hour, minute, second
sql title=Query
SELECT makeDateTime64(2023, 5, 15, 10, 30, 45, 779, 5);
response title=Response
ββmakeDateTime64(2023, 5, 15, 10, 30, 45, 779, 5)ββ
β 2023-05-15 10:30:45.00779 β
βββββββββββββββββββββββββββββββββββββββββββββββββββ
monthName {#monthName}
Introduced in: v22.1
Returns the name of the month as a string from a date or date with time value.
Syntax
sql
monthName(datetime)
Arguments
datetime
β Date or date with time.
Date
or
Date32
or
DateTime
or
DateTime64
Returned value | {"source_file": "date-time-functions.md"} | [
0.00618298863992095,
0.028991352766752243,
-0.04733828827738762,
0.06697218120098114,
-0.07031978666782379,
-0.06321361660957336,
0.009449897333979607,
0.010552446357905865,
-0.019504573196172714,
0.02354723960161209,
-0.023658137768507004,
-0.11350881308317184,
-0.0016079688211902976,
-0.... |
847caaed-86a3-4777-9ede-1c0e7da94746 | Syntax
sql
monthName(datetime)
Arguments
datetime
β Date or date with time.
Date
or
Date32
or
DateTime
or
DateTime64
Returned value
Returns the name of the month.
String
Examples
Get month name from date
sql title=Query
WITH toDateTime('2021-04-14 11:22:33') AS date_value
SELECT monthName(date_value)
response title=Response
ββmonthName(date_value)ββ
β April β
βββββββββββββββββββββββββ
now {#now}
Introduced in: v1.1
Returns the current date and time at the moment of query analysis. The function is a constant expression.
Syntax
sql
now([timezone])
Aliases
:
current_timestamp
Arguments
timezone
β Optional. Timezone name for the returned value.
String
Returned value
Returns the current date and time.
DateTime
Examples
Query without timezone
sql title=Query
SELECT now()
response title=Response
ββββββββββββββββnow()ββ
β 2020-10-17 07:42:09 β
βββββββββββββββββββββββ
Query with specified timezone
sql title=Query
SELECT now('Asia/Istanbul')
response title=Response
ββnow('Asia/Istanbul')ββ
β 2020-10-17 10:42:23 β
ββββββββββββββββββββββββ
now64 {#now64}
Introduced in: v20.1
Returns the current date and time with sub-second precision at the moment of query analysis. The function is a constant expression.
Syntax
sql
now64([scale], [timezone])
Arguments
scale
β Optional. Tick size (precision): 10^-precision seconds. Valid range: [0 : 9]. Typically, are used - 3 (default) (milliseconds), 6 (microseconds), 9 (nanoseconds).
UInt8
timezone
β Optional. Timezone name for the returned value.
String
Returned value
Returns current date and time with sub-second precision.
DateTime64
Examples
Query with default and custom precision
sql title=Query
SELECT now64(), now64(9, 'Asia/Istanbul')
response title=Response
ββββββββββββββββββnow64()ββ¬βββββnow64(9, 'Asia/Istanbul')ββ
β 2022-08-21 19:34:26.196 β 2022-08-21 22:34:26.196542766 β
βββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ
nowInBlock {#nowInBlock}
Introduced in: v22.8
Returns the current date and time at the moment of processing of each block of data. In contrast to the function
now
, it is not a constant expression, and the returned value will be different in different blocks for long-running queries.
It makes sense to use this function to generate the current time in long-running
INSERT SELECT
queries.
Syntax
sql
nowInBlock([timezone])
Arguments
timezone
β Optional. Timezone name for the returned value.
String
Returned value
Returns the current date and time at the moment of processing of each block of data.
DateTime
Examples
Difference with the now() function
sql title=Query
SELECT
now(),
nowInBlock(),
sleep(1)
FROM numbers(3)
SETTINGS max_block_size = 1
FORMAT PrettyCompactMonoBlock | {"source_file": "date-time-functions.md"} | [
0.0014540759148076177,
-0.008846884593367577,
-0.09117911756038666,
0.07028862833976746,
-0.02214450016617775,
-0.06135089322924614,
0.03892708942294121,
0.011361449025571346,
0.014896776527166367,
0.02224140428006649,
0.008865823037922382,
-0.058820631355047226,
-0.05348389968276024,
0.01... |
04474270-e98a-4877-86e5-9f0f59be85ed | Examples
Difference with the now() function
sql title=Query
SELECT
now(),
nowInBlock(),
sleep(1)
FROM numbers(3)
SETTINGS max_block_size = 1
FORMAT PrettyCompactMonoBlock
response title=Response
ββββββββββββββββnow()ββ¬ββββββββnowInBlock()ββ¬βsleep(1)ββ
β 2022-08-21 19:41:19 β 2022-08-21 19:41:19 β 0 β
β 2022-08-21 19:41:19 β 2022-08-21 19:41:20 β 0 β
β 2022-08-21 19:41:19 β 2022-08-21 19:41:21 β 0 β
βββββββββββββββββββββββ΄ββββββββββββββββββββββ΄βββββββββββ
nowInBlock64 {#nowInBlock64}
Introduced in: v25.8
Returns the current date and time at the moment of processing of each block of data in milliseconds. In contrast to the function
now64
, it is not a constant expression, and the returned value will be different in different blocks for long-running queries.
It makes sense to use this function to generate the current time in long-running INSERT SELECT queries.
Syntax
sql
nowInBlock([scale[, timezone]])
Arguments
scale
β Optional. Tick size (precision): 10^-precision seconds. Valid range: [0 : 9]. Typically, are used - 3 (default) (milliseconds), 6 (microseconds), 9 (nanoseconds).
UInt8
timezone
β Optional. Timezone name for the returned value.
String
Returned value
Returns the current date and time at the moment of processing of each block of data with sub-second precision.
DateTime64
Examples
Difference with the now64() function
sql title=Query
SELECT
now64(),
nowInBlock64(),
sleep(1)
FROM numbers(3)
SETTINGS max_block_size = 1
FORMAT PrettyCompactMonoBlock
response title=Response
ββββββββββββββββββnow64()ββ¬ββββββββββnowInBlock64()ββ¬βsleep(1)ββ
β 2025-07-29 17:07:29.526 β 2025-07-29 17:07:29.534 β 0 β
β 2025-07-29 17:07:29.526 β 2025-07-29 17:07:30.535 β 0 β
β 2025-07-29 17:07:29.526 β 2025-07-29 17:07:31.535 β 0 β
βββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββ΄βββββββββββ
serverTimezone {#serverTimezone}
Introduced in: v23.6
Returns the timezone of the server, i.e. the value of the
timezone
setting.
If the function is executed in the context of a distributed table, then it generates a normal column with values relevant to each shard. Otherwise, it produces a constant value.
Syntax
sql
serverTimeZone()
Aliases
:
serverTimeZone
Arguments
None.
Returned value
Returns the server timezone as a
String
Examples
Usage example
sql title=Query
SELECT serverTimeZone()
response title=Response
ββserverTimeZone()ββ
β UTC β
ββββββββββββββββββββ
subDate {#subDate}
Introduced in: v23.9
Subtracts the time interval from the provided date, date with time or string-encoded date or date with time.
If the subtraction results in a value outside the bounds of the data type, the result is undefined.
Syntax
sql
subDate(datetime, interval)
Arguments
datetime
β The date or date with time from which
interval
is subtracted.
Date
or
Date32
or
DateTime
or
DateTime64 | {"source_file": "date-time-functions.md"} | [
-0.05269663780927658,
0.013550357893109322,
-0.03633493930101395,
0.07248060405254364,
0.008325599133968353,
-0.045906685292720795,
-0.0369514636695385,
0.013000545091927052,
0.036746442317962646,
0.005383637733757496,
-0.0026967802550643682,
-0.008370461873710155,
-0.06656983494758606,
-0... |
f37281bf-0857-4af6-8249-2cf34a229307 | Syntax
sql
subDate(datetime, interval)
Arguments
datetime
β The date or date with time from which
interval
is subtracted.
Date
or
Date32
or
DateTime
or
DateTime64
interval
β Interval to subtract.
Interval
Returned value
Returns date or date with time obtained by subtracting
interval
from
datetime
.
Date
or
Date32
or
DateTime
or
DateTime64
Examples
Subtract interval from date
sql title=Query
SELECT subDate(toDate('2018-01-01'), INTERVAL 3 YEAR)
response title=Response
ββsubDate(toDate('2018-01-01'), toIntervalYear(3))ββ
β 2015-01-01 β
ββββββββββββββββββββββββββββββββββββββββββββββββββββ
subtractDays {#subtractDays}
Introduced in: v1.1
Subtracts a specified number of days from a date, a date with time or a string-encoded date or date with time.
Syntax
sql
subtractDays(datetime, num)
Arguments
datetime
β Date or date with time to subtract specified number of days from.
Date
or
Date32
or
DateTime
or
DateTime64
or
String
num
β Number of days to subtract.
(U)Int*
or
Float*
Returned value
Returns
datetime
minus
num
days
Date
or
Date32
or
DateTime
or
DateTime64
Examples
Subtract days from different date types
sql title=Query
WITH
toDate('2024-01-01') AS date,
toDateTime('2024-01-01 00:00:00') AS date_time,
'2024-01-01 00:00:00' AS date_time_string
SELECT
subtractDays(date, 31) AS subtract_days_with_date,
subtractDays(date_time, 31) AS subtract_days_with_date_time,
subtractDays(date_time_string, 31) AS subtract_days_with_date_time_string
response title=Response
ββsubtract_days_with_dateββ¬βsubtract_days_with_date_timeββ¬βsubtract_days_with_date_time_stringββ
β 2023-12-01 β 2023-12-01 00:00:00 β 2023-12-01 00:00:00.000 β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββ
Using alternative INTERVAL syntax
sql title=Query
SELECT dateSub('1998-06-16'::Date, INTERVAL 10 day)
response title=Response
ββminus(CAST('β―valDay(10))ββ
β 1998-06-06 β
ββββββββββββββββββββββββββββ
subtractHours {#subtractHours}
Introduced in: v1.1
Subtracts a specified number of hours from a date, a date with time or a string-encoded date or date with time.
Syntax
sql
subtractHours(datetime, num)
Arguments
datetime
β Date or date with time to subtract specified number of hours from.
Date
or
Date32
or
DateTime
or
DateTime64
or
String
num
β Number of hours to subtract.
(U)Int*
or
Float*
Returned value
Returns
datetime
minus
num
hours
DateTime
or
DateTime64(3)
Examples
Subtract hours from different date types | {"source_file": "date-time-functions.md"} | [
-0.02838023193180561,
0.053910840302705765,
0.003355212975293398,
0.07616601884365082,
-0.04576859995722771,
-0.04098908230662346,
0.030410699546337128,
0.044427841901779175,
-0.035818420350551605,
-0.0419258251786232,
0.0034123973455280066,
-0.12220171838998795,
0.036651451140642166,
0.03... |
eb7de984-8f2e-4ae3-b1bd-230603bacb7f | num
β Number of hours to subtract.
(U)Int*
or
Float*
Returned value
Returns
datetime
minus
num
hours
DateTime
or
DateTime64(3)
Examples
Subtract hours from different date types
sql title=Query
WITH
toDate('2024-01-01') AS date,
toDateTime('2024-01-01 00:00:00') AS date_time,
'2024-01-01 00:00:00' AS date_time_string
SELECT
subtractHours(date, 12) AS subtract_hours_with_date,
subtractHours(date_time, 12) AS subtract_hours_with_date_time,
subtractHours(date_time_string, 12) AS subtract_hours_with_date_time_string
response title=Response
ββsubtract_hours_with_dateββ¬βsubtract_hours_with_date_timeββ¬βsubtract_hours_with_date_time_stringββ
β 2023-12-31 12:00:00 β 2023-12-31 12:00:00 β 2023-12-31 12:00:00.000 β
ββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββ
Using alternative INTERVAL syntax
sql title=Query
SELECT dateSub('1998-06-16'::Date, INTERVAL 10 hour)
response title=Response
ββminus(CAST('β―alHour(10))ββ
β 1998-06-15 14:00:00 β
ββββββββββββββββββββββββββββ
subtractInterval {#subtractInterval}
Introduced in: v22.11
Adds a negated interval to another interval or tuple of intervals.
Note: Intervals of the same type will be combined into a single interval. For instance if
toIntervalDay(2)
and
toIntervalDay(1)
are
passed then the result will be
(1)
rather than
(2,1)
.
Syntax
sql
subtractInterval(interval_1, interval_2)
Arguments
interval_1
β First interval or interval of tuples.
Interval
or
Tuple(Interval)
interval_2
β Second interval to be negated.
Interval
Returned value
Returns a tuple of intervals
Tuple(T)
Examples
Subtract intervals
sql title=Query
SELECT subtractInterval(INTERVAL 1 DAY, INTERVAL 1 MONTH);
SELECT subtractInterval((INTERVAL 1 DAY, INTERVAL 1 YEAR), INTERVAL 1 MONTH);
SELECT subtractInterval(INTERVAL 2 DAY, INTERVAL 1 DAY);
response title=Response
ββsubtractInterval(toIntervalDay(1), toIntervalMonth(1))ββ
β (1,-1) β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ββsubtractInterval((toIntervalDay(1), toIntervalYear(1)), toIntervalMonth(1))ββ
β (1,1,-1) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ββsubtractInterval(toIntervalDay(2), toIntervalDay(1))ββ
β (1) β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
subtractMicroseconds {#subtractMicroseconds}
Introduced in: v22.6
Subtracts a specified number of microseconds from a date with time or a string-encoded date with time.
Syntax
sql
subtractMicroseconds(datetime, num)
Arguments
datetime
β Date with time to subtract specified number of microseconds from.
DateTime
or
DateTime64
or
String
num
β Number of microseconds to subtract.
(U)Int*
or
Float* | {"source_file": "date-time-functions.md"} | [
0.025545751675963402,
0.07644805312156677,
0.007447245996445417,
0.07180222123861313,
-0.009458668529987335,
-0.0790744349360466,
0.006000400520861149,
0.04063943028450012,
-0.02858281135559082,
-0.027179650962352753,
-0.03263165429234505,
-0.13808253407478333,
-0.012109755538403988,
0.020... |
3d781767-f91f-4e0c-834e-f2db06fb8b7c | Arguments
datetime
β Date with time to subtract specified number of microseconds from.
DateTime
or
DateTime64
or
String
num
β Number of microseconds to subtract.
(U)Int*
or
Float*
Returned value
Returns
datetime
minus
num
microseconds
DateTime64
Examples
Subtract microseconds from different date time types
sql title=Query
WITH
toDateTime('2024-01-01 00:00:00') AS date_time,
'2024-01-01 00:00:00' AS date_time_string
SELECT
subtractMicroseconds(date_time, 1000000) AS subtract_microseconds_with_date_time,
subtractMicroseconds(date_time_string, 1000000) AS subtract_microseconds_with_date_time_string
response title=Response
ββsubtract_microseconds_with_date_timeββ¬βsubtract_microseconds_with_date_time_stringββ
β 2023-12-31 23:59:59.000000 β 2023-12-31 23:59:59.000000 β
ββββββββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββ
Using alternative INTERVAL syntax
sql title=Query
SELECT dateSub('1998-06-16'::DateTime, INTERVAL 10 microsecond)
response title=Response
ββminus(CAST('1β―osecond(10))ββ
β 1998-06-15 23:59:59.999990 β
ββββββββββββββββββββββββββββββ
subtractMilliseconds {#subtractMilliseconds}
Introduced in: v22.6
Subtracts a specified number of milliseconds from a date with time or a string-encoded date with time.
Syntax
sql
subtractMilliseconds(datetime, num)
Arguments
datetime
β Date with time to subtract specified number of milliseconds from.
DateTime
or
DateTime64
or
String
num
β Number of milliseconds to subtract.
(U)Int*
or
Float*
Returned value
Returns
datetime
minus
num
milliseconds
DateTime64
Examples
Subtract milliseconds from different date time types
sql title=Query
WITH
toDateTime('2024-01-01 00:00:00') AS date_time,
'2024-01-01 00:00:00' AS date_time_string
SELECT
subtractMilliseconds(date_time, 1000) AS subtract_milliseconds_with_date_time,
subtractMilliseconds(date_time_string, 1000) AS subtract_milliseconds_with_date_time_string
response title=Response
ββsubtract_milliseconds_with_date_timeββ¬βsubtract_milliseconds_with_date_time_stringββ
β 2023-12-31 23:59:59.000 β 2023-12-31 23:59:59.000 β
ββββββββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββ
Using alternative INTERVAL syntax
sql title=Query
SELECT dateSub('1998-06-16'::DateTime, INTERVAL 10 millisecond)
response title=Response
ββminus(CAST('β―second(10))ββ
β 1998-06-15 23:59:59.990 β
ββββββββββββββββββββββββββββ
subtractMinutes {#subtractMinutes}
Introduced in: v1.1
Subtracts a specified number of minutes from a date, a date with time or a string-encoded date or date with time.
Syntax
sql
subtractMinutes(datetime, num)
Arguments
datetime
β Date or date with time to subtract specified number of minutes from.
Date
or
Date32
or
DateTime
or
DateTime64
or
String | {"source_file": "date-time-functions.md"} | [
0.03842606022953987,
0.053580399602651596,
-0.022840889170765877,
0.06011911854147911,
-0.002831055549904704,
-0.039601679891347885,
0.018535159528255463,
0.08934802561998367,
0.007055919151753187,
-0.026315268129110336,
-0.018038012087345123,
-0.15169797837734222,
-0.02422134205698967,
0.... |
9fb3bca2-e731-4f1c-8deb-45533b108106 | sql
subtractMinutes(datetime, num)
Arguments
datetime
β Date or date with time to subtract specified number of minutes from.
Date
or
Date32
or
DateTime
or
DateTime64
or
String
num
β Number of minutes to subtract.
(U)Int*
or
Float*
Returned value
Returns
datetime
minus
num
minutes
DateTime
or
DateTime64(3)
Examples
Subtract minutes from different date types
sql title=Query
WITH
toDate('2024-01-01') AS date,
toDateTime('2024-01-01 00:00:00') AS date_time,
'2024-01-01 00:00:00' AS date_time_string
SELECT
subtractMinutes(date, 30) AS subtract_minutes_with_date,
subtractMinutes(date_time, 30) AS subtract_minutes_with_date_time,
subtractMinutes(date_time_string, 30) AS subtract_minutes_with_date_time_string
response title=Response
ββsubtract_minutes_with_dateββ¬βsubtract_minutes_with_date_timeββ¬βsubtract_minutes_with_date_time_stringββ
β 2023-12-31 23:30:00 β 2023-12-31 23:30:00 β 2023-12-31 23:30:00.000 β
ββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββ
Using alternative INTERVAL syntax
sql title=Query
SELECT dateSub('1998-06-16'::Date, INTERVAL 10 minute)
response title=Response
ββminus(CAST('β―Minute(10))ββ
β 1998-06-15 23:50:00 β
ββββββββββββββββββββββββββββ
subtractMonths {#subtractMonths}
Introduced in: v1.1
Subtracts a specified number of months from a date, a date with time or a string-encoded date or date with time.
Syntax
sql
subtractMonths(datetime, num)
Arguments
datetime
β Date or date with time to subtract specified number of months from.
Date
or
Date32
or
DateTime
or
DateTime64
or
String
num
β Number of months to subtract.
(U)Int*
or
Float*
Returned value
Returns
datetime
minus
num
months
Date
or
Date32
or
DateTime
or
DateTime64
Examples
Subtract months from different date types
sql title=Query
WITH
toDate('2024-01-01') AS date,
toDateTime('2024-01-01 00:00:00') AS date_time,
'2024-01-01 00:00:00' AS date_time_string
SELECT
subtractMonths(date, 1) AS subtract_months_with_date,
subtractMonths(date_time, 1) AS subtract_months_with_date_time,
subtractMonths(date_time_string, 1) AS subtract_months_with_date_time_string
response title=Response
ββsubtract_months_with_dateββ¬βsubtract_months_with_date_timeββ¬βsubtract_months_with_date_time_stringββ
β 2023-12-01 β 2023-12-01 00:00:00 β 2023-12-01 00:00:00.000 β
βββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββ
Using alternative INTERVAL syntax
sql title=Query
SELECT dateSub('1998-06-16'::Date, INTERVAL 10 month)
response title=Response
ββminus(CAST('β―lMonth(10))ββ
β 1997-08-16 β
ββββββββββββββββββββββββββββ
subtractNanoseconds {#subtractNanoseconds}
Introduced in: v20.1 | {"source_file": "date-time-functions.md"} | [
0.04239952936768532,
0.09123259037733078,
-0.028426866978406906,
0.03910818323493004,
-0.00585523247718811,
-0.01807338371872902,
0.03643880784511566,
0.07433284819126129,
-0.009414843283593655,
-0.022626105695962906,
-0.014268007129430771,
-0.16251923143863678,
0.01355911698192358,
0.0569... |
6432ba7e-94ca-4f26-8cc7-1a8e3f2b1270 | response title=Response
ββminus(CAST('β―lMonth(10))ββ
β 1997-08-16 β
ββββββββββββββββββββββββββββ
subtractNanoseconds {#subtractNanoseconds}
Introduced in: v20.1
Subtracts a specified number of nanoseconds from a date with time or a string-encoded date with time.
Syntax
sql
subtractNanoseconds(datetime, num)
Arguments
datetime
β Date with time to subtract specified number of nanoseconds from.
DateTime
or
DateTime64
or
String
num
β Number of nanoseconds to subtract.
(U)Int*
or
Float*
Returned value
Returns
datetime
minus
num
nanoseconds
DateTime64
Examples
Subtract nanoseconds from different date time types
sql title=Query
WITH
toDateTime('2024-01-01 00:00:00') AS date_time,
'2024-01-01 00:00:00' AS date_time_string
SELECT
subtractNanoseconds(date_time, 1000) AS subtract_nanoseconds_with_date_time,
subtractNanoseconds(date_time_string, 1000) AS subtract_nanoseconds_with_date_time_string
response title=Response
ββsubtract_nanoseconds_with_date_timeββ¬βsubtract_nanoseconds_with_date_time_stringββ
β 2023-12-31 23:59:59.999999000 β 2023-12-31 23:59:59.999999000 β
βββββββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββ
Using alternative INTERVAL syntax
sql title=Query
SELECT dateSub('1998-06-16'::DateTime, INTERVAL 10 nanosecond)
response title=Response
ββminus(CAST('19β―anosecond(10))ββ
β 1998-06-15 23:59:59.999999990 β
βββββββββββββββββββββββββββββββββ
subtractQuarters {#subtractQuarters}
Introduced in: v20.1
Subtracts a specified number of quarters from a date, a date with time or a string-encoded date or date with time.
Syntax
sql
subtractQuarters(datetime, num)
Arguments
datetime
β Date or date with time to subtract specified number of quarters from.
Date
or
Date32
or
DateTime
or
DateTime64
or
String
num
β Number of quarters to subtract.
(U)Int*
or
Float*
Returned value
Returns
datetime
minus
num
quarters
Date
or
Date32
or
DateTime
or
DateTime64
Examples
Subtract quarters from different date types
sql title=Query
WITH
toDate('2024-01-01') AS date,
toDateTime('2024-01-01 00:00:00') AS date_time,
'2024-01-01 00:00:00' AS date_time_string
SELECT
subtractQuarters(date, 1) AS subtract_quarters_with_date,
subtractQuarters(date_time, 1) AS subtract_quarters_with_date_time,
subtractQuarters(date_time_string, 1) AS subtract_quarters_with_date_time_string
response title=Response
ββsubtract_quarters_with_dateββ¬βsubtract_quarters_with_date_timeββ¬βsubtract_quarters_with_date_time_stringββ
β 2023-10-01 β 2023-10-01 00:00:00 β 2023-10-01 00:00:00.000 β
βββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββ
Using alternative INTERVAL syntax
sql title=Query
SELECT dateSub('1998-06-16'::Date, INTERVAL 10 quarter) | {"source_file": "date-time-functions.md"} | [
0.015675868839025497,
0.03225484490394592,
0.019604694098234177,
0.05879998579621315,
-0.01967177540063858,
-0.03338726982474327,
0.041885245591402054,
0.09269344806671143,
-0.006147786974906921,
-0.0453239381313324,
-0.023219414055347443,
-0.1490963101387024,
-0.012405543588101864,
0.0398... |
45437d9e-9a76-453c-8af1-42838ac57e4d | Using alternative INTERVAL syntax
sql title=Query
SELECT dateSub('1998-06-16'::Date, INTERVAL 10 quarter)
response title=Response
ββminus(CAST('1β―Quarter(10))ββ
β 1996-09-16 β
βββββββββββββββββββββββββββββ
subtractSeconds {#subtractSeconds}
Introduced in: v1.1
Subtracts a specified number of seconds from a date, a date with time or a string-encoded date or date with time.
Syntax
sql
subtractSeconds(datetime, num)
Arguments
datetime
β Date or date with time to subtract specified number of seconds from.
Date
or
Date32
or
DateTime
or
DateTime64
or
String
num
β Number of seconds to subtract.
(U)Int*
or
Float*
Returned value
Returns
datetime
minus
num
seconds
DateTime
or
DateTime64(3)
Examples
Subtract seconds from different date types
sql title=Query
WITH
toDate('2024-01-01') AS date,
toDateTime('2024-01-01 00:00:00') AS date_time,
'2024-01-01 00:00:00' AS date_time_string
SELECT
subtractSeconds(date, 60) AS subtract_seconds_with_date,
subtractSeconds(date_time, 60) AS subtract_seconds_with_date_time,
subtractSeconds(date_time_string, 60) AS subtract_seconds_with_date_time_string
response title=Response
ββsubtract_seconds_with_dateββ¬βsubtract_seconds_with_date_timeββ¬βsubtract_seconds_with_date_time_stringββ
β 2023-12-31 23:59:00 β 2023-12-31 23:59:00 β 2023-12-31 23:59:00.000 β
ββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββ
Using alternative INTERVAL syntax
sql title=Query
SELECT dateSub('1998-06-16'::Date, INTERVAL 10 second)
response title=Response
ββminus(CAST('β―Second(10))ββ
β 1998-06-15 23:59:50 β
ββββββββββββββββββββββββββββ
subtractTupleOfIntervals {#subtractTupleOfIntervals}
Introduced in: v22.11
Consecutively subtracts a tuple of intervals from a date or a date with time.
Syntax
sql
subtractTupleOfIntervals(datetime, intervals)
Arguments
datetime
β Date or date with time to subtract intervals from.
Date
or
Date32
or
DateTime
or
DateTime64
intervals
β Tuple of intervals to subtract from
datetime
.
Tuple(Interval)
Returned value
Returns
date
with subtracted
intervals
Date
or
Date32
or
DateTime
or
DateTime64
Examples
Subtract tuple of intervals from date
sql title=Query
WITH toDate('2018-01-01') AS date SELECT subtractTupleOfIntervals(date, (INTERVAL 1 DAY, INTERVAL 1 YEAR))
response title=Response
ββsubtractTuplβ―alYear(1)))ββ
β 2016-12-31 β
ββββββββββββββββββββββββββββ
subtractWeeks {#subtractWeeks}
Introduced in: v1.1
Subtracts a specified number of weeks from a date, a date with time or a string-encoded date or date with time.
Syntax
sql
subtractWeeks(datetime, num)
Arguments
datetime
β Date or date with time to subtract specified number of weeks from.
Date
or
Date32
or
DateTime
or
DateTime64
or
String | {"source_file": "date-time-functions.md"} | [
0.008395063690841198,
0.04888876900076866,
0.0006442857556976378,
0.039095569401979446,
-0.04402228444814682,
0.002340540988370776,
0.031619906425476074,
0.08587145805358887,
0.008523805066943169,
-0.07953473180532455,
0.004777114372700453,
-0.11912615597248077,
0.0006864677416160703,
0.02... |
b09e3fa4-91cf-47f5-bd54-258bab80dcdb | Syntax
sql
subtractWeeks(datetime, num)
Arguments
datetime
β Date or date with time to subtract specified number of weeks from.
Date
or
Date32
or
DateTime
or
DateTime64
or
String
num
β Number of weeks to subtract.
(U)Int*
or
Float*
Returned value
Returns
datetime
minus
num
weeks
Date
or
Date32
or
DateTime
or
DateTime64
Examples
Subtract weeks from different date types
sql title=Query
WITH
toDate('2024-01-01') AS date,
toDateTime('2024-01-01 00:00:00') AS date_time,
'2024-01-01 00:00:00' AS date_time_string
SELECT
subtractWeeks(date, 1) AS subtract_weeks_with_date,
subtractWeeks(date_time, 1) AS subtract_weeks_with_date_time,
subtractWeeks(date_time_string, 1) AS subtract_weeks_with_date_time_string
response title=Response
ββsubtract_weeks_with_dateββ¬βsubtract_weeks_with_date_timeββ¬βsubtract_weeks_with_date_time_stringββ
β 2023-12-25 β 2023-12-25 00:00:00 β 2023-12-25 00:00:00.000 β
ββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββ
Using alternative INTERVAL syntax
sql title=Query
SELECT dateSub('1998-06-16'::Date, INTERVAL 10 week)
response title=Response
ββminus(CAST('β―alWeek(10))ββ
β 1998-04-07 β
ββββββββββββββββββββββββββββ
subtractYears {#subtractYears}
Introduced in: v1.1
Subtracts a specified number of years from a date, a date with time or a string-encoded date or date with time.
Syntax
sql
subtractYears(datetime, num)
Arguments
datetime
β Date or date with time to subtract specified number of years from.
Date
or
Date32
or
DateTime
or
DateTime64
or
String
num
β Number of years to subtract.
(U)Int*
or
Float*
Returned value
Returns
datetime
minus
num
years
Date
or
Date32
or
DateTime
or
DateTime64
Examples
Subtract years from different date types
sql title=Query
WITH
toDate('2024-01-01') AS date,
toDateTime('2024-01-01 00:00:00') AS date_time,
'2024-01-01 00:00:00' AS date_time_string
SELECT
subtractYears(date, 1) AS subtract_years_with_date,
subtractYears(date_time, 1) AS subtract_years_with_date_time,
subtractYears(date_time_string, 1) AS subtract_years_with_date_time_string
response title=Response
ββsubtract_years_with_dateββ¬βsubtract_years_with_date_timeββ¬βsubtract_years_with_date_time_stringββ
β 2023-01-01 β 2023-01-01 00:00:00 β 2023-01-01 00:00:00.000 β
ββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββ
Using alternative INTERVAL syntax
sql title=Query
SELECT dateSub('1998-06-16'::Date, INTERVAL 10 year)
response title=Response
ββminus(CAST('β―alYear(10))ββ
β 1988-06-16 β
ββββββββββββββββββββββββββββ
timeDiff {#timeDiff}
Introduced in: v23.4 | {"source_file": "date-time-functions.md"} | [
0.014847608283162117,
0.06611235439777374,
-0.010978990234434605,
0.057315461337566376,
0.005171583499759436,
0.042074013501405716,
-0.014546862803399563,
0.04121873900294304,
-0.11573445796966553,
-0.02383050136268139,
-0.029721565544605255,
-0.13935670256614685,
-0.007141225505620241,
-0... |
a6d01daf-1e63-4333-9530-a86b84013f35 | response title=Response
ββminus(CAST('β―alYear(10))ββ
β 1988-06-16 β
ββββββββββββββββββββββββββββ
timeDiff {#timeDiff}
Introduced in: v23.4
Returns the difference between two dates or dates with time values in seconds.
The difference is calculated as
enddate
-
startdate
.
This function is equivalent to
dateDiff('second', startdate, enddate)
.
For calculating time differences in other units (hours, days, months, etc.), use the
dateDiff
function instead.
Syntax
sql
timeDiff(startdate, enddate)
Arguments
startdate
β The first time value to subtract (the subtrahend).
Date
or
Date32
or
DateTime
or
DateTime64
enddate
β The second time value to subtract from (the minuend).
Date
or
Date32
or
DateTime
or
DateTime64
Returned value
Returns the difference between
enddate
and
startdate
expressed in seconds.
Int64
Examples
Calculate time difference in seconds
sql title=Query
SELECT timeDiff(toDateTime('2018-01-01 22:00:00'), toDateTime('2018-01-02 23:00:00')) AS res
response title=Response
ββββresββ
β 90000 β
βββββββββ
Calculate time difference and convert to hours
sql title=Query
SELECT timeDiff(toDateTime('2018-01-01 22:00:00'), toDateTime('2018-01-02 23:00:00')) / 3600 AS hours
response title=Response
ββhoursββ
β 25 β
βββββββββ
Equivalent to dateDiff with seconds
sql title=Query
SELECT
timeDiff(toDateTime('2021-12-29'), toDateTime('2022-01-01')) AS time_diff_result,
dateDiff('second', toDateTime('2021-12-29'), toDateTime('2022-01-01')) AS date_diff_result
response title=Response
ββtime_diff_resultββ¬βdate_diff_resultββ
β 259200 β 259200 β
ββββββββββββββββββββ΄βββββββββββββββββββ
timeSlot {#timeSlot}
Introduced in: v1.1
Round the time to the start of a half-an-hour length interval.
:::note
Although this function can take values of the extended types
Date32
and
DateTime64
as an argument,
passing it a time outside the normal range (year 1970 to 2149 for
Date
/ 2106 for
DateTime
) will produce wrong results.
:::
Syntax
sql
timeSlot(time[, time_zone])
Arguments
time
β Time to round to the start of a half-an-hour length interval.
DateTime
or
Date32
or
DateTime64
time_zone
β Optional. A String type const value or an expression representing the time zone.
String
Returned value
Returns the time rounded to the start of a half-an-hour length interval.
DateTime
Examples
Round time to half-hour interval
sql title=Query
SELECT timeSlot(toDateTime('2000-01-02 03:04:05', 'UTC'))
response title=Response
ββtimeSlot(toDateTime('2000-01-02 03:04:05', 'UTC'))ββ
β 2000-01-02 03:00:00 β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
timeSlots {#timeSlots}
Introduced in: v1.1 | {"source_file": "date-time-functions.md"} | [
-0.00010361836029915139,
0.04664349928498268,
0.0033215621951967478,
0.019822319969534874,
-0.00871471967548132,
0.0073036570101976395,
-0.016291210427880287,
0.07107895612716675,
0.02692483738064766,
-0.03956473246216774,
0.03498972952365875,
-0.14100487530231476,
0.0028346756007522345,
0... |
304afbf5-2106-4daf-9d87-7cbda774c394 | timeSlots {#timeSlots}
Introduced in: v1.1
For a time interval starting at
StartTime
and continuing for
Duration
seconds, it returns an array of moments in time, consisting of points from this interval rounded down to the
Size
in seconds.
Size
is an optional parameter set to 1800 (30 minutes) by default.
This is necessary, for example, when searching for pageviews in the corresponding session.
For
DateTime64
, the return value's scale can differ from the scale of
StartTime
. The highest scale among all given arguments is taken.
Syntax
sql
timeSlots(StartTime, Duration[, Size])
Arguments
StartTime
β Starting time for the interval.
DateTime
or
DateTime64
Duration
β Duration of the interval in seconds.
UInt32
or
DateTime64
Size
β Optional. Size of time slots in seconds. Default is 1800 (30 minutes).
UInt32
or
DateTime64
Returned value
Returns an array of DateTime/DateTime64 (return type matches the type of
StartTime
). For DateTime64, the return value's scale can differ from the scale of
StartTime
- the highest scale among all given arguments is taken.
Array(DateTime)
or
Array(DateTime64)
Examples
Generate time slots for an interval
sql title=Query
SELECT timeSlots(toDateTime('2012-01-01 12:20:00'), toUInt32(600));
SELECT timeSlots(toDateTime('1980-12-12 21:01:02', 'UTC'), toUInt32(600), 299);
SELECT timeSlots(toDateTime64('1980-12-12 21:01:02.1234', 4, 'UTC'), toDecimal64(600.1, 1), toDecimal64(299, 0))
response title=Response
ββtimeSlots(toDateTime('2012-01-01 12:20:00'), toUInt32(600))ββ
β ['2012-01-01 12:00:00','2012-01-01 12:30:00'] β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ββtimeSlots(toDateTime('1980-12-12 21:01:02', 'UTC'), toUInt32(600), 299)ββ
β ['1980-12-12 20:56:13','1980-12-12 21:01:12','1980-12-12 21:06:11'] β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ββtimeSlots(toDateTime64('1980-12-12 21:01:02.1234', 4, 'UTC'), toDecimal64(600.1, 1), toDecimal64(299, 0))ββ
β ['1980-12-12 20:56:13.0000','1980-12-12 21:01:12.0000','1980-12-12 21:06:11.0000'] β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
timestamp {#timestamp}
Introduced in: v23.9
Converts the first argument
expr
to type
DateTime64(6)
.
If a second argument
expr_time
is provided, it adds the specified time to the converted value.
Syntax
sql
timestamp(expr[, expr_time])
Arguments
expr
β Date or date with time.
String
expr_time
β Optional. Time to add to the converted value.
String
Returned value
Returns the converted value of
expr
, or
expr
with added time
DateTime64(6)
Examples
Convert date string to DateTime64(6)
sql title=Query
SELECT timestamp('2023-12-31') AS ts;
response title=Response
ββββββββββββββββββββββββββtsββ
β 2023-12-31 00:00:00.000000 β
ββββββββββββββββββββββββββββββ
Add time to date string | {"source_file": "date-time-functions.md"} | [
0.02572571113705635,
-0.016745546832680702,
-0.07768868654966354,
-0.003634774126112461,
-0.04488002508878708,
0.018309229984879494,
0.011298066936433315,
0.09135494381189346,
0.024905318394303322,
0.0013325868640094995,
0.020728975534439087,
-0.05358630791306496,
-0.02621060609817505,
0.0... |
be759df9-bf57-44c7-8263-5a71fdf6624b | response title=Response
ββββββββββββββββββββββββββtsββ
β 2023-12-31 00:00:00.000000 β
ββββββββββββββββββββββββββββββ
Add time to date string
sql title=Query
SELECT timestamp('2023-12-31 12:00:00', '12:00:00.11') AS ts;
response title=Response
ββββββββββββββββββββββββββtsββ
β 2024-01-01 00:00:00.110000 β
ββββββββββββββββββββββββββββββ
timezone {#timezone}
Introduced in: v21.4
Returns the time zone name of the current session or converts a time zone
offset or name to a canonical time zone name.
Syntax
sql
timezone()
Aliases
:
timeZone
Arguments
None.
Returned value
Returns the canonical time zone name as a
String
Examples
Usage example
sql title=Query
SELECT timezone()
response title=Response
ββtimezone()ββββββββ
β Europe/Amsterdam β
ββββββββββββββββββββ
timezoneOf {#timezoneOf}
Introduced in: v21.4
Returns the timezone name of a
DateTime
or
DateTime64
value.
Syntax
sql
timeZoneOf(datetime)
Aliases
:
timeZoneOf
Arguments
datetime
β A value of type.
DateTime
or
DateTime64
timezone
β Optional. Timezone name to convert the
datetime
value's timezone to.
String
Returned value
Returns the timezone name for
datetime
String
Examples
Usage example
sql title=Query
SELECT timezoneOf(now());
response title=Response
ββtimezoneOf(now())ββ
β Europe/Amsterdam β
βββββββββββββββββββββ
timezoneOffset {#timezoneOffset}
Introduced in: v21.6
Returns the timezone offset in seconds from
UTC
.
The function takes daylight saving time and historical timezone changes at the specified date and time into account.
Syntax
sql
timeZoneOffset(datetime)
Aliases
:
timeZoneOffset
Arguments
datetime
β
DateTime
value to get the timezone offset for.
DateTime
or
DateTime64
Returned value
Returns the offset from UTC in seconds
Int32
Examples
Usage example
sql title=Query
SELECT toDateTime('2021-04-21 10:20:30', 'America/New_York') AS Time,
toTypeName(Time) AS Type,
timeZoneOffset(Time) AS Offset_in_seconds,
(Offset_in_seconds / 3600) AS Offset_in_hours;
response title=Response
βββββββββββββββββTimeββ¬βTypeββββββββββββββββββββββββββ¬βOffset_in_secondsββ¬βOffset_in_hoursββ
β 2021-04-21 10:20:30 β DateTime('America/New_York') β -14400 β -4 β
βββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄ββββββββββββββββββββ΄ββββββββββββββββββ
toDayOfMonth {#toDayOfMonth}
Introduced in: v1.1
Returns the day of the month (1-31) of a
Date
or
DateTime
.
Syntax
sql
toDayOfMonth(datetime)
Aliases
:
DAY
,
DAYOFMONTH
Arguments
datetime
β Date or date with time to get the day of month from.
Date
or
Date32
or
DateTime
or
DateTime64
Returned value
Returns the day of the month of the given date/time
UInt8
Examples
Usage example
sql title=Query
SELECT toDayOfMonth(toDateTime('2023-04-21 10:20:30')) | {"source_file": "date-time-functions.md"} | [
0.017070747911930084,
-0.008189239539206028,
-0.04658303037285805,
0.0018438758561387658,
-0.010555503889918327,
-0.0522766187787056,
0.03775545954704285,
0.04790959879755974,
0.018115166574716568,
0.024692991748452187,
-0.04723048582673073,
-0.08278413116931915,
-0.06143336370587349,
0.02... |
bf96c9b4-f3f0-4485-9f89-5b3456f0f806 | Returned value
Returns the day of the month of the given date/time
UInt8
Examples
Usage example
sql title=Query
SELECT toDayOfMonth(toDateTime('2023-04-21 10:20:30'))
response title=Response
ββtoDayOfMonth(toDateTime('2023-04-21 10:20:30'))ββ
β 21 β
βββββββββββββββββββββββββββββββββββββββββββββββββββ
toDayOfWeek {#toDayOfWeek}
Introduced in: v1.1
Returns the number of the day within the week of a
Date
or
DateTime
value.
The two-argument form of
toDayOfWeek()
enables you to specify whether the week starts on Monday or Sunday,
and whether the return value should be in the range from 0 to 6 or 1 to 7.
| Mode | First day of week | Range |
|------|-------------------|------------------------------------------------|
| 0 | Monday | 1-7: Monday = 1, Tuesday = 2, ..., Sunday = 7 |
| 1 | Monday | 0-6: Monday = 0, Tuesday = 1, ..., Sunday = 6 |
| 2 | Sunday | 0-6: Sunday = 0, Monday = 1, ..., Saturday = 6 |
| 3 | Sunday | 1-7: Sunday = 1, Monday = 2, ..., Saturday = 7 |
Syntax
sql
toDayOfWeek(datetime[, mode[, timezone]])
Aliases
:
DAYOFWEEK
Arguments
datetime
β Date or date with time to get the day of week from.
Date
or
Date32
or
DateTime
or
DateTime64
mode
β Optional. Integer specifying the week mode (0-3). Defaults to 0 if omitted.
UInt8
timezone
β Optional. Timezone to use for the conversion.
String
Returned value
Returns the day of the week for the given
Date
or
DateTime
UInt8
Examples
Usage example
sql title=Query
-- The following date is April 21, 2023, which was a Friday:
SELECT
toDayOfWeek(toDateTime('2023-04-21')),
toDayOfWeek(toDateTime('2023-04-21'), 1)
response title=Response
ββtoDayOfWeek(toDateTime('2023-04-21'))ββ¬βtoDayOfWeek(toDateTime('2023-04-21'), 1)ββ
β 5 β 4 β
βββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββ
toDayOfYear {#toDayOfYear}
Introduced in: v18.4
Returns the number of the day within the year (1-366) of a
Date
or
DateTime
value.
Syntax
sql
toDayOfYear(datetime)
Aliases
:
DAYOFYEAR
Arguments
datetime
β Date or date with time to get the day of year from.
Date
or
Date32
or
DateTime
or
DateTime64
Returned value
Returns the day of the year of the given Date or DateTime
UInt16
Examples
Usage example
sql title=Query
SELECT toDayOfYear(toDateTime('2023-04-21 10:20:30'))
response title=Response
ββtoDayOfYear(toDateTime('2023-04-21 10:20:30'))ββ
β 111 β
ββββββββββββββββββββββββββββββββββββββββββββββββββ
toDaysSinceYearZero {#toDaysSinceYearZero}
Introduced in: v23.9
For a given date, returns the number of days which have passed since
1 January 0000
in the | {"source_file": "date-time-functions.md"} | [
-0.0519254133105278,
0.041106875985860825,
0.0070280758664011955,
0.07630767673254013,
-0.06836546957492828,
0.031208839267492294,
-0.0015139702009037137,
0.00877651758491993,
-0.06073726341128349,
-0.05994904413819313,
-0.006669522728770971,
-0.1011846587061882,
-0.028523821383714676,
-0.... |
4e4948f7-e315-4a9f-a458-428c2df6d0a0 | toDaysSinceYearZero {#toDaysSinceYearZero}
Introduced in: v23.9
For a given date, returns the number of days which have passed since
1 January 0000
in the
proleptic Gregorian calendar defined by ISO 8601
.
The calculation is the same as in MySQL's
TO_DAYS
function.
Syntax
sql
toDaysSinceYearZero(date[, time_zone])
Aliases
:
TO_DAYS
Arguments
date
β The date or date with time for which to calculate the number of days since year zero from.
Date
or
Date32
or
DateTime
or
DateTime64
time_zone
β Time zone.
String
Returned value
Returns the number of days passed since date
0000-01-01
.
UInt32
Examples
Calculate days since year zero
sql title=Query
SELECT toDaysSinceYearZero(toDate('2023-09-08'))
response title=Response
ββtoDaysSinceYearZero(toDate('2023-09-08')))ββ
β 713569 β
ββββββββββββββββββββββββββββββββββββββββββββββ
toHour {#toHour}
Introduced in: v1.1
Returns the hour component (0-23) of a
DateTime
or
DateTime64
value.
Syntax
sql
toHour(datetime)
Aliases
:
HOUR
Arguments
datetime
β Date with time to get the hour from.
DateTime
or
DateTime64
Returned value
Returns the hour (0-23) of
datetime
.
UInt8
Examples
Usage example
sql title=Query
SELECT toHour(toDateTime('2023-04-21 10:20:30'))
response title=Response
ββtoHour(toDateTime('2023-04-21 10:20:30'))ββ
β 10 β
βββββββββββββββββββββββββββββββββββββββββββββ
toISOYear {#toISOYear}
Introduced in: v18.4
Converts a date or date with time to the ISO year number.
Syntax
sql
toISOYear(datetime)
Arguments
datetime
β The value with date or date with time.
Date
or
Date32
or
DateTime
or
DateTime64
Returned value
Returns the input value converted to an ISO year number.
UInt16
Examples
Get ISO year from date values
sql title=Query
SELECT
toISOYear(toDate('2024/10/02')) as year1,
toISOYear(toDateTime('2024-10-02 01:30:00')) as year2
response title=Response
ββweek1ββ¬βweek2ββ
β 40 β 40 β
βββββββββ΄ββββββββ
toLastDayOfMonth {#toLastDayOfMonth}
Introduced in: v1.1
Rounds up a date or date with time to the last day of the month.
:::note
The return type can be configured by setting
enable_extended_results_for_datetime_functions
.
:::
Syntax
sql
toLastDayOfMonth(value)
Aliases
:
LAST_DAY
Arguments
value
β The date or date with time to round up to the last day of the month.
Date
or
Date32
or
DateTime
or
DateTime64
Returned value
Returns the date of the last day of the month for the given date or date with time.
Date
Examples
Round up to the last day of the month
sql title=Query
SELECT toLastDayOfMonth(toDateTime('2023-04-21 10:20:30'))
response title=Response
ββtoLastDayOfMonth(toDateTime('2023-04-21 10:20:30'))ββ
β 2023-04-30 β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
toLastDayOfWeek {#toLastDayOfWeek} | {"source_file": "date-time-functions.md"} | [
-0.014334439300000668,
0.048482608050107956,
-0.02902427688241005,
0.06449875980615616,
-0.08333580195903778,
-0.027855295687913895,
-0.010303845629096031,
0.0454806387424469,
-0.05248846113681793,
-0.012522413395345211,
0.004221740644425154,
-0.16451643407344818,
-0.0035916820634156466,
0... |
da4633d8-6a34-4141-b89a-9319e1727756 | toLastDayOfWeek {#toLastDayOfWeek}
Introduced in: v23.5
Rounds a date or date with time up to the nearest Saturday or Sunday.
:::note
The return type can be configured by setting
enable_extended_results_for_datetime_functions
.
:::
Syntax
sql
toLastDayOfWeek(datetime[, mode[, timezone]])
Arguments
datetime
β A date or date with time to convert.
Date
or
DateTime
or
Date32
or
DateTime64
mode
β Determines the first day of the week as described in the
toWeek()
function. Default
0
.
UInt8
timezone
β Optional. The timezone to use for the conversion. If not specified, the server's timezone is used.
String
Returned value
Returns the date of the nearest Saturday or Sunday, on or after the given date, depending on the mode
Date
or
Date32
or
DateTime
or
DateTime64
Examples
Round up to the nearest Saturday or Sunday
sql title=Query
SELECT
toLastDayOfWeek(toDateTime('2023-04-21 10:20:30')), /* a Friday */
toLastDayOfWeek(toDateTime('2023-04-21 10:20:30'), 1), /* a Friday */
toLastDayOfWeek(toDate('2023-04-23')), /* a Sunday */
toLastDayOfWeek(toDate('2023-04-23'), 1) /* a Sunday */
FORMAT Vertical
response title=Response
Row 1:
ββββββ
toLastDayOfWeek(toDateTime('2023-04-21 10:20:30')): 2023-04-23
toLastDayOfWeek(toDateTime('2023-04-21 10:20:30'), 1): 2023-04-22
toLastDayOfWeek(toDate('2023-04-23')): 2023-04-23
toLastDayOfWeek(toDate('2023-04-23'), 1): 2023-04-23
toMillisecond {#toMillisecond}
Introduced in: v24.2
Returns the millisecond component (0-999) of a
DateTime
or
DateTime64
value.
Syntax
sql
toMillisecond(datetime)
Aliases
:
MILLISECOND
Arguments
datetime
β Date with time to get the millisecond from.
DateTime
or
DateTime64
Returned value
Returns the millisecond in the minute (0 - 59) of
datetime
.
UInt16
Examples
Usage example
sql title=Query
SELECT toMillisecond(toDateTime64('2023-04-21 10:20:30.456', 3));
response title=Response
βββtoMillisecond(toDateTime64('2023-04-21 10:20:30.456', 3))ββ
β 456 β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
toMinute {#toMinute}
Introduced in: v1.1
Returns the minute component (0-59) of a
Date
or
DateTime
value.
Syntax
sql
toMinute(datetime)
Aliases
:
MINUTE
Arguments
datetime
β Date with time to get the minute from.
DateTime
or
DateTime64
Returned value
Returns the minute of the hour (0 - 59) of
datetime
.
UInt8
Examples
Usage example
sql title=Query
SELECT toMinute(toDateTime('2023-04-21 10:20:30'))
response title=Response
ββtoMinute(toDateTime('2023-04-21 10:20:30'))ββ
β 20 β
βββββββββββββββββββββββββββββββββββββββββββββββ
toModifiedJulianDay {#toModifiedJulianDay}
Introduced in: v21.1 | {"source_file": "date-time-functions.md"} | [
-0.036575768142938614,
0.0368829183280468,
-0.019353289157152176,
0.03164699673652649,
-0.04742330312728882,
0.035230547189712524,
0.01319931447505951,
0.017306214198470116,
-0.06087370961904526,
-0.031046533957123756,
-0.05979471653699875,
-0.06695105880498886,
-0.06829631328582764,
-0.02... |
f79fdbf3-5c3a-440d-8859-0fb0e6fe9727 | toModifiedJulianDay {#toModifiedJulianDay}
Introduced in: v21.1
Converts a
Proleptic Gregorian calendar
date in text form
YYYY-MM-DD
to a
Modified Julian Day
number in
Int32
. This function supports date from
0000-01-01
to
9999-12-31
. It raises an exception if the argument cannot be parsed as a date, or the date is invalid.
Syntax
sql
toModifiedJulianDay(date)
Arguments
date
β The date in String form.
String
or
FixedString
Returned value
Returns Modified Julian Day number.
Int32
Examples
Convert date to Modified Julian Day
sql title=Query
SELECT toModifiedJulianDay('2020-01-01')
response title=Response
ββtoModifiedJulianDay('2020-01-01')ββ
β 58849 β
βββββββββββββββββββββββββββββββββββββ
toModifiedJulianDayOrNull {#toModifiedJulianDayOrNull}
Introduced in: v21.1
Similar to
toModifiedJulianDay()
, but instead of raising exceptions it returns
NULL
.
Syntax
sql
toModifiedJulianDayOrNull(date)
Arguments
date
β Date in text form.
String
or
FixedString
Returned value
Returns the modified Julian day number for valid
date
, otherwise
null
.
Nullable(Int32)
Examples
Convert date to Modified Julian Day with null handling
sql title=Query
SELECT toModifiedJulianDayOrNull('2020-01-01');
SELECT toModifiedJulianDayOrNull('0000-00-00'); -- invalid date, returns NULL
response title=Response
ββtoModifiedJuβ―020-01-01')ββ
β 58849 β
ββββββββββββββββββββββββββββ
ββtoModifiedJuβ―000-00-00')ββ
β α΄Ία΅α΄Έα΄Έ β
ββββββββββββββββββββββββββββ
toMonday {#toMonday}
Introduced in: v1.1
Rounds down a date or date with time to the Monday of the same week. Returns the date.
:::note
The return type can be configured by setting
enable_extended_results_for_datetime_functions
.
:::
Syntax
sql
toMonday(value)
Arguments
value
β Date or date with time to round down to the Monday of the week.
Date
or
Date32
or
DateTime
or
DateTime64
Returned value
Returns the date of the Monday of the same week for the given date or date with time.
Date
Examples
Round down to the Monday of the week
sql title=Query
SELECT
toMonday(toDateTime('2023-04-21 10:20:30')), -- A Friday
toMonday(toDate('2023-04-24')); -- Already a Monday
response title=Response
ββtoMonday(toDateTime('2023-04-21 10:20:30'))ββ¬βtoMonday(toDate('2023-04-24'))ββ
β 2023-04-17 β 2023-04-24 β
βββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββ
toMonth {#toMonth}
Introduced in: v1.1
Returns the month component (1-12) of a
Date
or
DateTime
value.
Syntax
sql
toMonth(datetime)
Aliases
:
MONTH
Arguments
datetime
β Date or date with time to get the month from.
Date
or
Date32
or
DateTime
or
DateTime64
Returned value
Returns the month of the given date/time
UInt8
Examples
Usage example | {"source_file": "date-time-functions.md"} | [
-0.021661249920725822,
0.07158597558736801,
0.029685838147997856,
0.010961240157485008,
-0.07988536357879639,
-0.03584814444184303,
-0.0029393858276307583,
0.024373263120651245,
-0.08329884707927704,
-0.03608180582523346,
0.018548812717199326,
-0.09297018498182297,
0.058335959911346436,
-0... |
0a02fb56-adfc-4012-a960-1b8c35b67b36 | Returned value
Returns the month of the given date/time
UInt8
Examples
Usage example
sql title=Query
SELECT toMonth(toDateTime('2023-04-21 10:20:30'))
response title=Response
ββtoMonth(toDateTime('2023-04-21 10:20:30'))ββ
β 4 β
ββββββββββββββββββββββββββββββββββββββββββββββ
toMonthNumSinceEpoch {#toMonthNumSinceEpoch}
Introduced in: v25.3
Returns amount of months passed from year 1970
Syntax
sql
toMonthNumSinceEpoch(date)
Arguments
date
β A date or date with time.
Date
or
DateTime
or
DateTime64
Returned value
Positive integer
Examples
Example
sql title=Query
SELECT toMonthNumSinceEpoch(toDate('2024-10-01'))
response title=Response
657
toQuarter {#toQuarter}
Introduced in: v1.1
Returns the quarter of the year (1-4) for a given
Date
or
DateTime
value.
Syntax
sql
toQuarter(datetime)
Aliases
:
QUARTER
Arguments
datetime
β Date or date with time to get the quarter of the year from.
Date
or
Date32
or
DateTime
or
DateTime64
Returned value
Returns the quarter of the year for the given date/time
UInt8
Examples
Usage example
sql title=Query
SELECT toQuarter(toDateTime('2023-04-21 10:20:30'))
response title=Response
ββtoQuarter(toDateTime('2023-04-21 10:20:30'))ββ
β 2 β
ββββββββββββββββββββββββββββββββββββββββββββββββ
toRelativeDayNum {#toRelativeDayNum}
Introduced in: v1.1
Converts a date or date with time to the number of days elapsed since a certain fixed point in the past.
The exact point in time is an implementation detail, and therefore this function is not intended to be used standalone.
The main purpose of the function is to calculate the difference in days between two dates or dates with time, e.g.,
toRelativeDayNum(dt1) - toRelativeDayNum(dt2)
.
Syntax
sql
toRelativeDayNum(date)
Arguments
date
β Date or date with time.
Date
or
DateTime
or
DateTime64
Returned value
Returns the number of days from a fixed reference point in the past.
UInt32
Examples
Get relative day numbers
sql title=Query
SELECT toRelativeDayNum(toDate('2023-04-01')) - toRelativeDayNum(toDate('2023-01-01'))
response title=Response
ββminus(toRelaβ―3-01-01')))ββ
β 90 β
ββββββββββββββββββββββββββββ
toRelativeHourNum {#toRelativeHourNum}
Introduced in: v1.1
Converts a date or date with time to the number of hours elapsed since a certain fixed point in the past.
The exact point in time is an implementation detail, and therefore this function is not intended to be used standalone.
The main purpose of the function is to calculate the difference in hours between two dates or dates with time, e.g.,
toRelativeHourNum(dt1) - toRelativeHourNum(dt2)
.
Syntax
sql
toRelativeHourNum(date)
Arguments
date
β Date or date with time.
Date
or
DateTime
or
DateTime64
Returned value | {"source_file": "date-time-functions.md"} | [
-0.02441779337823391,
0.01141499076038599,
-0.024891076609492302,
0.030603952705860138,
-0.07985600084066391,
0.023492783308029175,
-0.0327555276453495,
-0.007572971284389496,
0.008074234239757061,
0.012267319485545158,
0.030348576605319977,
-0.09568823873996735,
0.01214898657053709,
0.003... |
793bbbb5-9746-4ad2-99e8-9abdd8e1dc00 | Syntax
sql
toRelativeHourNum(date)
Arguments
date
β Date or date with time.
Date
or
DateTime
or
DateTime64
Returned value
Returns the number of hours from a fixed reference point in the past.
UInt32
Examples
Get relative hour numbers
sql title=Query
SELECT toRelativeHourNum(toDateTime('2023-01-01 12:00:00')) - toRelativeHourNum(toDateTime('2023-01-01 00:00:00')) AS hours_difference
response title=Response
ββhours_differenceββ
β 12 β
ββββββββββββββββββββ
toRelativeMinuteNum {#toRelativeMinuteNum}
Introduced in: v1.1
Converts a date or date with time to the number of minutes elapsed since a certain fixed point in the past.
The exact point in time is an implementation detail, and therefore this function is not intended to be used standalone.
The main purpose of the function is to calculate the difference in minutes between two dates or dates with time, e.g.,
toRelativeMinuteNum(dt1) - toRelativeMinuteNum(dt2)
.
Syntax
sql
toRelativeMinuteNum(date)
Arguments
date
β Date or date with time.
Date
or
DateTime
or
DateTime64
Returned value
Returns the number of minutes from a fixed reference point in the past.
UInt32
Examples
Get relative minute numbers
sql title=Query
SELECT toRelativeMinuteNum(toDateTime('2023-01-01 00:30:00')) - toRelativeMinuteNum(toDateTime('2023-01-01 00:00:00')) AS minutes_difference
response title=Response
ββminutes_differenceββ
β 30 β
ββββββββββββββββββββββ
toRelativeMonthNum {#toRelativeMonthNum}
Introduced in: v1.1
Converts a date or date with time to the number of months elapsed since a certain fixed point in the past.
The exact point in time is an implementation detail, and therefore this function is not intended to be used standalone.
The main purpose of the function is to calculate the difference in months between two dates or dates with time, e.g.,
toRelativeMonthNum(dt1) - toRelativeMonthNum(dt2)
.
Syntax
sql
toRelativeMonthNum(date)
Arguments
date
β Date or date with time.
Date
or
DateTime
or
DateTime64
Returned value
Returns the number of months from a fixed reference point in the past.
UInt32
Examples
Get relative month numbers
sql title=Query
SELECT toRelativeMonthNum(toDate('2023-04-01')) - toRelativeMonthNum(toDate('2023-01-01')) AS months_difference
response title=Response
ββmonths_differenceββ
β 3 β
βββββββββββββββββββββ
toRelativeQuarterNum {#toRelativeQuarterNum}
Introduced in: v1.1
Converts a date or date with time to the number of quarters elapsed since a certain fixed point in the past.
The exact point in time is an implementation detail, and therefore this function is not intended to be used standalone.
The main purpose of the function is to calculate the difference in quarters between two dates or dates with time, e.g.,
toRelativeQuarterNum(dt1) - toRelativeQuarterNum(dt2)
.
Syntax
sql
toRelativeQuarterNum(date)
Arguments | {"source_file": "date-time-functions.md"} | [
-0.05100319907069206,
0.0491853803396225,
0.00987771712243557,
0.05325895547866821,
-0.07341738790273666,
-0.035752203315496445,
0.0021824645809829235,
0.10572898387908936,
-0.006743560545146465,
-0.017041759565472603,
-0.03378066420555115,
-0.06804917007684708,
-0.010026584379374981,
-0.0... |
0ce2d847-b793-444f-80ee-d80724790f20 | Syntax
sql
toRelativeQuarterNum(date)
Arguments
date
β Date or date with time.
Date
or
DateTime
or
DateTime64
Returned value
Returns the number of quarters from a fixed reference point in the past.
UInt32
Examples
Get relative quarter numbers
sql title=Query
SELECT toRelativeQuarterNum(toDate('2023-04-01')) - toRelativeQuarterNum(toDate('2023-01-01')) AS quarters_difference
response title=Response
ββquarters_differenceββ
β 1 β
βββββββββββββββββββββββ
toRelativeSecondNum {#toRelativeSecondNum}
Introduced in: v1.1
Converts a date or date with time to the number of seconds elapsed since a certain fixed point in the past.
The exact point in time is an implementation detail, and therefore this function is not intended to be used standalone.
The main purpose of the function is to calculate the difference in seconds between two dates or dates with time, e.g.,
toRelativeSecondNum(dt1) - toRelativeSecondNum(dt2)
.
Syntax
sql
toRelativeSecondNum(date)
Arguments
date
β Date or date with time.
Date
or
DateTime
or
DateTime64
Returned value
Returns the number of seconds from a fixed reference point in the past.
UInt32
Examples
Get relative second numbers
sql title=Query
SELECT toRelativeSecondNum(toDateTime('2023-01-01 00:01:00')) - toRelativeSecondNum(toDateTime('2023-01-01 00:00:00')) AS seconds_difference
response title=Response
ββseconds_differenceββ
β 60 β
ββββββββββββββββββββββ
toRelativeWeekNum {#toRelativeWeekNum}
Introduced in: v1.1
Converts a date or date with time to the number of weeks elapsed since a certain fixed point in the past.
The exact point in time is an implementation detail, and therefore this function is not intended to be used standalone.
The main purpose of the function is to calculate the difference in weeks between two dates or dates with time, e.g.,
toRelativeWeekNum(dt1) - toRelativeWeekNum(dt2)
.
Syntax
sql
toRelativeWeekNum(date)
Arguments
date
β Date or date with time.
Date
or
DateTime
or
DateTime64
Returned value
Returns the number of weeks from a fixed reference point in the past.
UInt32
Examples
Get relative week numbers
sql title=Query
SELECT toRelativeWeekNum(toDate('2023-01-08')) - toRelativeWeekNum(toDate('2023-01-01')) AS weeks_difference
response title=Response
ββweeks_differenceββ
β 1 β
ββββββββββββββββββββ
toRelativeYearNum {#toRelativeYearNum}
Introduced in: v1.1
Converts a date or date with time to the number of years elapsed since a certain fixed point in the past.
The exact point in time is an implementation detail, and therefore this function is not intended to be used
standalone. The main purpose of the function is to calculate the difference in years between two dates or dates with time, e.g.,
toRelativeYearNum(dt1) - toRelativeYearNum(dt2)
.
Syntax
sql
toRelativeYearNum(date)
Arguments | {"source_file": "date-time-functions.md"} | [
-0.050822220742702484,
0.04055663198232651,
-0.024766769260168076,
0.020203053951263428,
-0.0890980213880539,
0.03041168674826622,
-0.025285186246037483,
0.09322966635227203,
0.001137713436037302,
-0.015205031260848045,
0.004973205272108316,
-0.0827600359916687,
-0.022642478346824646,
-0.0... |
967e7ca2-4aca-4875-8584-d9a3b1817074 | Syntax
sql
toRelativeYearNum(date)
Arguments
date
β Date or date with time.
Date
or
DateTime
or
DateTime64
Returned value
Returns the number of years from a fixed reference point in the past.
UInt16
Examples
Get relative year numbers
sql title=Query
SELECT toRelativeYearNum('2010-10-01'::DateTime) - toRelativeYearNum('2000-01-01'::DateTime)
response title=Response
ββminus(toRelaβ―ateTime')))ββ
β 10 β
ββββββββββββββββββββββββββββ
toSecond {#toSecond}
Introduced in: v1.1
Returns the second component (0-59) of a
DateTime
or
DateTime64
value.
Syntax
sql
toSecond(datetime)
Aliases
:
SECOND
Arguments
datetime
β Date with time to get the second from.
DateTime
or
DateTime64
Returned value
Returns the second in the minute (0 - 59) of
datetime
.
UInt8
Examples
Usage example
sql title=Query
SELECT toSecond(toDateTime('2023-04-21 10:20:30'))
response title=Response
ββtoSecond(toDateTime('2023-04-21 10:20:30'))ββ
β 30 β
βββββββββββββββββββββββββββββββββββββββββββββββ
toStartOfDay {#toStartOfDay}
Introduced in: v1.1
Rounds down a date with time to the start of the day.
:::note
The return type can be configured by setting
enable_extended_results_for_datetime_functions
.
:::
Syntax
sql
toStartOfDay(datetime)
Arguments
datetime
β A date or date with time to round.
Date
or
DateTime
Returned value
Returns the date with time rounded down to the start of the day.
Date
or
DateTime
or
Date32
or
DateTime64
Examples
Round down to the start of the day
sql title=Query
SELECT toStartOfDay(toDateTime('2023-04-21 10:20:30'))
response title=Response
ββtoStartOfDay(toDateTime('2023-04-21 10:20:30'))ββ
β 2023-04-21 00:00:00 β
βββββββββββββββββββββββββββββββββββββββββββββββββββ
toStartOfFifteenMinutes {#toStartOfFifteenMinutes}
Introduced in: v1.1
Rounds down the date with time to the start of the fifteen-minute interval.
:::note
The return type can be configured by setting
enable_extended_results_for_datetime_functions
.
:::
Syntax
sql
toStartOfFifteenMinutes(datetime)
Arguments
datetime
β A date or date with time to round.
DateTime
or
DateTime64
Returned value
Returns the date with time rounded to the start of the nearest fifteen-minute interval
DateTime
or
DateTime64
Examples
Example
sql title=Query
SELECT
toStartOfFifteenMinutes(toDateTime('2023-04-21 10:17:00')),
toStartOfFifteenMinutes(toDateTime('2023-04-21 10:20:00')),
toStartOfFifteenMinutes(toDateTime('2023-04-21 10:23:00'))
FORMAT Vertical
response title=Response
Row 1:
ββββββ
toStartOfFifteenMinutes(toDateTime('2023-04-21 10:17:00')): 2023-04-21 10:15:00
toStartOfFifteenMinutes(toDateTime('2023-04-21 10:20:00')): 2023-04-21 10:15:00
toStartOfFifteenMinutes(toDateTime('2023-04-21 10:23:00')): 2023-04-21 10:15:00
toStartOfFiveMinutes {#toStartOfFiveMinutes} | {"source_file": "date-time-functions.md"} | [
-0.043018221855163574,
-0.021702392026782036,
-0.013588584959506989,
0.04587874189019203,
-0.05841641128063202,
0.0605025514960289,
0.01191167626529932,
0.06461227685213089,
0.000601276580709964,
-0.030713742598891258,
0.01531720720231533,
-0.07118500769138336,
-0.009695261716842651,
0.033... |
103a1bfd-e2ab-47da-8333-ee730f6ea36e | toStartOfFiveMinutes {#toStartOfFiveMinutes}
Introduced in: v22.6
Rounds down a date with time to the start of the nearest five-minute interval.
:::note
The return type can be configured by setting
enable_extended_results_for_datetime_functions
.
:::
Syntax
sql
toStartOfFiveMinutes(datetime)
Aliases
:
toStartOfFiveMinute
Arguments
datetime
β A date with time to round.
DateTime
or
DateTime64
Returned value
Returns the date with time rounded to the start of the nearest five-minute interval
DateTime
or
DateTime64
Examples
Example
sql title=Query
SELECT
toStartOfFiveMinutes(toDateTime('2023-04-21 10:17:00')),
toStartOfFiveMinutes(toDateTime('2023-04-21 10:20:00')),
toStartOfFiveMinutes(toDateTime('2023-04-21 10:23:00'))
FORMAT Vertical
response title=Response
Row 1:
ββββββ
toStartOfFiveMinutes(toDateTime('2023-04-21 10:17:00')): 2023-04-21 10:15:00
toStartOfFiveMinutes(toDateTime('2023-04-21 10:20:00')): 2023-04-21 10:20:00
toStartOfFiveMinutes(toDateTime('2023-04-21 10:23:00')): 2023-04-21 10:20:00
toStartOfHour {#toStartOfHour}
Introduced in: v1.1
Rounds down a date with time to the start of the hour.
:::note
The return type can be configured by setting
enable_extended_results_for_datetime_functions
.
:::
Syntax
sql
toStartOfHour(datetime)
Arguments
datetime
β A date with time to round.
DateTime
or
DateTime64
Returned value
Returns the date with time rounded down to the start of the hour.
DateTime
or
DateTime64
Examples
Round down to the start of the hour
sql title=Query
SELECT
toStartOfHour(toDateTime('2023-04-21 10:20:30'));
response title=Response
ββββββββββββββββββresββ¬βtoTypeName(res)ββ
β 2023-04-21 10:00:00 β DateTime β
βββββββββββββββββββββββ΄ββββββββββββββββββ
toStartOfISOYear {#toStartOfISOYear}
Introduced in: v1.1
Rounds down a date or date with time to the first day of the ISO year, which can be different than a regular year. See
ISO week date
.
:::note
The return type can be configured by setting
enable_extended_results_for_datetime_functions
.
:::
Syntax
sql
toStartOfISOYear(value)
Arguments
value
β The date or date with time to round down to the first day of the ISO year.
Date
or
Date32
or
DateTime
or
DateTime64
Returned value
Returns the first day of the ISO year for the given date or date with time.
Date
Examples
Round down to the first day of the ISO year
sql title=Query
SELECT toStartOfISOYear(toDateTime('2023-04-21 10:20:30'))
response title=Response
ββtoStartOfISOYear(toDateTime('2023-04-21 10:20:30'))ββ
β 2023-01-02 β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
toStartOfInterval {#toStartOfInterval}
Introduced in: v20.1
This function generalizes other
toStartOf*()
functions with
toStartOfInterval(date_or_date_with_time, INTERVAL x unit [, time_zone])
syntax. | {"source_file": "date-time-functions.md"} | [
-0.020999256521463394,
0.022412655875086784,
-0.02299097739160061,
0.04823417589068413,
0.021007318049669266,
0.06203616410493851,
-0.017430707812309265,
0.0658092126250267,
0.015111129730939865,
0.02529127709567547,
-0.0703500360250473,
-0.07765369862318039,
-0.021647315472364426,
0.00632... |
2daa5906-5e60-4392-b05d-aa0e6129ebda | Introduced in: v20.1
This function generalizes other
toStartOf*()
functions with
toStartOfInterval(date_or_date_with_time, INTERVAL x unit [, time_zone])
syntax.
For example,
-
toStartOfInterval(t, INTERVAL 1 YEAR)
returns the same as
toStartOfYear(t)
,
-
toStartOfInterval(t, INTERVAL 1 MONTH)
returns the same as
toStartOfMonth(t)
,
-
toStartOfInterval(t, INTERVAL 1 DAY)
returns the same as
toStartOfDay(t)
,
-
toStartOfInterval(t, INTERVAL 15 MINUTE)
returns the same as
toStartOfFifteenMinutes(t)
.
The calculation is performed relative to specific points in time:
| Interval | Start |
|-------------|------------------------|
| YEAR | year 0 |
| QUARTER | 1900 Q1 |
| MONTH | 1900 January |
| WEEK | 1970, 1st week (01-05) |
| DAY | 1970-01-01 |
| HOUR | (
) |
| MINUTE | 1970-01-01 00:00:00 |
| SECOND | 1970-01-01 00:00:00 |
| MILLISECOND | 1970-01-01 00:00:00 |
| MICROSECOND | 1970-01-01 00:00:00 |
| NANOSECOND | 1970-01-01 00:00:00 |
(
) hour intervals are special: the calculation is always performed relative to 00:00:00 (midnight) of the current day. As a result, only
hour values between 1 and 23 are useful.
If unit
WEEK
was specified,
toStartOfInterval
assumes that weeks start on Monday. Note that this behavior is different from that of function
toStartOfWeek
in which weeks start by default on Sunday.
The second overload emulates TimescaleDB's
time_bucket()
function, respectively PostgreSQL's
date_bin()
function.
Syntax
sql
toStartOfInterval(value, INTERVAL x unit[, time_zone])
toStartOfInterval(value, INTERVAL x unit[, origin[, time_zone]])
Aliases
:
date_bin
,
time_bucket
Arguments
value
β Date or date with time value to round down.
Date
or
DateTime
or
DateTime64
x
β Interval length number. -
unit
β Interval unit: YEAR, QUARTER, MONTH, WEEK, DAY, HOUR, MINUTE, SECOND, MILLISECOND, MICROSECOND, NANOSECOND. -
time_zone
β Optional. Time zone name as a string. -
origin
β Optional. Origin point for calculation (second overload only).
Returned value
Returns the start of the interval containing the input value.
DateTime
Examples
Basic interval rounding
sql title=Query
SELECT toStartOfInterval(toDateTime('2023-01-15 14:30:00'), INTERVAL 1 MONTH)
response title=Response
ββtoStartOfIntβ―alMonth(1))ββ
β 2023-01-01 β
ββββββββββββββββββββββββββββ
Using origin point
sql title=Query
SELECT toStartOfInterval(toDateTime('2023-01-01 14:45:00'), INTERVAL 1 MINUTE, toDateTime('2023-01-01 14:35:30'))
response title=Response
ββtoStartOfIntβ―14:35:30'))ββ
β 2023-01-01 14:44:30 β
ββββββββββββββββββββββββββββ
toStartOfMicrosecond {#toStartOfMicrosecond}
Introduced in: v22.6
Rounds down a date with time to the start of the microseconds.
Syntax
sql
toStartOfMicrosecond(datetime, [timezone]) | {"source_file": "date-time-functions.md"} | [
0.002934260293841362,
-0.0031967395916581154,
-0.030693145468831062,
0.025626298040151596,
0.0023446381092071533,
0.050892554223537445,
-0.060642581433057785,
0.03864693641662598,
-0.015359589830040932,
0.017642751336097717,
-0.028797069564461708,
-0.07025299221277237,
0.03562237694859505,
... |
656bbb06-db87-4615-b879-f07cab7d6c6a | toStartOfMicrosecond {#toStartOfMicrosecond}
Introduced in: v22.6
Rounds down a date with time to the start of the microseconds.
Syntax
sql
toStartOfMicrosecond(datetime, [timezone])
Arguments
datetime
β Date and time.
DateTime64
timezone
β Optional. Timezone for the returned value. If not specified, the function uses the timezone of the
value
parameter.
String
Returned value
Input value with sub-microseconds
DateTime64
Examples
Query without timezone
sql title=Query
WITH toDateTime64('2020-01-01 10:20:30.999999999', 9) AS dt64
SELECT toStartOfMicrosecond(dt64);
response title=Response
βββββtoStartOfMicrosecond(dt64)ββ
β 2020-01-01 10:20:30.999999000 β
βββββββββββββββββββββββββββββββββ
Query with timezone
sql title=Query
WITH toDateTime64('2020-01-01 10:20:30.999999999', 9) AS dt64
SELECT toStartOfMicrosecond(dt64, 'Asia/Istanbul');
response title=Response
ββtoStartOfMicrosecond(dt64, 'Asia/Istanbul')ββ
β 2020-01-01 12:20:30.999999000 β
βββββββββββββββββββββββββββββββββββββββββββββββ
toStartOfMillisecond {#toStartOfMillisecond}
Introduced in: v22.6
Rounds down a date with time to the start of the milliseconds.
Syntax
sql
toStartOfMillisecond(datetime, [timezone])
Arguments
datetime
β Date and time.
DateTime64
timezone
β Optional. Timezone for the returned value. If not specified, the function uses the timezone of the
value
parameter.
String
Returned value
Input value with sub-milliseconds.
DateTime64
Examples
Query without timezone
sql title=Query
WITH toDateTime64('2020-01-01 10:20:30.999999999', 9) AS dt64
SELECT toStartOfMillisecond(dt64);
response title=Response
βββββtoStartOfMillisecond(dt64)ββ
β 2020-01-01 10:20:30.999000000 β
βββββββββββββββββββββββββββββββββ
Query with timezone
sql title=Query
WITH toDateTime64('2020-01-01 10:20:30.999999999', 9) AS dt64
SELECT toStartOfMillisecond(dt64, 'Asia/Istanbul');
response title=Response
ββtoStartOfMillisecond(dt64, 'Asia/Istanbul')ββ
β 2020-01-01 12:20:30.999000000 β
βββββββββββββββββββββββββββββββββββββββββββββββ
toStartOfMinute {#toStartOfMinute}
Introduced in: v1.1
Rounds down a date with time to the start of the minute.
:::note
The return type can be configured by setting
enable_extended_results_for_datetime_functions
.
:::
Syntax
sql
toStartOfMinute(datetime)
Arguments
datetime
β A date with time to round.
DateTime
or
DateTime64
Returned value
Returns the date with time rounded down to the start of the minute.
DateTime
or
DateTime64
Examples
Round down to the start of the minute
sql title=Query
SELECT
toStartOfMinute(toDateTime('2023-04-21 10:20:30')),
toStartOfMinute(toDateTime64('2023-04-21 10:20:30.5300', 8))
FORMAT Vertical
response title=Response
Row 1:
ββββββ
toStartOfMinute(toDateTime('2023-04-21 10:20:30')): 2023-04-21 10:20:00
toStartOfMinute(toDateTime64('2023-04-21 10:20:30.5300', 8)): 2023-04-21 10:20:00 | {"source_file": "date-time-functions.md"} | [
0.037447210401296616,
-0.003903592238202691,
-0.07141346484422684,
0.04010865092277527,
-0.0022863205522298813,
0.04074116051197052,
0.009186451323330402,
0.04060368239879608,
-0.0012372725177556276,
0.02908993698656559,
-0.06300371885299683,
-0.11001815646886826,
-0.01824033260345459,
-0.... |
c06ca035-9145-4315-a72b-d27fb25b3e30 | toStartOfMonth {#toStartOfMonth}
Introduced in: v1.1
Rounds down a date or date with time to the first day of the month.
:::note
The return type can be configured by setting
enable_extended_results_for_datetime_functions
.
:::
Syntax
sql
toStartOfMonth(value)
Arguments
value
β The date or date with time to round down to the first day of the month.
Date
or
Date32
or
DateTime
or
DateTime64
Returned value
Returns the first day of the month for the given date or date with time.
Date
Examples
Round down to the first day of the month
sql title=Query
SELECT toStartOfMonth(toDateTime('2023-04-21 10:20:30'))
response title=Response
ββtoStartOfMonth(toDateTime('2023-04-21 10:20:30'))ββ
β 2023-04-01 β
βββββββββββββββββββββββββββββββββββββββββββββββββββββ
toStartOfNanosecond {#toStartOfNanosecond}
Introduced in: v22.6
Rounds down a date with time to the start of the nanoseconds.
Syntax
sql
toStartOfNanosecond(datetime, [timezone])
Arguments
datetime
β Date and time.
DateTime64
timezone
β Optional. Timezone for the returned value. If not specified, the function uses the timezone of the
value
parameter.
String
Returned value
Input value with nanoseconds.
DateTime64
Examples
Query without timezone
sql title=Query
WITH toDateTime64('2020-01-01 10:20:30.999999999', 9) AS dt64
SELECT toStartOfNanosecond(dt64);
response title=Response
ββββββtoStartOfNanosecond(dt64)ββ
β 2020-01-01 10:20:30.999999999 β
βββββββββββββββββββββββββββββββββ
Query with timezone
sql title=Query
WITH toDateTime64('2020-01-01 10:20:30.999999999', 9) AS dt64
SELECT toStartOfNanosecond(dt64, 'Asia/Istanbul');
response title=Response
ββtoStartOfNanosecond(dt64, 'Asia/Istanbul')ββ
β 2020-01-01 12:20:30.999999999 β
ββββββββββββββββββββββββββββββββββββββββββββββ
toStartOfQuarter {#toStartOfQuarter}
Introduced in: v1.1
Rounds down a date or date with time to the first day of the quarter. The first day of the quarter is either 1 January, 1 April, 1 July, or 1 October.
:::note
The return type can be configured by setting
enable_extended_results_for_datetime_functions
.
:::
Syntax
sql
toStartOfQuarter(value)
Arguments
value
β The date or date with time to round down to the first day of the quarter.
Date
or
Date32
or
DateTime
or
DateTime64
Returned value
Returns the first day of the quarter for the given date or date with time.
Date
Examples
Round down to the first day of the quarter
sql title=Query
SELECT toStartOfQuarter(toDateTime('2023-04-21 10:20:30'))
response title=Response
ββtoStartOfQuarter(toDateTime('2023-04-21 10:20:30'))ββ
β 2023-04-01 β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
toStartOfSecond {#toStartOfSecond}
Introduced in: v20.5
Rounds down a date with time to the start of the seconds.
Syntax
sql
toStartOfSecond(datetime, [timezone]) | {"source_file": "date-time-functions.md"} | [
0.0015363090205937624,
-0.022708173841238022,
-0.06542889028787613,
0.07577752321958542,
-0.012766492553055286,
0.014650357887148857,
0.027411097660660744,
0.051562901586294174,
-0.030106887221336365,
0.05591818690299988,
-0.05396026372909546,
-0.06524427980184555,
0.0019688978791236877,
-... |
39c33534-9773-4d89-a012-9b5ad3545622 | toStartOfSecond {#toStartOfSecond}
Introduced in: v20.5
Rounds down a date with time to the start of the seconds.
Syntax
sql
toStartOfSecond(datetime, [timezone])
Arguments
datetime
β Date and time to truncate sub-seconds from.
DateTime64
timezone
β Optional. Timezone for the returned value. If not specified, the function uses the timezone of the
value
parameter.
String
Returned value
Returns the input value without sub-seconds.
DateTime64
Examples
Query without timezone
sql title=Query
WITH toDateTime64('2020-01-01 10:20:30.999', 3) AS dt64
SELECT toStartOfSecond(dt64);
response title=Response
ββββtoStartOfSecond(dt64)ββ
β 2020-01-01 10:20:30.000 β
βββββββββββββββββββββββββββ
Query with timezone
sql title=Query
WITH toDateTime64('2020-01-01 10:20:30.999', 3) AS dt64
SELECT toStartOfSecond(dt64, 'Asia/Istanbul');
response title=Response
ββtoStartOfSecond(dt64, 'Asia/Istanbul')ββ
β 2020-01-01 13:20:30.000 β
ββββββββββββββββββββββββββββββββββββββββββ
toStartOfTenMinutes {#toStartOfTenMinutes}
Introduced in: v20.1
Rounds down a date with time to the start of the nearest ten-minute interval.
:::note
The return type can be configured by setting
enable_extended_results_for_datetime_functions
.
:::
Syntax
sql
toStartOfTenMinutes(datetime)
Arguments
datetime
β A date with time.
DateTime
or
DateTime64
Returned value
Returns the date with time rounded to the start of the nearest ten-minute interval
DateTime
or
DateTime64
Examples
Example
sql title=Query
SELECT
toStartOfTenMinutes(toDateTime('2023-04-21 10:17:00')),
toStartOfTenMinutes(toDateTime('2023-04-21 10:20:00')),
toStartOfTenMinutes(toDateTime('2023-04-21 10:23:00'))
FORMAT Vertical
response title=Response
Row 1:
ββββββ
toStartOfTenMinutes(toDateTime('2023-04-21 10:17:00')): 2023-04-21 10:10:00
toStartOfTenMinutes(toDateTime('2023-04-21 10:20:00')): 2023-04-21 10:20:00
toStartOfTenMinutes(toDateTime('2023-04-21 10:23:00')): 2023-04-21 10:20:00
toStartOfWeek {#toStartOfWeek}
Introduced in: v20.1
Rounds a date or date with time down to the nearest Sunday or Monday.
:::note
The return type can be configured by setting
enable_extended_results_for_datetime_functions
.
:::
Syntax
sql
toStartOfWeek(datetime[, mode[, timezone]])
Arguments
datetime
β A date or date with time to convert.
Date
or
DateTime
or
Date32
or
DateTime64
mode
β Determines the first day of the week as described in the
toWeek()
function. Default
0
.
UInt8
timezone
β The timezone to use for the conversion. If not specified, the server's timezone is used.
String
Returned value
Returns the date of the nearest Sunday or Monday on, or prior to, the given date, depending on the mode
Date
or
Date32
or
DateTime
or
DateTime64
Examples
Round down to the nearest Sunday or Monday | {"source_file": "date-time-functions.md"} | [
0.057412441819906235,
0.002931508468464017,
-0.06978625059127808,
0.04290473088622093,
-0.010050665587186813,
-0.013109191320836544,
0.007922378368675709,
0.023581573739647865,
0.028395602479577065,
0.028256896883249283,
-0.06613407284021378,
-0.08796233683824539,
-0.02174883894622326,
-0.... |
886595d8-8994-4248-828c-e282fce0ffd2 | Examples
Round down to the nearest Sunday or Monday
sql title=Query
SELECT
toStartOfWeek(toDateTime('2023-04-21 10:20:30')), /* a Friday */
toStartOfWeek(toDateTime('2023-04-21 10:20:30'), 1), /* a Friday */
toStartOfWeek(toDate('2023-04-24')), /* a Monday */
toStartOfWeek(toDate('2023-04-24'), 1) /* a Monday */
FORMAT Vertical
response title=Response
Row 1:
ββββββ
toStartOfWeek(toDateTime('2023-04-21 10:20:30')): 2023-04-17
toStartOfWeek(toDateTime('2023-04-21 10:20:30'), 1): 2023-04-17
toStartOfWeek(toDate('2023-04-24')): 2023-04-24
toStartOfWeek(toDate('2023-04-24'), 1): 2023-04-24
toStartOfYear {#toStartOfYear}
Introduced in: v1.1
Rounds down a date or date with time to the first day of the year. Returns the date as a
Date
object.
:::note
The return type can be configured by setting
enable_extended_results_for_datetime_functions
.
:::
Syntax
sql
toStartOfYear(value)
Arguments
value
β The date or date with time to round down.
Date
or
Date32
or
DateTime
or
DateTime64
Returned value
Returns the first day of the year for the given date/time
Date
Examples
Round down to the first day of the year
sql title=Query
SELECT toStartOfYear(toDateTime('2023-04-21 10:20:30'))
response title=Response
ββtoStartOfYear(toDateTime('2023-04-21 10:20:30'))ββ
β 2023-01-01 β
ββββββββββββββββββββββββββββββββββββββββββββββββββββ
toTimeWithFixedDate {#toTimeWithFixedDate}
Introduced in: v1.1
Extracts the time component of a date or date with time.
The returned result is an offset to a fixed point in time, currently
1970-01-02
,
but the exact point in time is an implementation detail which may change in future.
toTime
should therefore not be used standalone.
The main purpose of the function is to calculate the time difference between two dates or dates with time, e.g.,
toTime(dt1) - toTime(dt2)
.
Syntax
sql
toTime(date[, timezone])
Arguments
date
β Date to convert to a time.
Date
or
DateTime
or
DateTime64
timezone
β Optional. Timezone for the returned value.
String
Returned value
Returns the time component of a date or date with time in the form of an offset to a fixed point in time (selected as 1970-01-02, currently).
DateTime
Examples
Calculate the time difference between two dates
sql title=Query
SELECT toTime('2025-06-15 12:00:00'::DateTime) - toTime('2024-05-10 11:00:00'::DateTime) AS result, toTypeName(result)
response title=Response
ββresultββ¬βtoTypeName(result)ββ
β 3600 β Int32 β
ββββββββββ΄βββββββββββββββββββββ
toTimezone {#toTimezone}
Introduced in: v1.1
Converts a
DateTime
or
DateTime64
to the specified time zone.
The internal value (number of unix seconds) of the data doesn't change.
Only the value's time zone attribute and the value's string representation changes.
Syntax | {"source_file": "date-time-functions.md"} | [
-0.017932450398802757,
0.04561549052596092,
0.025646282359957695,
0.024569213390350342,
-0.02373986691236496,
0.059589557349681854,
-0.07275570183992386,
-0.006546495482325554,
-0.0386042483150959,
-0.021315651014447212,
-0.06940220296382904,
-0.06371065229177475,
-0.027602821588516235,
-0... |
4fda59d6-0f3e-4ac9-bb8b-8da7c00b3015 | Syntax
sql
toTimeZone(datetime, timezone)
Aliases
:
toTimeZone
Arguments
date
β The value to convert.
DateTime
or
DateTime64
timezone
β The target time zone name.
String
Returned value
Returns the same timestamp as the input, but with the specified time zone
DateTime
or
DateTime64
Examples
Usage example
sql title=Query
SELECT toDateTime('2019-01-01 00:00:00', 'UTC') AS time_utc,
toTypeName(time_utc) AS type_utc,
toInt32(time_utc) AS int32utc,
toTimeZone(time_utc, 'Asia/Yekaterinburg') AS time_yekat,
toTypeName(time_yekat) AS type_yekat,
toInt32(time_yekat) AS int32yekat,
toTimeZone(time_utc, 'US/Samoa') AS time_samoa,
toTypeName(time_samoa) AS type_samoa,
toInt32(time_samoa) AS int32samoa
FORMAT Vertical;
response title=Response
Row 1:
ββββββ
time_utc: 2019-01-01 00:00:00
type_utc: DateTime('UTC')
int32utc: 1546300800
time_yekat: 2019-01-01 05:00:00
type_yekat: DateTime('Asia/Yekaterinburg')
int32yekat: 1546300800
time_samoa: 2018-12-31 13:00:00
type_samoa: DateTime('US/Samoa')
int32samoa: 1546300800
toUTCTimestamp {#toUTCTimestamp}
Introduced in: v23.8
Converts a date or date with time value from one time zone to UTC timezone timestamp. This function is mainly included for compatibility with Apache Spark and similar frameworks.
Syntax
sql
toUTCTimestamp(datetime, time_zone)
Aliases
:
to_utc_timestamp
Arguments
datetime
β A date or date with time type const value or an expression.
DateTime
or
DateTime64
time_zone
β A String type const value or an expression representing the time zone.
String
Returned value
Returns a date or date with time in UTC timezone.
DateTime
or
DateTime64
Examples
Convert timezone to UTC
sql title=Query
SELECT toUTCTimestamp(toDateTime('2023-03-16'), 'Asia/Shanghai')
response title=Response
ββtoUTCTimestamp(toDateTime('2023-03-16'), 'Asia/Shanghai')ββ
β 2023-03-15 16:00:00 β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
toUnixTimestamp {#toUnixTimestamp}
Introduced in: v1.1
Converts a
String
,
Date
, or
DateTime
to a Unix timestamp (seconds since
1970-01-01 00:00:00 UTC
) as
UInt32
.
Syntax
sql
toUnixTimestamp(date, [timezone])
Arguments
date
β Value to convert.
Date
or
Date32
or
DateTime
or
DateTime64
or
String
timezone
β Optional. Timezone to use for conversion. If not specified, the server's timezone is used.
String
Returned value
Returns the Unix timestamp.
UInt32
Examples
Usage example
sql title=Query
SELECT
'2017-11-05 08:07:47' AS dt_str,
toUnixTimestamp(dt_str) AS from_str,
toUnixTimestamp(dt_str, 'Asia/Tokyo') AS from_str_tokyo,
toUnixTimestamp(toDateTime(dt_str)) AS from_datetime,
toUnixTimestamp(toDateTime64(dt_str, 0)) AS from_datetime64,
toUnixTimestamp(toDate(dt_str)) AS from_date,
toUnixTimestamp(toDate32(dt_str)) AS from_date32
FORMAT Vertical; | {"source_file": "date-time-functions.md"} | [
0.043776411563158035,
0.008535152301192284,
-0.05128169059753418,
0.018761519342660904,
-0.01167435571551323,
-0.07461915910243988,
0.043126992881298065,
0.057025130838155746,
-0.029357872903347015,
0.005912184249609709,
-0.036806099116802216,
-0.14757093787193298,
-0.006462428718805313,
0... |
f5ff0d7e-c3d3-4b18-bb6c-2350aa46ea22 | response title=Response
Row 1:
ββββββ
dt_str: 2017-11-05 08:07:47
from_str: 1509869267
from_str_tokyo: 1509836867
from_datetime: 1509869267
from_datetime64: 1509869267
from_date: 1509840000
from_date32: 1509840000
toWeek {#toWeek}
Introduced in: v20.1
This function returns the week number for date or datetime. The two-argument form of
toWeek()
enables you to specify whether the week starts
on Sunday or Monday and whether the return value should be in the range from
0
to
53
or from
1
to
53
.
toISOWeek()
is a compatibility function that is equivalent to
toWeek(date,3)
.
The following table describes how the mode argument works.
| Mode | First day of week | Range | Week 1 is the first week ... |
|------|-------------------|-------|---------------------------------|
| 0 | Sunday | 0-53 | with a Sunday in this year |
| 1 | Monday | 0-53 | with 4 or more days this year |
| 2 | Sunday | 1-53 | with a Sunday in this year |
| 3 | Monday | 1-53 | with 4 or more days this year |
| 4 | Sunday | 0-53 | with 4 or more days this year |
| 5 | Monday | 0-53 | with a Monday in this year |
| 6 | Sunday | 1-53 | with 4 or more days this year |
| 7 | Monday | 1-53 | with a Monday in this year |
| 8 | Sunday | 1-53 | contains January 1 |
| 9 | Monday | 1-53 | contains January 1 |
For mode values with a meaning of "with 4 or more days this year," weeks are numbered according to ISO 8601:1988:
If the week containing January 1 has 4 or more days in the new year, it is week 1.
Otherwise, it is the last week of the previous year, and the next week is week 1.
For mode values with a meaning of "contains January 1", the week contains January 1 is week 1.
It does not matter how many days in the new year the week contained, even if it contained only one day.
I.e. if the last week of December contains January 1 of the next year, it will be week 1 of the next year.
The first argument can also be specified as
String
in a format supported by
parseDateTime64BestEffort()
. Support for string arguments exists only for reasons of compatibility with MySQL which is expected by certain 3rd party tools. As string argument support may in future be made dependent on new MySQL-compatibility settings and because string parsing is generally slow, it is recommended to not use it.
Syntax
sql
toWeek(datetime[, mode[, time_zone]])
Aliases
:
week
Arguments
datetime
β Date or date with time to get the week number from.
Date
or
DateTime
mode
β Optional. A mode
0
to
9
determines the first day of the week and the range of the week number. Default
0
. -
time_zone
β Optional. Time zone.
String
Returned value
Returns the week number according to the specified mode.
UInt32
Examples | {"source_file": "date-time-functions.md"} | [
-0.07256459444761276,
0.057260408997535706,
-0.007688107900321484,
0.041229497641325,
-0.05438372492790222,
0.0283189807087183,
-0.06511648744344711,
0.022548014298081398,
-0.09875648468732834,
-0.05486297979950905,
-0.016788378357887268,
-0.10402237623929977,
-0.06652381271123886,
-0.0038... |
fe39e593-a84c-4f83-8b27-e3fab6a2c2c2 | Returned value
Returns the week number according to the specified mode.
UInt32
Examples
Get week numbers with different modes
sql title=Query
SELECT toDate('2016-12-27') AS date, toWeek(date) AS week0, toWeek(date,1) AS week1, toWeek(date,9) AS week9
response title=Response
ββββββββdateββ¬βweek0ββ¬βweek1ββ¬βweek9ββ
β 2016-12-27 β 52 β 52 β 1 β
ββββββββββββββ΄ββββββββ΄ββββββββ΄ββββββββ
toYYYYMM {#toYYYYMM}
Introduced in: v1.1
Converts a date or date with time to a
UInt32
number containing the year and month number (YYYY * 100 + MM).
Accepts a second optional timezone argument. If provided, the timezone must be a string constant.
This function is the opposite of function
YYYYMMDDToDate()
.
Syntax
sql
toYYYYMM(datetime[, timezone])
Arguments
datetime
β A date or date with time to convert.
Date
or
Date32
or
DateTime
or
DateTime64
timezone
β Optional. Timezone for the conversion. If provided, the timezone must be a string constant.
String
Returned value
Returns a UInt32 number containing the year and month number (YYYY * 100 + MM).
UInt32
Examples
Convert current date to YYYYMM format
sql title=Query
SELECT toYYYYMM(now(), 'US/Eastern')
response title=Response
ββtoYYYYMM(now(), 'US/Eastern')ββ
β 202303 β
βββββββββββββββββββββββββββββββββ
toYYYYMMDD {#toYYYYMMDD}
Introduced in: v1.1
Converts a date or date with time to a
UInt32
number containing the year and month number (YYYY * 10000 + MM * 100 + DD). Accepts a second optional timezone argument. If provided, the timezone must be a string constant.
Syntax
sql
toYYYYMMDD(datetime[, timezone])
Arguments
datetime
β A date or date with time to convert.
Date
or
Date32
or
DateTime
or
DateTime64
timezone
β Optional. Timezone for the conversion. If provided, the timezone must be a string constant.
String
Returned value
Returns a
UInt32
number containing the year, month and day (YYYY * 10000 + MM * 100 + DD).
UInt32
Examples
Convert current date to YYYYMMDD format
sql title=Query
SELECT toYYYYMMDD(now(), 'US/Eastern')
response title=Response
ββtoYYYYMMDD(now(), 'US/Eastern')ββ
β 20230302 β
βββββββββββββββββββββββββββββββββββ
toYYYYMMDDhhmmss {#toYYYYMMDDhhmmss}
Introduced in: v1.1
Converts a date or date with time to a
UInt64
number containing the year and month number (YYYY * 10000000000 + MM * 100000000 + DD * 1000000 + hh * 10000 + mm * 100 + ss).
Accepts a second optional timezone argument. If provided, the timezone must be a string constant.
Syntax
sql
toYYYYMMDDhhmmss(datetime[, timezone])
Arguments
datetime
β Date or date with time to convert.
Date
or
Date32
or
DateTime
or
DateTime64
timezone
β Optional. Timezone for the conversion. If provided, the timezone must be a string constant.
String
Returned value | {"source_file": "date-time-functions.md"} | [
0.02008979022502899,
0.002098512602970004,
-0.02103409916162491,
0.02453719638288021,
-0.06741909682750702,
0.035197146236896515,
0.0478786937892437,
0.032160647213459015,
-0.14021578431129456,
-0.039204422384500504,
-0.031794607639312744,
-0.09464360028505325,
-0.01940583623945713,
0.0051... |
0c0ae273-b130-47af-bc27-6ca7e86a9f09 | timezone
β Optional. Timezone for the conversion. If provided, the timezone must be a string constant.
String
Returned value
Returns a
UInt64
number containing the year, month, day, hour, minute and second (YYYY * 10000000000 + MM * 100000000 + DD * 1000000 + hh * 10000 + mm * 100 + ss).
UInt64
Examples
Convert current date and time to YYYYMMDDhhmmss format
sql title=Query
SELECT toYYYYMMDDhhmmss(now(), 'US/Eastern')
response title=Response
ββtoYYYYMMDDhhmmss(now(), 'US/Eastern')ββ
β 20230302112209 β
βββββββββββββββββββββββββββββββββββββββββ
toYear {#toYear}
Introduced in: v1.1
Returns the year component (AD) of a
Date
or
DateTime
value.
Syntax
sql
toYear(datetime)
Aliases
:
YEAR
Arguments
datetime
β Date or date with time to get the year from.
Date
or
Date32
or
DateTime
or
DateTime64
Returned value
Returns the year of the given Date or DateTime
UInt16
Examples
Usage example
sql title=Query
SELECT toYear(toDateTime('2023-04-21 10:20:30'))
response title=Response
ββtoYear(toDateTime('2023-04-21 10:20:30'))ββ
β 2023 β
βββββββββββββββββββββββββββββββββββββββββββββ
toYearNumSinceEpoch {#toYearNumSinceEpoch}
Introduced in: v25.3
Returns amount of years passed from year 1970
Syntax
sql
toYearNumSinceEpoch(date)
Arguments
date
β A date or date with time to convert.
Date
or
DateTime
or
DateTime64
Returned value
Positive integer
Examples
Example
sql title=Query
SELECT toYearNumSinceEpoch(toDate('2024-10-01'))
response title=Response
54
toYearWeek {#toYearWeek}
Introduced in: v20.1
Returns the year and week for a date. The year in the result may be different from the year in the date argument for the first and the last week of the year.
The mode argument works like the mode argument of
toWeek()
.
Warning: The week number returned by
toYearWeek()
can be different from what the
toWeek()
returns.
toWeek()
always returns week number in the context of the given year, and in case
toWeek()
returns
0
,
toYearWeek()
returns the value corresponding to the last week of previous year. See
prev_yearWeek
in example below.
The first argument can also be specified as
String
in a format supported by
parseDateTime64BestEffort()
. Support for string arguments exists only for reasons of compatibility with MySQL which is expected by certain 3rd party tools. As string argument support may in future be made dependent on new MySQL-compatibility settings and because string parsing is generally slow, it is recommended to not use it.
Syntax
sql
toYearWeek(datetime[, mode[, timezone]])
Aliases
:
yearweek
Arguments
datetime
β Date or date with time to get the year and week of.
Date
or
DateTime
mode
β Optional. A mode
0
to
9
determines the first day of the week and the range of the week number. Default
0
. -
timezone
β Optional. Time zone.
String
Returned value | {"source_file": "date-time-functions.md"} | [
0.04167556390166283,
0.007088780403137207,
-0.01852325163781643,
0.011057153344154358,
-0.027821633964776993,
-0.019749417901039124,
0.005403244402259588,
0.04062803089618683,
-0.04359808936715126,
0.0017001728992909193,
-0.016792098060250282,
-0.10633471608161926,
-0.013390596956014633,
0... |
c3342ab2-adf5-40d5-ba53-e69e3898bd90 | mode
β Optional. A mode
0
to
9
determines the first day of the week and the range of the week number. Default
0
. -
timezone
β Optional. Time zone.
String
Returned value
Returns year and week number as a combined integer value.
UInt32
Examples
Get year-week combinations with different modes
sql title=Query
SELECT toDate('2016-12-27') AS date, toYearWeek(date) AS yearWeek0, toYearWeek(date,1) AS yearWeek1, toYearWeek(date,9) AS yearWeek9, toYearWeek(toDate('2022-01-01')) AS prev_yearWeek
response title=Response
ββββββββdateββ¬βyearWeek0ββ¬βyearWeek1ββ¬βyearWeek9ββ¬βprev_yearWeekββ
β 2016-12-27 β 201652 β 201652 β 201701 β 202152 β
ββββββββββββββ΄ββββββββββββ΄ββββββββββββ΄ββββββββββββ΄ββββββββββββββββ
today {#today}
Introduced in: v1.1
Returns the current date at moment of query analysis. Same as
toDate(now())
.
Syntax
sql
today()
Aliases
:
curdate
,
current_date
Arguments
None.
Returned value
Returns the current date
Date
Examples
Usage example
sql title=Query
SELECT today() AS today, curdate() AS curdate, current_date() AS current_date FORMAT Pretty
response title=Response
ββββββββββββββ³βββββββββββββ³βββββββββββββββ
β today β curdate β current_date β
β‘βββββββββββββββββββββββββββββββββββββββββ©
β 2025-03-03 β 2025-03-03 β 2025-03-03 β
ββββββββββββββ΄βββββββββββββ΄βββββββββββββββ
yesterday {#yesterday}
Introduced in: v1.1
Accepts zero arguments and returns yesterday's date at one of the moments of query analysis.
Syntax
sql
yesterday()
Arguments
None.
Returned value
Returns yesterday's date.
Date
Examples
Get yesterday's date
sql title=Query
SELECT yesterday();
SELECT today() - 1;
response title=Response
ββyesterday()ββ
β 2025-06-09 β
βββββββββββββββ
ββminus(today(), 1)ββ
β 2025-06-09 β
βββββββββββββββββββββ | {"source_file": "date-time-functions.md"} | [
-0.024053962901234627,
0.018722357228398323,
-0.034866414964199066,
0.05630795657634735,
-0.039468735456466675,
0.03349420428276062,
0.018037427216768265,
-0.0004988079308532178,
-0.09695955365896225,
-0.036428920924663544,
-0.04710030183196068,
-0.10284887999296188,
-0.07719756662845612,
... |
4fb387ba-8c5a-4082-8be6-944f93dcb9b0 | description: 'Documentation for logical functions'
sidebar_label: 'Logical'
slug: /sql-reference/functions/logical-functions
title: 'Logical functions'
doc_type: 'reference'
Logical functions
The functions below perform logical operations on arguments of arbitrary numeric types.
They return either
0
or
1
as
UInt8
or in some cases
NULL
.
Zero as an argument is considered
false
, non-zero values are considered
true
.
and {#and}
Introduced in: v1.1
Calculates the logical conjunction of two or more values.
Setting
short_circuit_function_evaluation
controls whether short-circuit evaluation is used.
If enabled,
val_i
is evaluated only if
(val_1 AND val_2 AND ... AND val_{i-1})
is
true
.
For example, with short-circuit evaluation, no division-by-zero exception is thrown when executing the query
SELECT and(number = 2, intDiv(1, number)) FROM numbers(5)
.
Zero as an argument is considered
false
, non-zero values are considered
true
.
Syntax
sql
and(val1, val2[, ...])
Arguments
val1, val2[, ...]
β List of at least two values.
Nullable((U)Int*)
or
Nullable(Float*)
Returned value
Returns:
-
0
, if at least one argument evaluates to
false
-
NULL
, if no argument evaluates to
false
and at least one argument is
NULL
-
1
, otherwise
Nullable(UInt8)
Examples
Basic usage
sql title=Query
SELECT and(0, 1, -2);
response title=Response
0
With NULL
sql title=Query
SELECT and(NULL, 1, 10, -2);
response title=Response
α΄Ία΅α΄Έα΄Έ
not {#not}
Introduced in: v1.1
Calculates the logical negation of a value.
Zero as an argument is considered
false
, non-zero values are considered
true
.
Syntax
sql
not(val)
Arguments
val
β The value.
(U)Int*
or
Float*
Returned value
Returns:
-
1
, if
val
evaluates to
false
-
0
, if
val
evaluates to
true
-
NULL
, if
val
is
NULL
.
Nullable(UInt8)
Examples
Basic usage
sql title=Query
SELECT NOT(1);
response title=Response
0
or {#or}
Introduced in: v1.1
Calculates the logical disjunction of two or more values.
Setting
short_circuit_function_evaluation
controls whether short-circuit evaluation is used.
If enabled,
val_i
is evaluated only if
((NOT val_1) AND (NOT val_2) AND ... AND (NOT val_{i-1}))
is
true
.
For example, with short-circuit evaluation, no division-by-zero exception is thrown when executing the query
SELECT or(number = 0, intDiv(1, number) != 0) FROM numbers(5)
.
Zero as an argument is considered
false
, non-zero values are considered
true
.
Syntax
sql
or(val1, val2[, ...])
Arguments
val1, val2[, ...]
β List of at least two values.
Nullable((U)Int*)
or
Nullable(Float*)
Returned value
Returns:
-
1
, if at least one argument evaluates to
true
-
0
, if all arguments evaluate to
false
-
NULL
, if all arguments evaluate to
false
and at least one argument is
NULL
Nullable(UInt8)
Examples
Basic usage | {"source_file": "logical-functions.md"} | [
0.04224082827568054,
0.046910181641578674,
0.0010955241741612554,
-0.0037165090907365084,
-0.034459326416254044,
-0.010629258118569851,
0.04935045540332794,
0.030329374596476555,
-0.03388874977827072,
-0.012356891296803951,
0.030753472819924355,
-0.020899467170238495,
0.06451362371444702,
... |
8161bc6c-2203-451a-9de3-0edb8f1c7ab6 | -
0
, if all arguments evaluate to
false
-
NULL
, if all arguments evaluate to
false
and at least one argument is
NULL
Nullable(UInt8)
Examples
Basic usage
sql title=Query
SELECT or(1, 0, 0, 2, NULL);
response title=Response
1
With NULL
sql title=Query
SELECT or(0, NULL);
response title=Response
α΄Ία΅α΄Έα΄Έ
xor {#xor}
Introduced in: v1.1
Calculates the logical exclusive disjunction of two or more values.
For more than two input values, the function first xor-s the first two values, then xor-s the result with the third value etc.
Zero as an argument is considered
false
, non-zero values are considered
true
.
Syntax
sql
xor(val1, val2[, ...])
Arguments
val1, val2[, ...]
β List of at least two values.
Nullable((U)Int*)
or
Nullable(Float*)
Returned value
Returns:
-
1
, for two values: if one of the values evaluates to
false
and other does not
-
0
, for two values: if both values evaluate to
false
or to both
true
-
NULL
, if at least one of the inputs is
NULL
.
Nullable(UInt8)
Examples
Basic usage
sql title=Query
SELECT xor(0, 1, 1);
response title=Response
0 | {"source_file": "logical-functions.md"} | [
-0.007236242759972811,
0.016791239380836487,
-0.09776285290718079,
-0.021058276295661926,
-0.025936154648661613,
-0.07337458431720734,
0.08694835752248764,
-0.014027828350663185,
-0.028796346858143806,
-0.07132093608379364,
0.04608717933297157,
-0.07603892683982849,
0.07235869020223618,
0.... |
090c698d-bb1a-446a-8af1-68a7701952bc | description: 'Documentation for rounding functions'
sidebar_label: 'Rounding'
slug: /sql-reference/functions/rounding-functions
title: 'Rounding functions'
doc_type: 'reference'
Rounding functions
:::note
The documentation below is generated from the
system.functions
system table
:::
ceil {#ceil}
Introduced in: v1.1
Like
floor
but returns the smallest rounded number greater than or equal to
x
.
If rounding causes an overflow (for example,
ceiling(255, -1)
), the result is undefined.
Syntax
sql
ceiling(x[, N])
Aliases
:
ceiling
Arguments
x
β The value to round.
Float*
or
Decimal*
or
(U)Int*
N
β Optional. The number of decimal places to round to. Defaults to zero, which means rounding to an integer. Can be negative.
(U)Int*
Returned value
Returns a rounded number of the same type as
x
.
Float*
or
Decimal*
or
(U)Int*
Examples
Basic usage
sql title=Query
SELECT ceiling(123.45, 1) AS rounded
response title=Response
ββroundedββ
β 123.5 β
βββββββββββ
Negative precision
sql title=Query
SELECT ceiling(123.45, -1)
response title=Response
ββceiling(123.45, -1)ββ
β 130 β
βββββββββββββββββββββββ
floor {#floor}
Introduced in: v1.1
Returns the largest rounded number less than or equal to
x
, where the rounded number is a multiple of
1 / 10 * N
, or the nearest number of the appropriate data type if
1 / 10 * N
isn't exact.
Integer arguments may be rounded with a negative
N
argument.
With non-negative
N
the function returns
x
.
If rounding causes an overflow (for example,
floor(-128, -1)
), the result is undefined.
Syntax
sql
floor(x[, N])
Arguments
x
β The value to round.
Float*
or
Decimal*
or
(U)Int*
N
β Optional. The number of decimal places to round to. Defaults to zero, which means rounding to an integer. Can be negative.
(U)Int*
Returned value
Returns a rounded number of the same type as
x
.
Float*
or
Decimal*
or
(U)Int*
Examples
Usage example
sql title=Query
SELECT floor(123.45, 1) AS rounded
response title=Response
ββroundedββ
β 123.4 β
βββββββββββ
Negative precision
sql title=Query
SELECT floor(123.45, -1)
response title=Response
ββfloor(123.45, -1)ββ
β 120 β
βββββββββββββββββββββ
round {#round}
Introduced in: v1.1
Rounds a value to a specified number of decimal places
N
.
If
N > 0
, the function rounds to the right of the decimal point.
If
N < 0
, the function rounds to the left of the decimal point.
If
N = 0
, the function rounds to the next integer.
The function returns the nearest number of the specified order.
If the input value has equal distance to two neighboring numbers, the function uses banker's rounding for
Float*
inputs and rounds away from zero for the other number types (
Decimal*
).
If rounding causes an overflow (for example,
round(255, -1)
), the result is undefined.
Syntax
sql
round(x[, N])
Arguments | {"source_file": "rounding-functions.md"} | [
-0.023101964965462685,
0.02719016931951046,
-0.038799360394477844,
-0.008662614040076733,
-0.057595252990722656,
-0.11160261929035187,
-0.00019349496869836003,
0.11506547778844833,
0.031155234202742577,
-0.009620722383260727,
0.00945601798593998,
-0.08663800358772278,
0.04906954988837242,
... |
1e871b28-d4d5-4cfe-abc9-3821ac2095bf | If rounding causes an overflow (for example,
round(255, -1)
), the result is undefined.
Syntax
sql
round(x[, N])
Arguments
x
β A number to round.
Float*
or
Decimal*
or
(U)Int*
N
β Optional. The number of decimal places to round to. Defaults to
0
.
(U)Int*
Returned value
Returns a rounded number of the same type as
x
.
Float*
or
Decimal*
or
(U)Int*
Examples
Float inputs
sql title=Query
SELECT number / 2 AS x, round(x) FROM system.numbers LIMIT 3;
response title=Response
ββββxββ¬βround(x)ββ
β 0 β 0 β
β 0.5 β 0 β
β 1 β 1 β
βββββββ΄βββββββββββ
Decimal inputs
sql title=Query
SELECT cast(number / 2 AS Decimal(10,4)) AS x, round(x) FROM system.numbers LIMIT 3;
response title=Response
ββββxββ¬βround(x)ββ
β 0 β 0 β
β 0.5 β 1 β
β 1 β 1 β
βββββββ΄βββββββββββ
roundAge {#roundAge}
Introduced in: v1.1
Takes a number representing a human age, compares it to standard age ranges, and returns either the highest or lowest value of the range the number falls within.
Returns
0
, for
age < 1
.
Returns
17
, for
1 β€ age β€ 17
.
Returns
18
, for
18 β€ age β€ 24
.
Returns
25
, for
25 β€ age β€ 34
.
Returns
35
, for
35 β€ age β€ 44
.
Returns
45
, for
45 β€ age β€ 54
.
Returns
55
, for
age β₯ 55
.
Syntax
sql
roundAge(num)
Arguments
age
β A number representing an age in years.
(U)Int*
or
Float*
Returned value
Returns either the highest or lowest age of the range
age
falls within.
UInt8
Examples
Usage example
sql title=Query
SELECT *, roundAge(*) FROM system.numbers WHERE number IN (0, 5, 20, 31, 37, 54, 72);
response title=Response
ββnumberββ¬βroundAge(number)ββ
β 0 β 0 β
β 5 β 17 β
β 20 β 18 β
β 31 β 25 β
β 37 β 35 β
β 54 β 45 β
β 72 β 55 β
ββββββββββ΄βββββββββββββββββββ
roundBankers {#roundBankers}
Introduced in: v20.1
Rounds a number to a specified decimal position
N
.
If the rounding number is halfway between two numbers, the function uses a method of rounding called banker's rounding, which is the default rounding method for floating point numbers defined in IEEE 754.
If
N > 0
, the function rounds to the right of the decimal point
If
N < 0
, the function rounds to the left of the decimal point
If
N = 0
, the function rounds to the next integer
:::info Notes
- When the rounding number is halfway between two numbers, it's rounded to the nearest even digit at the specified decimal position.
For example:
3.5
rounds up to
4
,
2.5
rounds down to
2
.
- The
round
function performs the same rounding for floating point numbers.
- The
roundBankers
function also rounds integers the same way, for example,
roundBankers(45, -1) = 40
.
- In other cases, the function rounds numbers to the nearest integer.
::: | {"source_file": "rounding-functions.md"} | [
0.008350174874067307,
0.034796569496393204,
-0.040253013372421265,
-0.0005004857666790485,
-0.051132600754499435,
-0.0769432783126831,
0.04539016634225845,
0.07584597915410995,
-0.0332799069583416,
-0.022701501846313477,
-0.055231936275959015,
-0.09895191341638565,
-0.034572578966617584,
-... |
a5364461-ca5e-432e-b967-5f480f416d99 | :::tip Use banker's rounding for summation or subtraction of numbers
Using banker's rounding, you can reduce the effect that rounding numbers has on the results of summing or subtracting these numbers.
For example, sum numbers
1.5, 2.5, 3.5, 4.5
with different rounding:
- No rounding:
1.5 + 2.5 + 3.5 + 4.5 = 12
.
- Banker's rounding:
2 + 2 + 4 + 4 = 12
.
- Rounding to the nearest integer:
2 + 3 + 4 + 5 = 14
.
:::
Syntax
sql
roundBankers(x[, N])
Arguments
x
β A number to round.
(U)Int*
or
Decimal*
or
Float*
[, N]
β Optional. The number of decimal places to round to. Defaults to
0
.
(U)Int*
Returned value
Returns a value rounded by the banker's rounding method.
(U)Int*
or
Decimal*
or
Float*
Examples
Basic usage
sql title=Query
SELECT number / 2 AS x, roundBankers(x, 0) AS b FROM system.numbers LIMIT 10
response title=Response
ββββxββ¬βbββ
β 0 β 0 β
β 0.5 β 0 β
β 1 β 1 β
β 1.5 β 2 β
β 2 β 2 β
β 2.5 β 2 β
β 3 β 3 β
β 3.5 β 4 β
β 4 β 4 β
β 4.5 β 4 β
βββββββ΄ββββ
roundDown {#roundDown}
Introduced in: v20.1
Rounds a number down to an element in the specified array.
If the value is less than the lower bound, the lower bound is returned.
Syntax
sql
roundDown(num, arr)
Arguments
num
β A number to round down.
(U)Int*
or
Decimal*
or
Float*
arr
β Array of elements to round
num
down to.
Array((U)Int*)
or
Array(Float*)
Returned value
Returns a number rounded down to an element in
arr
. If the value is less than the lowest bound, the lowest bound is returned.
(U)Int*
or
Float*
Examples
Usage example
sql title=Query
SELECT *, roundDown(*, [3, 4, 5]) FROM system.numbers WHERE number IN (0, 1, 2, 3, 4, 5)
response title=Response
ββnumberββ¬βroundDown(number, [3, 4, 5])ββ
β 0 β 3 β
β 1 β 3 β
β 2 β 3 β
β 3 β 3 β
β 4 β 4 β
β 5 β 5 β
ββββββββββ΄βββββββββββββββββββββββββββββββ
roundDuration {#roundDuration}
Introduced in: v1.1
Rounds a number down to the closest from a set of commonly used durations:
1, 10, 30, 60, 120, 180, 240, 300, 600, 1200, 1800, 3600, 7200, 18000, 36000
.
If the number is less than one, it returns
0
.
Syntax
sql
roundDuration(num)
Arguments
num
β A number to round to one of the numbers in the set of common durations.
(U)Int*
or
Float*
Returned value
Returns
0
, for
num
< 1. Otherwise, one of:
1, 10, 30, 60, 120, 180, 240, 300, 600, 1200, 1800, 3600, 7200, 18000, 36000
.
UInt16
Examples
Usage example
sql title=Query
SELECT *, roundDuration(*) FROM system.numbers WHERE number IN (0, 9, 19, 47, 101, 149, 205, 271, 421, 789, 1423, 2345, 4567, 9876, 24680, 42573) | {"source_file": "rounding-functions.md"} | [
0.01934225857257843,
0.01618197374045849,
-0.06463637948036194,
-0.02548239752650261,
-0.06736572086811066,
-0.09257417917251587,
0.0905814841389656,
0.050870876759290695,
0.021658841520547867,
-0.025143666192889214,
-0.03569644317030907,
-0.10179682821035385,
-0.0223957858979702,
-0.06342... |
d524abe4-0d23-47ed-abaf-1f03f9489a52 | Examples
Usage example
sql title=Query
SELECT *, roundDuration(*) FROM system.numbers WHERE number IN (0, 9, 19, 47, 101, 149, 205, 271, 421, 789, 1423, 2345, 4567, 9876, 24680, 42573)
response title=Response
ββnumberββ¬βroundDuration(number)ββ
β 0 β 0 β
β 9 β 1 β
β 19 β 10 β
β 47 β 30 β
β 101 β 60 β
β 149 β 120 β
β 205 β 180 β
β 271 β 240 β
β 421 β 300 β
β 789 β 600 β
β 1423 β 1200 β
β 2345 β 1800 β
β 4567 β 3600 β
β 9876 β 7200 β
β 24680 β 18000 β
β 42573 β 36000 β
ββββββββββ΄ββββββββββββββββββββββββ
roundToExp2 {#roundToExp2}
Introduced in: v1.1
Rounds a number down to the nearest (whole non-negative) power of two.
If the number is less than one, it returns
0
.
Syntax
sql
roundToExp2(num)
Arguments
num
β A number to round.
(U)Int*
or
Float*
Returned value
Returns
num
rounded down to the nearest (whole non-negative) power of two, otherwise
0
for
num < 1
.
(U)Int*
or
Float*
Examples
Usage example
sql title=Query
SELECT *, roundToExp2(*) FROM system.numbers WHERE number IN (0, 2, 5, 10, 19, 50)
response title=Response
ββnumberββ¬βroundToExp2(number)ββ
β 0 β 0 β
β 2 β 2 β
β 5 β 4 β
β 10 β 8 β
β 19 β 16 β
β 50 β 32 β
ββββββββββ΄ββββββββββββββββββββββ
trunc {#trunc}
Introduced in: v1.1
Like
floor
but returns the rounded number with the largest absolute value less than or equal to that of
x
.
Syntax
sql
truncate(x[, N])
Aliases
:
truncate
Arguments
x
β The value to round.
Float*
or
Decimal*
or
(U)Int*
N
β Optional. The number of decimal places to round to. Defaults to zero, which means rounding to an integer.
(U)Int*
Returned value
Returns a rounded number of the same type as
x
.
Float*
or
Decimal*
or
(U)Int*
Examples
Basic usage
sql title=Query
SELECT truncate(123.499, 1) AS res;
response title=Response
ββββresββ
β 123.4 β
βββββββββ | {"source_file": "rounding-functions.md"} | [
-0.012779678218066692,
0.05036540329456329,
-0.05499189719557762,
0.01789233461022377,
-0.028467202559113503,
-0.05151400715112686,
0.0863180011510849,
0.05810900777578354,
0.0021424058359116316,
-0.006120692938566208,
-0.04057885333895683,
-0.09222086519002914,
0.056284308433532715,
-0.04... |
425eb7b2-507d-4c39-ba9f-4b558ad6fc55 | description: 'Documentation for uniqTheta Functions'
sidebar_label: 'uniqTheta'
slug: /sql-reference/functions/uniqtheta-functions
title: 'uniqTheta Functions'
doc_type: 'reference'
uniqTheta functions
uniqTheta functions work for two uniqThetaSketch objects to do set operation calculations such as βͺ / β© / Γ (union/intersect/not), it is to return a new uniqThetaSketch object contain the result.
A uniqThetaSketch object is to be constructed by aggregation function uniqTheta with -State.
UniqThetaSketch is a data structure storage of approximate values set.
For more information on RoaringBitmap, see:
Theta Sketch Framework
.
uniqThetaUnion {#uniqthetaunion}
Two uniqThetaSketch objects to do union calculation(set operation βͺ), the result is a new uniqThetaSketch.
sql
uniqThetaUnion(uniqThetaSketch,uniqThetaSketch)
Arguments
uniqThetaSketch
β uniqThetaSketch object.
Example
sql
SELECT finalizeAggregation(uniqThetaUnion(a, b)) AS a_union_b, finalizeAggregation(a) AS a_cardinality, finalizeAggregation(b) AS b_cardinality
FROM
(SELECT arrayReduce('uniqThetaState',[1,2]) AS a, arrayReduce('uniqThetaState',[2,3,4]) AS b );
text
ββa_union_bββ¬βa_cardinalityββ¬βb_cardinalityββ
β 4 β 2 β 3 β
βββββββββββββ΄ββββββββββββββββ΄ββββββββββββββββ
uniqThetaIntersect {#uniqthetaintersect}
Two uniqThetaSketch objects to do intersect calculation(set operation β©), the result is a new uniqThetaSketch.
sql
uniqThetaIntersect(uniqThetaSketch,uniqThetaSketch)
Arguments
uniqThetaSketch
β uniqThetaSketch object.
Example
sql
SELECT finalizeAggregation(uniqThetaIntersect(a, b)) AS a_intersect_b, finalizeAggregation(a) AS a_cardinality, finalizeAggregation(b) AS b_cardinality
FROM
(SELECT arrayReduce('uniqThetaState',[1,2]) AS a, arrayReduce('uniqThetaState',[2,3,4]) AS b );
text
ββa_intersect_bββ¬βa_cardinalityββ¬βb_cardinalityββ
β 1 β 2 β 3 β
βββββββββββββββββ΄ββββββββββββββββ΄ββββββββββββββββ
uniqThetaNot {#uniqthetanot}
Two uniqThetaSketch objects to do a_not_b calculation(set operation Γ), the result is a new uniqThetaSketch.
sql
uniqThetaNot(uniqThetaSketch,uniqThetaSketch)
Arguments
uniqThetaSketch
β uniqThetaSketch object.
Example
sql
SELECT finalizeAggregation(uniqThetaNot(a, b)) AS a_not_b, finalizeAggregation(a) AS a_cardinality, finalizeAggregation(b) AS b_cardinality
FROM
(SELECT arrayReduce('uniqThetaState',[2,3,4]) AS a, arrayReduce('uniqThetaState',[1,2]) AS b );
text
ββa_not_bββ¬βa_cardinalityββ¬βb_cardinalityββ
β 2 β 3 β 2 β
βββββββββββ΄ββββββββββββββββ΄ββββββββββββββββ
See Also
uniqThetaSketch | {"source_file": "uniqtheta-functions.md"} | [
-0.06401417404413223,
-0.011028498411178589,
-0.03251224011182785,
0.03194563090801239,
-0.12210611253976822,
0.00007481616194127128,
0.07451880723237991,
-0.051580049097537994,
-0.02250460535287857,
-0.0017084864666685462,
-0.03384232893586159,
-0.03345621004700661,
0.0801263153553009,
-0... |
0255f0a1-660a-4d5e-b955-0395ac654993 | description: 'Documentation for distance functions'
sidebar_label: 'Distance'
slug: /sql-reference/functions/distance-functions
title: 'Distance functions'
keywords: ['distance functions', 'norms', 'distances', 'vectors']
doc_type: 'reference'
Distance functions
L1Distance {#L1Distance}
Introduced in: v21.11
Calculates the distance between two points (the elements of the vectors are the coordinates) in
L1
space (1-norm (
taxicab geometry
distance)).
Syntax
sql
L1Distance(vector1, vector2)
Aliases
:
distanceL1
Arguments
vector1
β First vector.
Tuple(T)
or
Array(T)
vector2
β Second vector.
Tuple(T)
or
Array(T)
Returned value
Returns the 1-norm distance.
UInt32
or
Float64
Examples
Basic usage
sql title=Query
SELECT L1Distance((1, 2), (2, 3))
response title=Response
ββL1Distance((1, 2), (2, 3))ββ
β 2 β
ββββββββββββββββββββββββββββββ
L1Norm {#L1Norm}
Introduced in: v21.11
Calculates the sum of absolute elements of a vector.
Syntax
sql
L1Norm(vector)
Aliases
:
normL1
Arguments
vector
β Vector or tuple of numeric values.
Array(T)
or
Tuple(T)
Returned value
Returns the L1-norm or
taxicab geometry
distance.
UInt*
or
Float*
or
Decimal
Examples
Basic usage
sql title=Query
SELECT L1Norm((1, 2))
response title=Response
ββL1Norm((1, 2))ββ
β 3 β
ββββββββββββββββββ
L1Normalize {#L1Normalize}
Introduced in: v21.11
Calculates the unit vector of a given vector (the elements of the tuple are the coordinates) in
L1
space (
taxicab geometry
).
Syntax
sql
L1Normalize(tuple)
Aliases
:
normalizeL1
Arguments
tuple
β A tuple of numeric values.
Tuple(T)
Returned value
Returns the unit vector.
Tuple(Float64)
Examples
Basic usage
sql title=Query
SELECT L1Normalize((1, 2))
response title=Response
ββL1Normalize((1, 2))ββββββββββββββββββββββ
β (0.3333333333333333,0.6666666666666666) β
βββββββββββββββββββββββββββββββββββββββββββ
L2Distance {#L2Distance}
Introduced in: v21.11
Calculates the distance between two points (the elements of the vectors are the coordinates) in Euclidean space (
Euclidean distance
).
Syntax
sql
L2Distance(vector1, vector2)
Aliases
:
distanceL2
Arguments
vector1
β First vector.
Tuple(T)
or
Array(T)
vector2
β Second vector.
Tuple(T)
or
Array(T)
Returned value
Returns the 2-norm distance.
Float64
Examples
Basic usage
sql title=Query
SELECT L2Distance((1, 2), (2, 3))
response title=Response
ββL2Distance((1, 2), (2, 3))ββ
β 1.4142135623730951 β
ββββββββββββββββββββββββββββββ
L2DistanceTransposed {#L2DistanceTransposed}
Introduced in: v25.10
Calculates the approximate distance between two points (the values of the vectors are the coordinates) in Euclidean space (
Euclidean distance
).
Syntax
sql
L2DistanceTransposed(vector1, vector2, p)
Aliases
:
distanceL2Transposed
Arguments | {"source_file": "distance-functions.md"} | [
-0.021391700953245163,
-0.05471267178654671,
-0.04310782253742218,
-0.023194612935185432,
-0.04060984402894974,
0.002970599103718996,
0.03516456484794617,
0.07354656606912613,
-0.06469116359949112,
-0.03721077740192413,
0.054072048515081406,
-0.04630890116095543,
0.05106232315301895,
-0.05... |
71291d07-d4ad-4750-ae5f-9e2a399403f9 | Syntax
sql
L2DistanceTransposed(vector1, vector2, p)
Aliases
:
distanceL2Transposed
Arguments
vectors
β Vectors.
QBit(T, UInt64)
reference
β Reference vector.
Array(T)
p
β Number of bits from each vector element to use in the distance calculation (1 to element bit-width). The quantization level controls the precision-speed trade-off. Using fewer bits results in faster I/O and calculations with reduced accuracy, while using more bits increases accuracy at the cost of performance.
UInt
Returned value
Returns the approximate 2-norm distance.
Float64
Examples
Basic usage
sql title=Query
CREATE TABLE qbit (id UInt32, vec QBit(Float64, 2)) ENGINE = Memory;
INSERT INTO qbit VALUES (1, [0, 1]);
SELECT L2DistanceTransposed(vec, array(1.0, 2.0), 16) FROM qbit;"
response title=Response
ββL2DistanceTransposed([0, 1], [1.0, 2.0], 16)ββ
β 1.4142135623730951 β
ββββββββββββββββββββββββββββββββββββββββββββββββ
L2Norm {#L2Norm}
Introduced in: v21.11
Calculates the square root of the sum of the squares of the vector elements.
Syntax
sql
L2Norm(vector)
Aliases
:
normL2
Arguments
vector
β Vector or tuple of numeric values.
Tuple(T)
or
Array(T)
Returned value
Returns the L2-norm or
Euclidean distance
.
UInt*
or
Float*
Examples
Basic usage
sql title=Query
SELECT L2Norm((1, 2))
response title=Response
ββββL2Norm((1, 2))ββ
β 2.23606797749979 β
ββββββββββββββββββββ
L2Normalize {#L2Normalize}
Introduced in: v21.11
Calculates the unit vector of a given vector (the elements of the tuple are the coordinates) in Euclidean space (using
Euclidean distance
).
Syntax
sql
L2Normalize(tuple)
Aliases
:
normalizeL2
Arguments
tuple
β A tuple of numeric values.
Tuple(T)
Returned value
Returns the unit vector.
Tuple(Float64)
Examples
Basic usage
sql title=Query
SELECT L2Normalize((3, 4))
response title=Response
ββL2Normalize((3, 4))ββ
β (0.6,0.8) β
βββββββββββββββββββββββ
L2SquaredDistance {#L2SquaredDistance}
Introduced in: v22.7
Calculates the sum of the squares of the difference between the corresponding elements of two vectors.
Syntax
sql
L2SquaredDistance(vector1, vector2)
Aliases
:
distanceL2Squared
Arguments
vector1
β First vector.
Tuple(T)
or
Array(T)
vector2
β Second vector.
Tuple(T)
or
Array(T)
Returned value
Returns the sum of the squares of the difference between the corresponding elements of two vectors.
Float64
Examples
Basic usage
sql title=Query
SELECT L2SquaredDistance([1, 2, 3], [0, 0, 0])
response title=Response
ββL2SquaredDisβ― [0, 0, 0])ββ
β 14 β
ββββββββββββββββββββββββββββ
L2SquaredNorm {#L2SquaredNorm}
Introduced in: v22.7
Calculates the square root of the sum of the squares of the vector elements (the
L2Norm
) squared.
Syntax
sql
L2SquaredNorm(vector)
Aliases
:
normL2Squared
Arguments | {"source_file": "distance-functions.md"} | [
0.019660744816064835,
0.0006664709071628749,
-0.06823539733886719,
-0.034065667539834976,
-0.019299879670143127,
-0.04131413996219635,
-0.035180311650037766,
0.033610690385103226,
0.019418537616729736,
-0.07548714429140091,
0.008632860146462917,
-0.08324402570724487,
0.06221422180533409,
-... |
4deec113-b7c8-4605-a6e9-3710690d164d | Calculates the square root of the sum of the squares of the vector elements (the
L2Norm
) squared.
Syntax
sql
L2SquaredNorm(vector)
Aliases
:
normL2Squared
Arguments
vector
β Vector or tuple of numeric values.
Array(T)
or
Tuple(T)
Returned value
Returns the L2-norm squared.
UInt*
or
Float*
or
Decimal
Examples
Basic usage
sql title=Query
SELECT L2SquaredNorm((1, 2))
response title=Response
ββL2SquaredNorm((1, 2))ββ
β 5 β
βββββββββββββββββββββββββ
LinfDistance {#LinfDistance}
Introduced in: v21.11
Calculates the distance between two points (the elements of the vectors are the coordinates) in
L_{inf}
space (
maximum norm
).
Syntax
sql
LinfDistance(vector1, vector2)
Aliases
:
distanceLinf
Arguments
vector1
β First vector.
Tuple(T)
or
Array(T)
vector2
β Second vector.
Tuple(T)
or
Array(T)
Returned value
Returns the Infinity-norm distance.
Float64
Examples
Basic usage
sql title=Query
SELECT LinfDistance((1, 2), (2, 3))
response title=Response
ββLinfDistance((1, 2), (2, 3))ββ
β 1 β
ββββββββββββββββββββββββββββββββ
LinfNorm {#LinfNorm}
Introduced in: v21.11
Calculates the maximum of absolute elements of a vector.
Syntax
sql
LinfNorm(vector)
Aliases
:
normLinf
Arguments
vector
β Vector or tuple of numeric values.
Array(T)
or
Tuple(T)
Returned value
Returns the Linf-norm or the maximum absolute value.
Float64
Examples
Basic usage
sql title=Query
SELECT LinfNorm((1, -2))
response title=Response
ββLinfNorm((1, -2))ββ
β 2 β
βββββββββββββββββββββ
LinfNormalize {#LinfNormalize}
Introduced in: v21.11
Calculates the unit vector of a given vector (the elements of the tuple are the coordinates) in
L_{inf}
space (using
maximum norm
).
Syntax
sql
LinfNormalize(tuple)
Aliases
:
normalizeLinf
Arguments
tuple
β A tuple of numeric values.
Tuple(T)
Returned value
Returns the unit vector.
Tuple(Float64)
Examples
Basic usage
sql title=Query
SELECT LinfNormalize((3, 4))
response title=Response
ββLinfNormalize((3, 4))ββ
β (0.75,1) β
βββββββββββββββββββββββββ
LpDistance {#LpDistance}
Introduced in: v21.11
Calculates the distance between two points (the elements of the vectors are the coordinates) in
Lp
space (
p-norm distance
).
Syntax
sql
LpDistance(vector1, vector2, p)
Aliases
:
distanceLp
Arguments
vector1
β First vector.
Tuple(T)
or
Array(T)
vector2
β Second vector.
Tuple(T)
or
Array(T)
p
β The power. Possible values: real number from
[1; inf)
.
UInt*
or
Float*
Returned value
Returns the p-norm distance.
Float64
Examples
Basic usage
sql title=Query
SELECT LpDistance((1, 2), (2, 3), 3)
response title=Response
ββLpDistance((1, 2), (2, 3), 3)ββ
β 1.2599210498948732 β
βββββββββββββββββββββββββββββββββ
LpNorm {#LpNorm}
Introduced in: v21.11 | {"source_file": "distance-functions.md"} | [
0.010973620228469372,
-0.10191211849451065,
-0.03798381984233856,
-0.02117534540593624,
0.05408795550465584,
-0.014915704727172852,
-0.015355944633483887,
0.06610426306724548,
-0.029658613726496696,
-0.02020840160548687,
0.05605832487344742,
0.006355357822030783,
0.03647328540682793,
-0.02... |
de510cfb-30be-4bcf-8a7b-76307fd46e92 | response title=Response
ββLpDistance((1, 2), (2, 3), 3)ββ
β 1.2599210498948732 β
βββββββββββββββββββββββββββββββββ
LpNorm {#LpNorm}
Introduced in: v21.11
Calculates the p-norm of a vector, which is the p-th root of the sum of the p-th powers of the absolute elements of its elements.
Special cases:
- When p=1, it's equivalent to L1Norm (Manhattan distance).
- When p=2, it's equivalent to L2Norm (Euclidean distance).
- When p=β, it's equivalent to LinfNorm (maximum norm).
Syntax
sql
LpNorm(vector, p)
Aliases
:
normLp
Arguments
vector
β Vector or tuple of numeric values.
Tuple(T)
or
Array(T)
p
β The power. Possible values are real numbers in the range
[1; inf)
.
UInt*
or
Float*
Returned value
Returns the
Lp-norm
.
Float64
Examples
Basic usage
sql title=Query
SELECT LpNorm((1, -2), 2)
response title=Response
ββLpNorm((1, -2), 2)ββ
β 2.23606797749979 β
ββββββββββββββββββββββ
LpNormalize {#LpNormalize}
Introduced in: v21.11
Calculates the unit vector of a given vector (the elements of the tuple are the coordinates) in
Lp
space (using
p-norm
).
Syntax
sql
LpNormalize(tuple, p)
Aliases
:
normalizeLp
Arguments
tuple
β A tuple of numeric values.
Tuple(T)
p
β The power. Possible values are any number in the range range from
[1; inf)
.
UInt*
or
Float*
Returned value
Returns the unit vector.
Tuple(Float64)
Examples
Usage example
sql title=Query
SELECT LpNormalize((3, 4), 5)
response title=Response
ββLpNormalize((3, 4), 5)βββββββββββββββββββ
β (0.7187302630182624,0.9583070173576831) β
βββββββββββββββββββββββββββββββββββββββββββ
cosineDistance {#cosineDistance}
Introduced in: v1.1
Calculates the cosine distance between two vectors (the elements of the tuples are the coordinates). The smaller the returned value is, the more similar are the vectors.
Syntax
sql
cosineDistance(vector1, vector2)
Arguments
vector1
β First tuple.
Tuple(T)
or
Array(T)
vector2
β Second tuple.
Tuple(T)
or
Array(T)
Returned value
Returns the cosine of the angle between two vectors subtracted from one.
Float64
Examples
Basic usage
sql title=Query
SELECT cosineDistance((1, 2), (2, 3));
response title=Response
ββcosineDistance((1, 2), (2, 3))ββ
β 0.007722123286332261 β
ββββββββββββββββββββββββββββββββββ | {"source_file": "distance-functions.md"} | [
0.019467845559120178,
-0.06310978531837463,
-0.06909771263599396,
-0.0010477494215592742,
0.02195177786052227,
-0.04825340956449509,
0.07041164487600327,
0.06255090981721878,
-0.023171233013272285,
-0.008695784024894238,
0.028631549328565598,
-0.004219538066536188,
0.061498720198869705,
-0... |
37d2194b-214e-4c6c-8618-d4ea5991c5b3 | description: 'Documentation for Bitmap Functions'
sidebar_label: 'Bitmap'
slug: /sql-reference/functions/bitmap-functions
title: 'Bitmap Functions'
doc_type: 'reference'
Bitmap functions
Bitmaps can be constructed in two ways. The first way is constructed by aggregation function groupBitmap with
-State
, the other way is to constructed a bitmap from an Array object.
bitmapAnd {#bitmapAnd}
Introduced in: v20.1
Computes the logical conjunction (AND) of two bitmaps.
Syntax
sql
bitmapAnd(bitmap1, bitmap2)
Arguments
bitmap1
β First bitmap object.
AggregateFunction(groupBitmap, T)
. -
bitmap2
β Second bitmap object.
AggregateFunction(groupBitmap, T)
.
Returned value
Returns a bitmap containing bits present in both input bitmaps
AggregateFunction(groupBitmap, T)
Examples
Usage example
sql title=Query
SELECT bitmapToArray(bitmapAnd(bitmapBuild([1, 2, 3]), bitmapBuild([3, 4, 5]))) AS res;
response title=Response
ββresββ
β [3] β
βββββββ
bitmapAndCardinality {#bitmapAndCardinality}
Introduced in: v20.1
Returns the cardinality of the logical conjunction (AND) of two bitmaps.
Syntax
sql
bitmapAndCardinality(bitmap1, bitmap2)
Arguments
bitmap1
β First bitmap object.
AggregateFunction(groupBitmap, T)
. -
bitmap2
β Second bitmap object.
AggregateFunction(groupBitmap, T)
.
Returned value
Returns the number of set bits in the intersection of the two bitmaps
UInt64
Examples
Usage example
sql title=Query
SELECT bitmapAndCardinality(bitmapBuild([1,2,3]), bitmapBuild([3,4,5])) AS res;
response title=Response
ββresββ
β 1 β
βββββββ
bitmapAndnot {#bitmapAndnot}
Introduced in: v20.1
Computes the set difference A AND-NOT B of two bitmaps.
Syntax
sql
bitmapAndnot(bitmap1, bitmap2)
Arguments
bitmap1
β First bitmap object.
AggregateFunction(groupBitmap, T)
. -
bitmap2
β Second bitmap object.
AggregateFunction(groupBitmap, T)
.
Returned value
Returns a bitmap containing set bits present in the first bitmap but not in the second
AggregateFunction(groupBitmap, T)
Examples
Usage example
sql title=Query
SELECT bitmapToArray(bitmapAndnot(bitmapBuild([1, 2, 3]), bitmapBuild([3, 4, 5]))) AS res;
response title=Response
ββresβββββ
β [1, 2] β
ββββββββββ
bitmapAndnotCardinality {#bitmapAndnotCardinality}
Introduced in: v20.1
Returns the cardinality of the AND-NOT operation of two bitmaps.
Syntax
sql
bitmapAndnotCardinality(bitmap1, bitmap2)
Arguments
bitmap1
β First bitmap object.
AggregateFunction(groupBitmap, T)
. -
bitmap2
β Second bitmap object.
AggregateFunction(groupBitmap, T)
.
Returned value
Returns the number of set bits in the result of
bitmap1 AND-NOT bitmap2
UInt64
Examples
Usage example
sql title=Query
SELECT bitmapAndnotCardinality(bitmapBuild([1,2,3]), bitmapBuild([3,4,5])) AS res;
response title=Response
ββresββ
β 2 β
βββββββ
bitmapBuild {#bitmapBuild}
Introduced in: v20.1 | {"source_file": "bitmap-functions.md"} | [
0.001544386032037437,
0.03763844445347786,
0.016320349648594856,
0.010768870823085308,
-0.06054021418094635,
-0.02100360579788685,
0.08335711807012558,
-0.03605777025222778,
-0.10049253702163696,
0.0019943476654589176,
-0.014033050276339054,
-0.1228938028216362,
0.08661749958992004,
-0.021... |
21d192a4-ad91-463b-99dd-f3a87e024d2e | response title=Response
ββresββ
β 2 β
βββββββ
bitmapBuild {#bitmapBuild}
Introduced in: v20.1
Builds a bitmap from an unsigned integer array. It is the opposite of function
bitmapToArray
.
Syntax
sql
bitmapBuild(array)
Arguments
array
β Unsigned integer array.
Array(UInt*)
Returned value
Returns a bitmap from the provided array
AggregateFunction(groupBitmap, T)
Examples
Usage example
sql title=Query
SELECT bitmapBuild([1, 2, 3, 4, 5]) AS res, toTypeName(res);
response title=Response
ββresββ¬βtoTypeName(bitmapBuild([1, 2, 3, 4, 5]))ββββββ
β β AggregateFunction(groupBitmap, UInt8) β
βββββββ΄βββββββββββββββββββββββββββββββββββββββββββββββ
bitmapCardinality {#bitmapCardinality}
Introduced in: v20.1
Returns the number of bits set (the cardinality) in the bitmap.
Syntax
sql
bitmapCardinality(bitmap)
Arguments
bitmap
β Bitmap object.
AggregateFunction(groupBitmap, T)
.
Returned value
Returns the number of bits set in the bitmap
UInt64
Examples
Usage example
sql title=Query
SELECT bitmapCardinality(bitmapBuild([1, 3, 3, 5, 7, 7])) AS res
response title=Response
ββresββ
β 4 β
βββββββ
bitmapContains {#bitmapContains}
Introduced in: v20.1
Checks if the bitmap contains a specific element.
Syntax
sql
bitmapContains(bitmap, value)
Arguments
bitmap
β Bitmap object.
AggregateFunction(groupBitmap, T)
. -
value
β Element to check for.
(U)Int8/16/32/64
Returned value
Returns
1
if the bitmap contains the specified value, otherwise
0
UInt8
Examples
Usage example
sql title=Query
SELECT bitmapContains(bitmapBuild([1, 2, 3]), 2) AS res;
response title=Response
ββresββ
β 1 β
βββββββ
bitmapHasAll {#bitmapHasAll}
Introduced in: v20.1
Checks if the first bitmap contains all set bits of the second bitmap.
Syntax
sql
bitmapHasAll(bitmap1, bitmap2)
Arguments
bitmap1
β First bitmap object.
AggregateFunction(groupBitmap, T)
. -
bitmap2
β Second bitmap object.
AggregateFunction(groupBitmap, T)
.
Returned value
Returns
1
if all set bits of the second bitmap are present in the first bitmap, otherwise
0
UInt8
Examples
Usage example
sql title=Query
SELECT bitmapHasAll(bitmapBuild([1, 2, 3]), bitmapBuild([2, 3])) AS res;
response title=Response
ββresββ
β 1 β
βββββββ
bitmapHasAny {#bitmapHasAny}
Introduced in: v20.1
Checks if the first bitmap contains any set bits of the second bitmap.
Syntax
sql
bitmapHasAny(bitmap1, bitmap2)
Arguments
bitmap1
β First bitmap object.
AggregateFunction(groupBitmap, T)
. -
bitmap2
β Second bitmap object.
AggregateFunction(groupBitmap, T)
.
Returned value
Returns
1
if any bits of the second bitmap are present in the first bitmap, otherwise
0
UInt8
Examples
Usage example
sql title=Query
SELECT bitmapHasAny(bitmapBuild([1, 2, 3]), bitmapBuild([3, 4, 5])) AS res;
response title=Response
ββresββ
β 1 β
βββββββ
bitmapMax {#bitmapMax} | {"source_file": "bitmap-functions.md"} | [
0.03136022016406059,
0.0654958188533783,
-0.007129282224923372,
0.033280570060014725,
-0.04601944610476494,
-0.041274163872003555,
0.0635882019996643,
-0.02413005381822586,
-0.06142839044332504,
-0.012327647767961025,
-0.047232870012521744,
-0.1212407797574997,
0.06576443463563919,
-0.0309... |
b466ffa9-2bb6-4e3a-8398-ad916c83ac58 | Examples
Usage example
sql title=Query
SELECT bitmapHasAny(bitmapBuild([1, 2, 3]), bitmapBuild([3, 4, 5])) AS res;
response title=Response
ββresββ
β 1 β
βββββββ
bitmapMax {#bitmapMax}
Introduced in: v20.1
Returns the position of the greatest bit set in a bitmap, or
0
if the bitmap is empty.
Syntax
sql
bitmapMax(bitmap)
Arguments
bitmap
β Bitmap object.
AggregateFunction(groupBitmap, T)
.
Returned value
Returns the position of the greatest bit set in the bitmap, otherwise
0
UInt64
Examples
Usage example
sql title=Query
SELECT bitmapMax(bitmapBuild([1, 2, 3, 4, 5])) AS res;
response title=Response
ββresββ
β 5 β
βββββββ
bitmapMin {#bitmapMin}
Introduced in: v20.1
Returns the position of the smallest bit set in a bitmap. If all bits are unset, or
UINT32_MAX
(
UINT64_MAX
if the bitmap contains more than
2^64
bits).
Syntax
sql
bitmapMin(bitmap)
Arguments
bitmap
β Bitmap object.
AggregateFunction(groupBitmap, T)
.
Returned value
Returns the position of the smallest bit set in the bitmap, or
UINT32_MAX
/
UINT64_MAX
UInt64
Examples
Usage example
sql title=Query
SELECT bitmapMin(bitmapBuild([3, 5, 2, 6])) AS res;
response title=Response
ββresββ
β 2 β
βββββββ
bitmapOr {#bitmapOr}
Introduced in: v20.1
Computes the logical disjunction (OR) of two bitmaps.
Syntax
sql
bitmapOr(bitmap1, bitmap2)
Arguments
bitmap1
β First bitmap object.
AggregateFunction(groupBitmap, T)
. -
bitmap2
β Second bitmap object.
AggregateFunction(groupBitmap, T)
.
Returned value
Returns a bitmap containing set bits present in either input bitmap
AggregateFunction(groupBitmap, T)
Examples
Usage example
sql title=Query
SELECT bitmapToArray(bitmapOr(bitmapBuild([1, 2, 3]), bitmapBuild([3, 4, 5]))) AS res;
response title=Response
ββresββββββββββββββ
β [1, 2, 3, 4, 5] β
βββββββββββββββββββ
bitmapOrCardinality {#bitmapOrCardinality}
Introduced in: v20.1
Returns the cardinality of the logical disjunction (OR) of two bitmaps.
Syntax
sql
bitmapOrCardinality(bitmap1, bitmap2)
Arguments
bitmap1
β First bitmap object.
AggregateFunction(groupBitmap, T)
. -
bitmap2
β Second bitmap object.
AggregateFunction(groupBitmap, T)
.
Returned value
Returns the number of set bits in the union of the two bitmaps
UInt64
Examples
Usage example
sql title=Query
SELECT bitmapOrCardinality(bitmapBuild([1,2,3]), bitmapBuild([3,4,5])) AS res;
response title=Response
ββresββ
β 5 β
βββββββ
bitmapSubsetInRange {#bitmapSubsetInRange}
Introduced in: v20.1
Returns a subset of the bitmap, containing only the set bits in the specified range [start, end). Uses 1-based indexing.
Syntax
sql
bitmapSubsetInRange(bitmap, start, end)
Arguments
bitmap
β Bitmap to extract the subset from.
AggregateFunction(groupBitmap, T)
. -
start
β Start of the range (inclusive).
UInt*
-
end
β End of the range (exclusive).
UInt*
Returned value | {"source_file": "bitmap-functions.md"} | [
0.02904268354177475,
0.050562936812639236,
-0.024522826075553894,
0.007378250826150179,
-0.05018312856554985,
-0.043222080916166306,
0.044732727110385895,
0.02177065797150135,
-0.04705885425209999,
0.024225803092122078,
-0.03639786317944527,
-0.05804499611258507,
0.0728011503815651,
-0.055... |
3c1bfd26-c686-4592-8e58-4a6fcfcab7b1 | Returned value
Returns a bitmap containing only the set bits in the specified range
AggregateFunction(groupBitmap, T)
Examples
Usage example
sql title=Query
SELECT bitmapToArray(bitmapSubsetInRange(bitmapBuild([1, 2, 3, 4, 5]), 2, 5)) AS res;
response title=Response
ββresββββββββ
β [2, 3, 4] β
βββββββββββββ
bitmapSubsetLimit {#bitmapSubsetLimit}
Introduced in: v20.1
Returns a subset of a bitmap from position
range_start
with at most
cardinality_limit
set bits. Uses 1-based indexing.
Syntax
sql
bitmapSubsetLimit(bitmap, range_start, cardinality_limit)
Arguments
bitmap
β Bitmap object.
AggregateFunction(groupBitmap, T)
. -
range_start
β Start of the range (inclusive).
UInt32
-
cardinality_limit
β Maximum cardinality of the subset.
UInt32
Returned value
Returns a bitmap containing at most
cardinality_limit
set bits, starting from
range_start
AggregateFunction(groupBitmap, T)
Examples
Usage example
sql title=Query
SELECT bitmapToArray(bitmapSubsetLimit(bitmapBuild([1, 5, 3, 2, 8]), 3, 2)) AS res;
response title=Response
ββresβββββ
β [5, 3] β
ββββββββββ
bitmapToArray {#bitmapToArray}
Introduced in: v20.1
Converts a bitmap to an array of unsigned integers. It is the opposite of function
bitmapBuild
.
Syntax
sql
bitmapToArray(bitmap)
Arguments
bitmap
β Bitmap to convert.
AggregateFunction(groupBitmap, T)
.
Returned value
Returns an array of unsigned integers contained in the bitmap
Array(UInt*)
Examples
Usage example
sql title=Query
SELECT bitmapToArray(bitmapBuild([1, 2, 3, 4, 5])) AS res;
response title=Response
ββresββββββββββββββ
β [1, 2, 3, 4, 5] β
βββββββββββββββββββ
bitmapTransform {#bitmapTransform}
Introduced in: v20.1
Changes up to N bits in a bitmap by swapping specific bit values in
from_array
with corresponding ones in
to_array
.
Syntax
sql
bitmapTransform(bitmap, from_array, to_array)
Arguments
bitmap
β Bitmap object.
AggregateFunction(groupBitmap, T)
. -
from_array
β Array of original set bits to be replaced.
Array(T)
. -
to_array
β Array of new set bits to replace with.
Array(T)
.
Returned value
Returns a bitmap with elements transformed according to the given mapping
AggregateFunction(groupBitmap, T)
Examples
Usage example
sql title=Query
SELECT bitmapToArray(bitmapTransform(bitmapBuild([1, 2, 3, 4, 5]), [2, 4], [20, 40])) AS res;
response title=Response
ββresββββββββββββββββ
β [1, 3, 5, 20, 40] β
βββββββββββββββββββββ
bitmapXor {#bitmapXor}
Introduced in: v20.1
Computes the symmetric difference (XOR) of two bitmaps.
Syntax
sql
bitmapXor(bitmap1, bitmap2)
Arguments
bitmap1
β First bitmap object.
AggregateFunction(groupBitmap, T)
. -
bitmap2
β Second bitmap object.
AggregateFunction(groupBitmap, T)
.
Returned value
Returns a bitmap containing set bits present in either input bitmap, but not in both
AggregateFunction(groupBitmap, T)
Examples
Usage example | {"source_file": "bitmap-functions.md"} | [
0.023673677816987038,
0.06219221651554108,
-0.020960690453648567,
0.03989079222083092,
-0.03108057752251625,
-0.03423832729458809,
0.046816617250442505,
-0.017400886863470078,
-0.05546100065112114,
-0.03489643335342407,
-0.06430353224277496,
-0.10410185903310776,
0.048344168812036514,
-0.0... |
d0394a2a-025d-48cc-b14e-f6dbf30796ff | Returned value
Returns a bitmap containing set bits present in either input bitmap, but not in both
AggregateFunction(groupBitmap, T)
Examples
Usage example
sql title=Query
SELECT bitmapToArray(bitmapXor(bitmapBuild([1, 2, 3]), bitmapBuild([3, 4, 5]))) AS res;
response title=Response
ββresβββββββββββ
β [1, 2, 4, 5] β
ββββββββββββββββ
bitmapXorCardinality {#bitmapXorCardinality}
Introduced in: v20.1
Returns the cardinality of the XOR (symmetric difference) of two bitmaps.
Syntax
sql
bitmapXorCardinality(bitmap1, bitmap2)
Arguments
bitmap1
β First bitmap object.
AggregateFunction(groupBitmap, T)
. -
bitmap2
β Second bitmap object.
AggregateFunction(groupBitmap, T)
.
Returned value
Returns the number of set bits in the symmetric difference of the two bitmaps
UInt64
Examples
Usage example
sql title=Query
SELECT bitmapXorCardinality(bitmapBuild([1,2,3]), bitmapBuild([3,4,5])) AS res;
response title=Response
ββresββ
β 4 β
βββββββ
subBitmap {#subBitmap}
Introduced in: v21.9
Returns a subset of the bitmap, starting from position
offset
. The maximum cardinality of the returned bitmap is
cardinality_limit
.
Syntax
sql
subBitmap(bitmap, offset, cardinality_limit)
Arguments
bitmap
β Bitmap object.
AggregateFunction(groupBitmap, T)
. -
offset
β Number of set bits to skip from the beginning (zero-based).
UInt32
-
cardinality_limit
β Maximum number of set bits to include in the subset.
UInt32
Returned value
Returns a bitmap containing at most
limit
set bits, starting after skipping
offset
set bits in ascending order
AggregateFunction(groupBitmap, T)
Examples
Usage example
sql title=Query
SELECT bitmapToArray(subBitmap(bitmapBuild([1, 2, 3, 4, 5]), 2, 2)) AS res;
response title=Response
ββresβββββ
β [3, 4] β
ββββββββββ | {"source_file": "bitmap-functions.md"} | [
-0.0019378813449293375,
0.016107749193906784,
0.03499186038970947,
0.02796543575823307,
-0.04663431644439697,
-0.07164647430181503,
0.04361053183674812,
-0.003311438485980034,
-0.03440423309803009,
-0.038695983588695526,
-0.017337948083877563,
-0.11693795025348663,
0.08174263685941696,
-0.... |
9dad15bf-8e12-483b-b03c-4d4f68b637a1 | description: 'Documentation for mathematical functions'
sidebar_label: 'Mathematical'
slug: /sql-reference/functions/math-functions
title: 'Mathematical functions'
doc_type: 'reference'
Mathematical functions
acos {#acos}
Introduced in: v1.1
Returns the arc cosine of the argument.
Syntax
sql
acos(x)
Arguments
x
β The value for which to find arc cosine of.
(U)Int*
or
Float*
or
Decimal*
Returned value
Returns the arc cosine of x
Float*
Examples
Usage example
sql title=Query
SELECT acos(0.5);
response title=Response
1.0471975511965979
acosh {#acosh}
Introduced in: v20.12
Returns the inverse hyperbolic cosine.
Syntax
sql
acosh(x)
Arguments
x
β Hyperbolic cosine of angle. Values from the interval:
1 β€ x < +β
.
(U)Int*
or
Float*
or
Decimal*
Returned value
Returns the angle, in radians. Values from the interval:
0 β€ acosh(x) < +β
.
Float64
Examples
Usage example
sql title=Query
SELECT acosh(1)
response title=Response
0
asin {#asin}
Introduced in: v1.1
Calculates the arcsine of the provided argument.
For arguments in the range
[-1, 1]
it returns the value in the range of
[-pi() / 2, pi() / 2]
.
Syntax
sql
asin(x)
Arguments
x
β Argument for which to calculate arcsine of.
(U)Int*
or
Float*
or
Decimal
Returned value
Returns the arcsine value of the provided argument
x
Float64
Examples
inverse
sql title=Query
SELECT asin(1.0) = pi() / 2, sin(asin(1)), asin(sin(1))
response title=Response
1 1 1
float32
sql title=Query
SELECT toTypeName(asin(1.0::Float32))
response title=Response
Float64
nan
sql title=Query
SELECT asin(1.1), asin(-2), asin(inf), asin(nan)
response title=Response
nan nan nan nan
asinh {#asinh}
Introduced in: v20.12
Returns the inverse hyperbolic sine.
Syntax
sql
asinh(x)
Arguments
x
β Hyperbolic sine of angle. Values from the interval:
-β < x < +β
.
(U)Int*
or
Float*
or
Decimal*
Returned value
Returns the angle, in radians. Values from the interval:
-β < asinh(x) < +β
.
Float64
Examples
Basic usage
sql title=Query
SELECT asinh(0)
response title=Response
0
atan {#atan}
Introduced in: v1.1
Returns the arc tangent of the argument.
Syntax
sql
atan(x)
Arguments
x
β The value for which to find arc tangent of.
(U)Int*
or
Float*
or
Decimal*
Returned value
Returns the arc tangent of
x
.
Float*
Examples
Usage example
sql title=Query
SELECT atan(1);
response title=Response
0.7853981633974483
atan2 {#atan2}
Introduced in: v20.12
Returns the atan2 as the angle in the Euclidean plane, given in radians, between the positive x axis and the ray to the point
(x, y) β (0, 0)
.
Syntax
sql
atan2(y, x)
Arguments
y
β y-coordinate of the point through which the ray passes.
(U)Int*
or
Float*
or
Decimal*
x
β x-coordinate of the point through which the ray passes.
(U)Int*
or
Float*
or
Decimal*
Returned value | {"source_file": "math-functions.md"} | [
-0.06065808981657028,
0.026182089000940323,
-0.05730070173740387,
0.01853831298649311,
-0.03341323882341385,
-0.06508610397577286,
0.03431875258684158,
0.09434566646814346,
0.031306181102991104,
0.01419853512197733,
0.11071429401636124,
-0.07310492545366287,
0.04350595921278,
-0.0427967235... |
15ed53b6-8b54-4d98-a096-b666f8ea4366 | x
β x-coordinate of the point through which the ray passes.
(U)Int*
or
Float*
or
Decimal*
Returned value
Returns the angle
ΞΈ
such that
-Ο < ΞΈ β€ Ο
, in radians
Float64
Examples
Usage example
sql title=Query
SELECT atan2(1, 1)
response title=Response
0.7853981633974483
atanh {#atanh}
Introduced in: v20.12
Returns the inverse hyperbolic tangent.
Syntax
sql
atanh(x)
Arguments
x
β Hyperbolic tangent of angle. Values from the interval: -1 < x < 1.
(U)Int*
,
Float*
or
Decimal*
.
(U)Int*
or
Float*
or
Decimal*
Returned value
Returns the angle, in radians. Values from the interval: -β < atanh(x) < +β
Float64
Examples
Usage example
sql title=Query
SELECT atanh(0)
response title=Response
0
cbrt {#cbrt}
Introduced in: v1.1
Returns the cubic root of the argument.
Syntax
sql
cbrt(x)
Arguments
x
β The value for which to find the cubic root of.
(U)Int*
or
Float*
or
Decimal*
Returned value
Returns the cubic root of
x
.
Float*
Examples
Usage example
sql title=Query
SELECT cbrt(8);
response title=Response
2
cos {#cos}
Introduced in: v1.1
Returns the cosine of the argument.
Syntax
sql
cos(x)
Arguments
x
β The angle in radians.
(U)Int*
or
Float*
or
Decimal*
Returned value
Returns the cosine of
x
.
Float*
Examples
Usage example
sql title=Query
SELECT cos(0);
response title=Response
1
cosh {#cosh}
Introduced in: v20.12
Returns the hyperbolic cosine of the argument.
Syntax
sql
cosh(x)
Arguments
x
β The angle, in radians. Values from the interval:
-β < x < +β
.
(U)Int*
or
Float*
or
Decimal*
Returned value
Returns values from the interval:
1 β€ cosh(x) < +β
Float64
Examples
Basic usage
sql title=Query
SELECT cosh(0)
response title=Response
1
degrees {#degrees}
Introduced in: v22.2
Converts radians to degrees.
Syntax
sql
degrees(x)
Arguments
x
β Input in radians.
(U)Int*
or
Float*
or
Decimal*
Returned value
Returns the value of
x
in degrees.
Float64
Examples
Basic usage
sql title=Query
SELECT degrees(3.141592653589793)
response title=Response
180
e {#e}
Introduced in: v1.1
Returns Euler's constant (e).
Syntax
sql
e()
Arguments
None.
Returned value
Returns Euler's constant
Float64
Examples
Usage example
sql title=Query
SELECT e();
response title=Response
2.718281828459045
erf {#erf}
Introduced in: v1.1
If
x
is non-negative, then
erf(x/(Οβ2))
is the probability that a random variable having a normal distribution with standard deviation
Ο
takes the value that is separated from the expected value by more than
x
.
Syntax
sql
erf(x)
Arguments
x
β The value for which to compute the error function value.
(U)Int*
or
Float*
or
Decimal*
Returned value
Returns the error function value
Float*
Examples
Three sigma rule
sql title=Query
SELECT erf(3 / sqrt(2)) | {"source_file": "math-functions.md"} | [
0.011060836724936962,
-0.02679447829723358,
-0.08477561175823212,
-0.005754576995968819,
-0.011327962391078472,
-0.06663874536752701,
0.03520709276199341,
0.020553776994347572,
0.014931634068489075,
-0.008967793546617031,
0.0673779770731926,
-0.09523855894804001,
0.10011423379182816,
-0.02... |
db498966-277d-4ac1-a391-3a184295cdcb | Returned value
Returns the error function value
Float*
Examples
Three sigma rule
sql title=Query
SELECT erf(3 / sqrt(2))
response title=Response
ββerf(divide(3, sqrt(2)))ββ
β 0.9973002039367398 β
βββββββββββββββββββββββββββ
erfc {#erfc}
Introduced in: v1.1
Returns a number close to
1-erf(x)
without loss of precision for large
x
values.
Syntax
sql
erfc(x)
Arguments
x
β The value for which to find the error function value.
(U)Int*
or
Float*
or
Decimal*
Returned value
Returns the complementary error function value
Float*
Examples
Usage example
sql title=Query
SELECT erfc(0);
response title=Response
1
exp {#exp}
Introduced in: v1.1
Returns e raised to the power of
x
, where
x
is the given argument to the function.
Syntax
sql
exp(x)
Arguments
x
β The exponent.
(U)Int*
or
Float*
or
Decimal*
Returned value
Returns
e^x
Float*
Examples
Basic usage
sql title=Query
SELECT round(exp(-1), 4)
response title=Response
ββround(exp(-1), 4)ββ
β 0.3679 β
βββββββββββββββββββββ
exp10 {#exp10}
Introduced in: v1.1
Returns 10 to the power of the given argument.
Syntax
sql
exp10(x)
Arguments
x
β The exponent.
(U)Int*
or
Float*
or
Decimal*
Returned value
Returns 10^x
Float*
Examples
Usage example
sql title=Query
SELECT exp10(2);
response title=Response
100
exp2 {#exp2}
Introduced in: v1.1
Returns 2 to the power of the given argument.
Syntax
sql
exp2(x)
Arguments
x
β The exponent.
(U)Int*
or
Float*
or
Decimal*
Returned value
Returns 2^x
Float*
Examples
Usage example
sql title=Query
SELECT exp2(3);
response title=Response
8
factorial {#factorial}
Introduced in: v22.11
Computes the factorial of an integer value.
The factorial of 0 is 1. Likewise, the
factorial()
function returns
1
for any negative value.
The maximum positive value for the input argument is
20
, a value of
21
or greater will cause an exception.
Syntax
sql
factorial(n)
Arguments
n
β Integer value for which to calculate the factorial. Maximum value is 20.
(U)Int8/16/32/64
Returned value
Returns the factorial of the input as UInt64. Returns 1 for input 0 or any negative value.
UInt64
Examples
Usage example
sql title=Query
factorial(10)
response title=Response
3628800
hypot {#hypot}
Introduced in: v20.12
Returns the length of the hypotenuse of a right-angle triangle.
Hypot avoids problems that occur when squaring very large or very small numbers.
Syntax
sql
hypot(x, y)
Arguments
x
β The first cathetus of a right-angle triangle.
(U)Int*
or
Float*
or
Decimal*
y
β The second cathetus of a right-angle triangle.
(U)Int*
or
Float*
or
Decimal*
Returned value
Returns the length of the hypotenuse of a right-angle triangle.
Float64
Examples
Basic usage
sql title=Query
SELECT hypot(1, 1)
response title=Response
1.4142135623730951
intExp10 {#intExp10} | {"source_file": "math-functions.md"} | [
0.017582012340426445,
-0.023611683398485184,
-0.03690463304519653,
0.04155110567808151,
0.02604818157851696,
-0.08167993277311325,
0.06753714382648468,
0.08334937691688538,
0.046275604516267776,
0.016569986939430237,
0.02703981287777424,
-0.12914283573627472,
-0.0026313455309718847,
0.0039... |
47347810-9a5d-4b3b-abda-9dd4ed831921 | Examples
Basic usage
sql title=Query
SELECT hypot(1, 1)
response title=Response
1.4142135623730951
intExp10 {#intExp10}
Introduced in: v1.1
Like
exp10
but returns a
UInt64
number.
Syntax
sql
intExp10(x)
Arguments
x
β The exponent.
Int*
or
UInt*
or
Float*
Returned value
Returns 10^x.
UInt64
Examples
Usage example
sql title=Query
SELECT intExp10(2);
response title=Response
100
intExp2 {#intExp2}
Introduced in: v1.1
Like
exp2
but returns a
UInt64
number.
Syntax
sql
intExp2(x)
Arguments
x
β The exponent.
Int*
or
UInt*
or
Float*
Returned value
Returns 2^x.
UInt64
Examples
Usage example
sql title=Query
SELECT intExp2(3);
response title=Response
8
lgamma {#lgamma}
Introduced in: v1.1
Returns the logarithm of the gamma function.
Syntax
sql
lgamma(x)
Arguments
x
β The number for which to compute the logarithm of the gamma function.
(U)Int*
or
Float*
or
Decimal*
Returned value
Returns the logarithm of the gamma function of
x
.
Float*
Examples
Usage example
sql title=Query
SELECT lgamma(5);
response title=Response
3.1780538303479458
log {#log}
Introduced in: v1.1
Returns the natural logarithm of the argument.
Syntax
sql
log(x)
Aliases
:
ln
Arguments
x
β The number for which to compute the natural logarithm of.
(U)Int*
or
Float*
or
Decimal*
Returned value
Returns the natural logarithm of
x
.
Float*
Examples
Usage example
sql title=Query
SELECT log(10);
response title=Response
2.302585092994046
log10 {#log10}
Introduced in: v1.1
Returns the decimal logarithm of the argument.
Syntax
sql
log10(x)
Arguments
x
β Number for which to compute the decimal logarithm of.
(U)Int*
or
Float*
or
Decimal*
Returned value
Returns the decimal logarithm of
x
.
Float*
Examples
Usage example
sql title=Query
SELECT log10(100);
response title=Response
2
log1p {#log1p}
Introduced in: v20.12
Calculates log(1+x).
The calculation log1p(x) is more accurate than log(1+x) for small values of
x
.
Syntax
sql
log1p(x)
Arguments
x
β Values from the interval:
-1 < x < +β
.
(U)Int*
or
Float*
or
Decimal*
Returned value
Returns values from the interval: -β < log1p(x) < +β
Float64
Examples
Usage example
sql title=Query
SELECT log1p(0)
response title=Response
0
log2 {#log2}
Introduced in: v1.1
Returns the binary logarithm of the argument.
Syntax
sql
log2(x)
Arguments
x
β The number for which to compute the binary logarithm of.
(U)Int*
or
Float*
or
Decimal*
Returned value
Returns the binary logarithm of
x
.
Float*
Examples
Usage example
sql title=Query
SELECT log2(8);
response title=Response
3
pi {#pi}
Introduced in: v1.1
Returns pi (Ο).
Syntax
sql
pi()
Arguments
None.
Returned value
Returns pi
Float64
Examples
Usage example
sql title=Query
SELECT pi(); | {"source_file": "math-functions.md"} | [
-0.027346154674887657,
-0.0022164671681821346,
-0.03068612515926361,
0.00688824150711298,
-0.05896300449967384,
-0.05993719398975372,
0.06636670231819153,
0.09404638409614563,
-0.02210809290409088,
-0.043000344187021255,
0.005969694349914789,
-0.05138763412833214,
0.058643896132707596,
-0.... |
87232b0b-33e2-4403-bd84-55ab37bf5456 | pi {#pi}
Introduced in: v1.1
Returns pi (Ο).
Syntax
sql
pi()
Arguments
None.
Returned value
Returns pi
Float64
Examples
Usage example
sql title=Query
SELECT pi();
response title=Response
3.141592653589793
pow {#pow}
Introduced in: v1.1
Returns x raised to the power of y.
Syntax
sql
pow(x, y)
Aliases
:
power
Arguments
x
β The base.
(U)Int8/16/32/64
or
Float*
or
Decimal*
y
β The exponent.
(U)Int8/16/32/64
or
Float*
or
Decimal*
Returned value
Returns x^y
Float64
Examples
Usage example
sql title=Query
SELECT pow(2, 3);
response title=Response
8
radians {#radians}
Introduced in: v22.2
Converts degrees to radians.
Syntax
sql
radians(x)
Arguments
x
β Input in degrees.
(U)Int*
or
Float*
or
Decimal*
Returned value
Returns value in radians
Float64
Examples
Usage example
sql title=Query
SELECT radians(180)
response title=Response
3.141592653589793
sign {#sign}
Introduced in: v21.2
Returns the sign of a real number.
Syntax
sql
sign(x)
Arguments
x
β Values from -β to +β.
(U)Int*
or
Decimal*
or
Float*
Returned value
Returns
-1
for
x < 0
,
0
for
x = 0
,
1
for
x > 0
.
Int8
Examples
Sign for zero
sql title=Query
SELECT sign(0)
response title=Response
0
Sign for positive
sql title=Query
SELECT sign(1)
response title=Response
1
Sign for negative
sql title=Query
SELECT sign(-1)
response title=Response
-1
sin {#sin}
Introduced in: v
Returns the sine of the argument.
Syntax
sql
sin(x)
Arguments
x
β The number whose sine will be returned.
(U)Int*
or
Float*
or
Decimal*
Returned value
Returns the sine of x.
Examples
simple
sql title=Query
SELECT sin(1.23)
response title=Response
0.9424888019316975
sinh {#sinh}
Introduced in: v20.12
Returns the hyperbolic sine.
Syntax
sql
sinh(x)
Arguments
x
β The angle, in radians. Values from the interval: -β < x < +β.
(U)Int*
or
Float*
or
Decimal*
Returned value
Returns values from the interval: -β < sinh(x) < +β
Float64
Examples
Usage example
sql title=Query
SELECT sinh(0)
response title=Response
0
sqrt {#sqrt}
Introduced in: v1.1
Returns the square root of the argument.
Syntax
sql
sqrt(x)
Arguments
x
β The number for which to find the square root of.
(U)Int*
or
Float*
or
Decimal*
Returned value
Returns the square root of x
Float*
Examples
Usage example
sql title=Query
SELECT sqrt(16);
response title=Response
4
tan {#tan}
Introduced in: v1.1
Returns the tangent of the argument.
Syntax
sql
tan(x)
Arguments
x
β The angle in radians.
(U)Int*
or
Float*
or
Decimal*
Returned value
Returns the tangent of
x
.
Float*
Examples
Usage example
sql title=Query
SELECT tan(0);
response title=Response
0
tanh {#tanh}
Introduced in: v20.1
Returns the hyperbolic tangent.
Syntax
sql
tanh(x)
Arguments | {"source_file": "math-functions.md"} | [
-0.02265975996851921,
0.02947486750781536,
-0.12080655992031097,
0.08284429460763931,
-0.04253290221095085,
-0.08169002830982208,
0.01569487527012825,
0.04877234622836113,
0.04825650528073311,
0.0237942673265934,
0.0004634522774722427,
-0.04582292214035988,
0.06851400434970856,
-0.00175333... |
1205d504-e73c-44bd-964d-e8ad2b9a0cbe | Examples
Usage example
sql title=Query
SELECT tan(0);
response title=Response
0
tanh {#tanh}
Introduced in: v20.1
Returns the hyperbolic tangent.
Syntax
sql
tanh(x)
Arguments
x
β The angle in radians. Values from the interval: -β < x < +β.
(U)Int*
or
Float*
or
Decimal*
Returned value
Returns values from the interval: -1 < tanh(x) < 1
Float*
Examples
Usage example
sql title=Query
SELECT tanh(0)
response title=Response
0
tgamma {#tgamma}
Introduced in: v1.1
Returns the gamma function.
Syntax
sql
tgamma(x)
Arguments
x
β The number for which to compute the gamma function of.
(U)Int*
or
Float*
or
Decimal*
Returned value
Returns the gamma function value
Float*
Examples
Usage example
sql title=Query
SELECT tgamma(5);
response title=Response
24
widthBucket {#widthBucket}
Introduced in: v23.3
Returns the number of the bucket in which parameter
operand
falls in a histogram having count equal-width buckets spanning the range
low
to
high
. Returns 0 if
operand
is less than
low
, and returns
count
+1 if
operand
is greater than or equal to
high
.
There is also a case insensitive alias called
WIDTH_BUCKET
to provide compatibility with other databases.
Syntax
sql
widthBucket(operand, low, high, count)
Aliases
:
width_bucket
Arguments
operand
β The value for which to determine the bucket.
(U)Int8/16/32/64
low
β The lower bound of the histogram range.
(U)Int8/16/32/64
high
β The upper bound of the histogram range.
(U)Int8/16/32/64
count
β The number of equal-width buckets. Cannot be zero.
UInt8/16/32/64
Returned value
Returns the bucket number as an integer. Returns 0 if operand < low, returns count+1 if operand >= high.
UInt8/16/32/64
Examples
Usage example
sql title=Query
widthBucket(10.15, -8.6, 23, 18)
response title=Response
11 | {"source_file": "math-functions.md"} | [
-0.01349561382085085,
0.045523691922426224,
-0.02841133438050747,
-0.001318279537372291,
-0.08325168490409851,
-0.030272789299488068,
0.05980300530791283,
0.06609330326318741,
0.024059157818555832,
-0.008149764500558376,
0.035285498946905136,
-0.0833977535367012,
0.04439574107527733,
-0.02... |
f253751f-840b-4691-81f2-33611c3e76d5 | description: 'Documentation for encryption functions'
sidebar_label: 'Encryption'
slug: /sql-reference/functions/encryption-functions
title: 'Encryption functions'
keywords: ['encryption', 'regular functions', 'encrypt', 'decrypt']
doc_type: 'reference'
Encryption functions
These functions implement encryption and decryption of data with AES (Advanced Encryption Standard) algorithm.
The key length depends on the encryption mode:
16
,
24
, and
32
bytes long for
-128-
,
-196-
, and
-256-
modes respectively.
The initialization vector length is always 16 bytes (bytes in excess of 16 are ignored).
aes_decrypt_mysql {#aes_decrypt_mysql}
Introduced in: v20.12
Decrypts data encrypted by MySQL's
AES_ENCRYPT
function.
Produces the same plaintext as
decrypt
for the same inputs.
When
key
or
iv
are longer than they should normally be,
aes_decrypt_mysql
will stick to what MySQL's
aes_decrypt
does which is to 'fold'
key
and ignore the excess bits of
IV
.
Supports the following decryption modes:
aes-128-ecb, aes-192-ecb, aes-256-ecb
aes-128-cbc, aes-192-cbc, aes-256-cbc
aes-128-cfb128
aes-128-ofb, aes-192-ofb, aes-256-ofb
Syntax
sql
aes_decrypt_mysql(mode, ciphertext, key[, iv])
Arguments
mode
β Decryption mode.
String
ciphertext
β Encrypted text that needs to be decrypted.
String
key
β Decryption key.
String
iv
β Optional. Initialization vector.
String
Returned value
Returns the decrypted String.
String
Examples
Decrypt MySQL data
```sql title=Query
-- Let's decrypt data we've previously encrypted with MySQL:
mysql> SET block_encryption_mode='aes-256-ofb';
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT aes_encrypt('Secret', '123456789101213141516171819202122', 'iviviviviviviviv123456') as ciphertext;
+------------------------+
| ciphertext |
+------------------------+
| 0x24E9E4966469 |
+------------------------+
1 row in set (0.00 sec)
SELECT aes_decrypt_mysql('aes-256-ofb', unhex('24E9E4966469'), '123456789101213141516171819202122', 'iviviviviviviviv123456') AS plaintext
```
response title=Response
ββplaintextββ
β Secret β
βββββββββββββ
aes_encrypt_mysql {#aes_encrypt_mysql}
Introduced in: v20.12
Encrypts text the same way as MySQL's
AES_ENCRYPT
function does.
The resulting ciphertext can be decrypted with MySQL's
AES_DECRYPT
function.
Produces the same ciphertext as the
encrypt
function for the same inputs.
When
key
or
iv
are longer than they should normally be,
aes_encrypt_mysql
will stick to what MySQL's
aes_encrypt
does which is to 'fold'
key
and ignore the excess bits of
iv
.
The supported encryption modes are:
aes-128-ecb, aes-192-ecb, aes-256-ecb
aes-128-cbc, aes-192-cbc, aes-256-cbc
aes-128-ofb, aes-192-ofb, aes-256-ofb
Syntax
sql
aes_encrypt_mysql(mode, plaintext, key[, iv])
Arguments
mode
β Encryption mode.
String
plaintext
β Text that should be encrypted.
String | {"source_file": "encryption-functions.md"} | [
0.006080928258597851,
0.02088582143187523,
-0.03003426268696785,
-0.03201252594590187,
-0.0373757965862751,
-0.06062067672610283,
0.04572991281747818,
0.05287940055131912,
0.0000788721299613826,
-0.009320665150880814,
-0.013883738778531551,
0.018363935872912407,
0.111976757645607,
-0.01164... |
095084fc-64f4-41b9-8684-f08f98157557 | Syntax
sql
aes_encrypt_mysql(mode, plaintext, key[, iv])
Arguments
mode
β Encryption mode.
String
plaintext
β Text that should be encrypted.
String
key
β Encryption key. If the key is longer than required by
mode
, MySQL-specific key folding is performed.
String
iv
β Optional. Initialization vector. Only the first 16 bytes are taken into account.
String
Returned value
Ciphertext binary string.
String
Examples
Equal input comparison
sql title=Query
-- Given equal input encrypt and aes_encrypt_mysql produce the same ciphertext:
SELECT encrypt('aes-256-ofb', 'Secret', '12345678910121314151617181920212', 'iviviviviviviviv') = aes_encrypt_mysql('aes-256-ofb', 'Secret', '12345678910121314151617181920212', 'iviviviviviviviv') AS ciphertexts_equal;
response title=Response
ββciphertexts_equalββ
β 1 β
βββββββββββββββββββββ
Encrypt fails with long key
sql title=Query
-- But encrypt fails when key or iv is longer than expected:
SELECT encrypt('aes-256-ofb', 'Secret', '123456789101213141516171819202122', 'iviviviviviviviv123');
response title=Response
Received exception from server (version 22.6.1):
Code: 36. DB::Exception: Received from localhost:9000. DB::Exception: Invalid key size: 33 expected 32: While processing encrypt('aes-256-ofb', 'Secret', '123456789101213141516171819202122', 'iviviviviviviviv123').
MySQL compatibility
sql title=Query
-- aes_encrypt_mysql produces MySQL-compatible output:
SELECT hex(aes_encrypt_mysql('aes-256-ofb', 'Secret', '123456789101213141516171819202122', 'iviviviviviviviv123')) AS ciphertext;
response title=Response
ββciphertextββββ
β 24E9E4966469 β
ββββββββββββββββ
Longer IV produces the same result
sql title=Query
-- Notice how supplying even longer IV produces the same result
SELECT hex(aes_encrypt_mysql('aes-256-ofb', 'Secret', '123456789101213141516171819202122', 'iviviviviviviviv123456')) AS ciphertext
response title=Response
ββciphertextββββ
β 24E9E4966469 β
ββββββββββββββββ
decrypt {#decrypt}
Introduced in: v20.12
This function decrypts an AES-encrypted binary string using the following modes:
aes-128-ecb, aes-192-ecb, aes-256-ecb
aes-128-cbc, aes-192-cbc, aes-256-cbc
aes-128-ofb, aes-192-ofb, aes-256-ofb
aes-128-gcm, aes-192-gcm, aes-256-gcm
aes-128-ctr, aes-192-ctr, aes-256-ctr
aes-128-cfb, aes-128-cfb1, aes-128-cfb8
Syntax
sql
decrypt(mode, ciphertext, key[, iv, aad])
Arguments
mode
β Decryption mode.
String
ciphertext
β Encrypted text that should be decrypted.
String
key
β Decryption key.
String
iv
β Initialization vector. Required for
-gcm
modes, optional for others.
String
aad
β Additional authenticated data. Won't decrypt if this value is incorrect. Works only in
-gcm
modes, for others throws an exception.
String
Returned value
Returns decrypted plaintext.
String
Examples
Correctly decrypting encrypted data | {"source_file": "encryption-functions.md"} | [
0.009892638772726059,
0.021952757611870766,
-0.026133188977837563,
0.02039947174489498,
-0.03535610809922218,
-0.06850012391805649,
0.09214790165424347,
0.04822712764143944,
-0.025710921734571457,
-0.012062063440680504,
-0.012519086711108685,
-0.06345286965370178,
0.12964190542697906,
-0.0... |
8962258a-ea8c-468c-954d-d7943bbcb6dc | Returned value
Returns decrypted plaintext.
String
Examples
Correctly decrypting encrypted data
sql title=Query
-- Re-using the table from the encrypt function example
SELECT comment, hex(secret) FROM encryption_test;
response title=Response
ββcommentβββββββββββββββ¬βhex(secret)βββββββββββββββββββββββββββββββββββ
β aes-256-gcm β A8A3CCBC6426CFEEB60E4EAE03D3E94204C1B09E0254 β
β aes-256-gcm with AAD β A8A3CCBC6426D9A1017A0A932322F1852260A4AD6837 β
ββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββββ
ββcommentβββββββββββββββββββββββββββ¬βhex(secret)βββββββββββββββββββββββ
β aes-256-ofb no IV β B4972BDC4459 β
β aes-256-ofb no IV, different key β 2FF57C092DC9 β
β aes-256-ofb with IV β 5E6CB398F653 β
β aes-256-cbc no IV β 1BC0629A92450D9E73A00E7D02CF4142 β
ββββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββ
Incorrectly decrypting encrypted data
sql title=Query
SELECT comment, decrypt('aes-256-cfb128', secret, '12345678910121314151617181920212') AS plaintext FROM encryption_test
response title=Response
-- Notice how only a portion of the data was properly decrypted, and the rest is gibberish since either `mode`, `key`, or `iv` were different upon encryption.
ββcommentβββββββββββββββ¬βplaintextβββ
β aes-256-gcm β OQοΏ½E
οΏ½tοΏ½7TοΏ½\οΏ½οΏ½οΏ½\οΏ½ β
β aes-256-gcm with AAD β OQοΏ½E
οΏ½\οΏ½οΏ½siοΏ½οΏ½οΏ½οΏ½;οΏ½oοΏ½οΏ½ β
ββββββββββββββββββββββββ΄βββββββββββββ
ββcommentβββββββββββββββββββββββββββ¬βplaintextββ
β aes-256-ofb no IV β Secret β
β aes-256-ofb no IV, different key β οΏ½4οΏ½
οΏ½ β
β aes-256-ofb with IV β οΏ½οΏ½οΏ½6οΏ½~ β
βaes-256-cbc no IV β οΏ½2*4οΏ½h3cοΏ½4wοΏ½οΏ½@
ββββββββββββββββββββββββββββββββββββ΄ββββββββββββ
encrypt {#encrypt}
Introduced in: v20.12
Encrypts plaintext into ciphertext using AES in one of the following modes:
aes-128-ecb, aes-192-ecb, aes-256-ecb
aes-128-cbc, aes-192-cbc, aes-256-cbc
aes-128-ofb, aes-192-ofb, aes-256-ofb
aes-128-gcm, aes-192-gcm, aes-256-gcm
aes-128-ctr, aes-192-ctr, aes-256-ctr
aes-128-cfb, aes-128-cfb1, aes-128-cfb8
Syntax
sql
encrypt(mode, plaintext, key[, iv, aad])
Arguments
mode
β Encryption mode.
String
plaintext
β Text that should be encrypted.
String
key
β Encryption key.
String
iv
β Initialization vector. Required for
-gcm
modes, optional for others.
String
aad
β Additional authenticated data. It isn't encrypted, but it affects decryption. Works only in
-gcm
modes, for others it throws an exception.
String
Returned value
Returns binary string ciphertext.
String
Examples
Example encryption
``sql title=Query
CREATE TABLE encryption_test
(
comment
String,
secret` String
)
ENGINE = MergeTree; | {"source_file": "encryption-functions.md"} | [
-0.03868672251701355,
-0.0007912039291113615,
-0.018104102462530136,
0.014878925867378712,
-0.05288020521402359,
-0.06258777529001236,
0.09613575786352158,
-0.010078039951622486,
0.017529785633087158,
0.036258239299058914,
0.021142181009054184,
-0.07180505990982056,
0.050522468984127045,
-... |
60e196af-fcc7-4000-9ca1-cb715dbf225a | Returned value
Returns binary string ciphertext.
String
Examples
Example encryption
``sql title=Query
CREATE TABLE encryption_test
(
comment
String,
secret` String
)
ENGINE = MergeTree;
INSERT INTO encryption_test VALUES
('aes-256-ofb no IV', encrypt('aes-256-ofb', 'Secret', '12345678910121314151617181920212')),
('aes-256-ofb no IV, different key', encrypt('aes-256-ofb', 'Secret', 'keykeykeykeykeykeykeykeykeykeyke')),
('aes-256-ofb with IV', encrypt('aes-256-ofb', 'Secret', '12345678910121314151617181920212', 'iviviviviviviviv')),
('aes-256-cbc no IV', encrypt('aes-256-cbc', 'Secret', '12345678910121314151617181920212'));
SELECT comment, hex(secret) FROM encryption_test;
```
response title=Response
ββcommentβββββββββββββββββββββββββββ¬βhex(secret)βββββββββββββββββββββββ
β aes-256-ofb no IV β B4972BDC4459 β
β aes-256-ofb no IV, different key β 2FF57C092DC9 β
β aes-256-ofb with IV β 5E6CB398F653 β
β aes-256-cbc no IV β 1BC0629A92450D9E73A00E7D02CF4142 β
ββββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββ
Example with GCM mode
```sql title=Query
INSERT INTO encryption_test VALUES
('aes-256-gcm', encrypt('aes-256-gcm', 'Secret', '12345678910121314151617181920212', 'iviviviviviviviv')),
('aes-256-gcm with AAD', encrypt('aes-256-gcm', 'Secret', '12345678910121314151617181920212', 'iviviviviviviviv', 'aad'));
SELECT comment, hex(secret) FROM encryption_test WHERE comment LIKE '%gcm%';
```
response title=Response
ββcommentβββββββββββββββ¬βhex(secret)βββββββββββββββββββββββββββββββββββ
β aes-256-gcm β A8A3CCBC6426CFEEB60E4EAE03D3E94204C1B09E0254 β
β aes-256-gcm with AAD β A8A3CCBC6426D9A1017A0A932322F1852260A4AD6837 β
ββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββββ
tryDecrypt {#tryDecrypt}
Introduced in: v22.10
Similar to the
decrypt
function, but returns
NULL
if decryption fails when using the wrong key.
Syntax
sql
tryDecrypt(mode, ciphertext, key[, iv, aad])
Arguments
mode
β Decryption mode.
String
ciphertext
β Encrypted text that should be decrypted.
String
key
β Decryption key.
String
iv
β Optional. Initialization vector. Required for
-gcm
modes, optional for other modes.
String
aad
β Optional. Additional authenticated data. Won't decrypt if this value is incorrect. Works only in
-gcm
modes, for other modes throws an exception.
String
Returned value
Returns the decrypted String, or
NULL
if decryption fails.
Nullable(String)
Examples
Create table and insert data | {"source_file": "encryption-functions.md"} | [
0.03678427264094353,
0.030270781368017197,
-0.04729733243584633,
0.030054179951548576,
-0.06820983439683914,
-0.05660593882203102,
0.07739853858947754,
0.016987750306725502,
-0.009548848494887352,
-0.030468570068478584,
-0.007169697899371386,
-0.10480202734470367,
0.11114479601383209,
-0.0... |
802706a7-2d66-4034-b26d-3f5581ba2179 | Returned value
Returns the decrypted String, or
NULL
if decryption fails.
Nullable(String)
Examples
Create table and insert data
```sql title=Query
-- Let's create a table where user_id is the unique user id, encrypted is an encrypted string field, iv is an initial vector for decrypt/encrypt.
-- Assume that users know their id and the key to decrypt the encrypted field:
CREATE TABLE decrypt_null
(
dt DateTime,
user_id UInt32,
encrypted String,
iv String
)
ENGINE = MergeTree;
-- Insert some data:
INSERT INTO decrypt_null VALUES
('2022-08-02 00:00:00', 1, encrypt('aes-256-gcm', 'value1', 'keykeykeykeykeykeykeykeykeykey01', 'iv1'), 'iv1'),
('2022-09-02 00:00:00', 2, encrypt('aes-256-gcm', 'value2', 'keykeykeykeykeykeykeykeykeykey02', 'iv2'), 'iv2'),
('2022-09-02 00:00:01', 3, encrypt('aes-256-gcm', 'value3', 'keykeykeykeykeykeykeykeykeykey03', 'iv3'), 'iv3');
-- Try decrypt with one key
SELECT
dt,
user_id,
tryDecrypt('aes-256-gcm', encrypted, 'keykeykeykeykeykeykeykeykeykey02', iv) AS value
FROM decrypt_null
ORDER BY user_id ASC
```
response title=Response
βββββββββββββββββββdtββ¬βuser_idββ¬βvalueβββ
β 2022-08-02 00:00:00 β 1 β α΄Ία΅α΄Έα΄Έ β
β 2022-09-02 00:00:00 β 2 β value2 β
β 2022-09-02 00:00:01 β 3 β α΄Ία΅α΄Έα΄Έ β
βββββββββββββββββββββββ΄ββββββββββ΄βββββββββ | {"source_file": "encryption-functions.md"} | [
0.014014736749231815,
0.03169182687997818,
-0.033721309155225754,
0.01815032586455345,
-0.0639154314994812,
-0.06311149895191193,
0.061852775514125824,
0.0720270499587059,
0.005413273815065622,
-0.047339070588350296,
0.01415436714887619,
-0.0712522566318512,
0.001181925181299448,
-0.050145... |
2f7fdb4a-3176-4543-a33c-42c7aed9d282 | description: 'Documentation for Arithmetic Functions'
sidebar_label: 'Arithmetic'
slug: /sql-reference/functions/arithmetic-functions
title: 'Arithmetic Functions'
doc_type: 'reference'
Arithmetic functions
Overview {#overview}
Arithmetic functions work for any two operands of type
UInt8
,
UInt16
,
UInt32
,
UInt64
,
Int8
,
Int16
,
Int32
,
Int64
,
Float32
, or
Float64
.
Before performing the operation, both operands are cast to the result type. The result type is determined as follows (unless specified
differently in the function documentation below):
- If both operands are up to 32 bits wide, the size of the result type will be the size of the next bigger type following the bigger of the
two operands (integer size promotion). For example,
UInt8 + UInt16 = UInt32
or
Float32 * Float32 = Float64
.
- If one of the operands has 64 or more bits, the size of the result type will be the same size as the bigger of the two operands. For
example,
UInt32 + UInt128 = UInt128
or
Float32 * Float64 = Float64
.
- If one of the operands is signed, the result type will also be signed, otherwise it will be signed. For example,
UInt32 * Int32 = Int64
.
These rules make sure that the result type will be the smallest type which can represent all possible results. While this introduces a risk
of overflows around the value range boundary, it ensures that calculations are performed quickly using the maximum native integer width of
64 bit. This behavior also guarantees compatibility with many other databases which provide 64 bit integers (BIGINT) as the biggest integer
type.
Example:
sql
SELECT toTypeName(0), toTypeName(0 + 0), toTypeName(0 + 0 + 0), toTypeName(0 + 0 + 0 + 0)
text
ββtoTypeName(0)ββ¬βtoTypeName(plus(0, 0))ββ¬βtoTypeName(plus(plus(0, 0), 0))ββ¬βtoTypeName(plus(plus(plus(0, 0), 0), 0))ββ
β UInt8 β UInt16 β UInt32 β UInt64 β
βββββββββββββββββ΄βββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββ
Overflows are produced the same way as in C++.
abs {#abs}
Introduced in: v1.1
Calculates the absolute value of
x
. Has no effect if
x
is of an unsigned type. If
x
is of a signed type, it returns an unsigned number.
Syntax
sql
abs(x)
Arguments
x
β Value to get the absolute value of
Returned value
The absolute value of
x
Examples
Usage example
sql title=Query
SELECT abs(-0.5)
response title=Response
0.5
avg2 {#avg2}
Introduced in: v25.11
Computes and returns the average value of the provided arguments.
Supports numerical and temporal types.
Syntax
sql
avg2(x1, x2])
Arguments
x1, x2]
β Accepts two values for averaging.
Returned value
Returns the average value of the provided arguments, promoted to the largest compatible type.
Examples
Numeric types | {"source_file": "arithmetic-functions.md"} | [
0.016942618414759636,
0.0215641837567091,
0.006772194989025593,
-0.01187305897474289,
-0.06796830892562866,
-0.055830102413892746,
0.009530752897262573,
0.030730515718460083,
-0.018863992765545845,
-0.022467486560344696,
-0.025014454498887062,
-0.03712775558233261,
0.0029523447155952454,
-... |
6c31afd8-4dd2-4a60-b934-650ee6589ee8 | x1, x2]
β Accepts two values for averaging.
Returned value
Returns the average value of the provided arguments, promoted to the largest compatible type.
Examples
Numeric types
sql title=Query
SELECT avg2(toUInt8(3), 1.0) AS result, toTypeName(result) AS type;
-- The type returned is a Float64 as the UInt8 must be promoted to 64 bit for the comparison.
response title=Response
ββresultββ¬βtypeβββββ
β 2 β Float64 β
ββββββββββ΄ββββββββββ
Decimal types
sql title=Query
SELECT avg2(toDecimal32(1, 2), 2) AS result, toTypeName(result) AS type;
response title=Response
ββresultββ¬βtypeβββββββββββ
β 1.5 β Decimal(9, 2) β
ββββββββββ΄ββββββββββββββββ
Date types
sql title=Query
SELECT avg2(toDate('2025-01-01'), toDate('2025-01-05')) AS result, toTypeName(result) AS type;
response title=Response
ββββββresultββ¬βtypeββ
β 2025-01-03 β Date β
ββββββββββββββ΄βββββββ
DateTime types
sql title=Query
SELECT avg2(toDateTime('2025-01-01 00:00:00'), toDateTime('2025-01-03 12:00:00')) AS result, toTypeName(result) AS type;
response title=Response
βββββββββββββββresultββ¬βtypeββββββ
β 2025-01-02 06:00:00 β DateTime β
βββββββββββββββββββββββ΄βββββββββββ
Time64 types
sql title=Query
SELECT avg2(toTime64('12:00:00', 0), toTime64('14:00:00', 0)) AS result, toTypeName(result) AS type;
response title=Response
ββββresultββ¬βtypeβββββββ
β 13:00:00 β Time64(0) β
ββββββββββββ΄ββββββββββββ
byteSwap {#byteSwap}
Introduced in: v23.10
Reverses the bytes of an integer, i.e. changes its
endianness
.
The below example can be worked out in the following manner:
Convert the base-10 integer to its equivalent hexadecimal format in big-endian format, i.e. 3351772109 -> C7 C7 FB CD (4 bytes)
Reverse the bytes, i.e. C7 C7 FB CD -> CD FB C7 C7
Convert the result back to an integer assuming big-endian, i.e. CD FB C7 C7 -> 3455829959
One use case of this function is reversing IPv4s:
result
ββtoIPv4(byteSwap(toUInt32(toIPv4('205.251.199.199'))))ββ
β 199.199.251.205 β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Syntax
sql
byteSwap(x)
Arguments
x
β An integer value.
(U)Int*
Returned value
Returns
x
with bytes reversed.
(U)Int*
Examples
Usage example
sql title=Query
SELECT byteSwap(3351772109)
response title=Response
3455829959
8-bit
sql title=Query
SELECT byteSwap(54)
response title=Response
54
16-bit
sql title=Query
SELECT byteSwap(4135)
response title=Response
10000
32-bit
sql title=Query
SELECT byteSwap(3351772109)
response title=Response
3455829959
64-bit
sql title=Query
SELECT byteSwap(123294967295)
response title=Response
18439412204227788800
divide {#divide}
Introduced in: v1.1
Calculates the quotient of two values `a` and `b`. The result type is always [Float64](/sql-reference/data-types/float).
Integer division is provided by the `intDiv` function.
:::note
Division by `0` returns `inf`, `-inf`, or `nan`.
:::
Syntax | {"source_file": "arithmetic-functions.md"} | [
0.02028554677963257,
-0.04350712150335312,
0.01854354329407215,
0.0985139012336731,
-0.07087481021881104,
-0.0467018261551857,
0.05325734242796898,
0.06591904908418655,
-0.045599374920129776,
-0.026967337355017662,
-0.04749686270952225,
-0.12594075500965118,
-0.0028287440072745085,
-0.0235... |
c345dedb-ef7b-4393-ac41-659ca84e2fbd | :::note
Division by `0` returns `inf`, `-inf`, or `nan`.
:::
Syntax
sql
divide(x, y)
Arguments
x
β Dividend -
y
β Divisor
Returned value
The quotient of x and y
Examples
Dividing two numbers
sql title=Query
SELECT divide(25,5) AS quotient, toTypeName(quotient)
response title=Response
5 Float64
Dividing by zero
sql title=Query
SELECT divide(25,0)
response title=Response
inf
divideDecimal {#divideDecimal}
Introduced in: v22.12
Performs division on two decimals. Result value will be of type
Decimal256
.
Result scale can be explicitly specified by
result_scale
argument (const Integer in range
[0, 76]
). If not specified, the result scale is the max scale of given arguments.
:::note
These function work significantly slower than usual
divide
.
In case you don't really need controlled precision and/or need fast computation, consider using
divide
.
:::
Syntax
sql
divideDecimal(x, y[, result_scale])
Arguments
x
β First value:
Decimal
. -
y
β Second value:
Decimal
. -
result_scale
β Scale of result. Type
Int/UInt
.
Returned value
The result of division with given scale.
Decimal256
Examples
Example 1
sql title=Query
divideDecimal(toDecimal256(-12, 0), toDecimal32(2.1, 1), 10)
response title=Response
ββdivideDecimal(toDecimal256(-12, 0), toDecimal32(2.1, 1), 10)ββ
β -5.7142857142 β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Example 2
sql title=Query
SELECT toDecimal64(-12, 1) / toDecimal32(2.1, 1);
SELECT toDecimal64(-12, 1) as a, toDecimal32(2.1, 1) as b, divideDecimal(a, b, 1), divideDecimal(a, b, 5);
response title=Response
ββdivide(toDecimal64(-12, 1), toDecimal32(2.1, 1))ββ
β -5.7 β
ββββββββββββββββββββββββββββββββββββββββββββββββββββ
ββββaββ¬βββbββ¬βdivideDecimal(toDecimal64(-12, 1), toDecimal32(2.1, 1), 1)ββ¬βdivideDecimal(toDecimal64(-12, 1), toDecimal32(2.1, 1), 5)ββ
β -12 β 2.1 β -5.7 β -5.71428 β
βββββββ΄ββββββ΄βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
divideOrNull {#divideOrNull}
Introduced in: v25.5
Same as
divide
but returns NULL when dividing by zero.
Syntax
sql
divideOrNull(x, y)
Arguments
x
β Dividend -
y
β Divisor
Returned value
The quotient of x and y, or NULL.
Examples
Dividing by zero
sql title=Query
SELECT divideOrNull(25, 0)
response title=Response
\N
gcd {#gcd}
Introduced in: v1.1
Returns the greatest common divisor of two values a and b.
An exception is thrown when dividing by zero or when dividing a minimal
negative number by minus one.
Syntax
sql
gcd(x, y)
Arguments
x
β First integer -
y
β Second integer
Returned value
The greatest common divisor of
x
and
y
.
Examples
Usage example | {"source_file": "arithmetic-functions.md"} | [
-0.0018684649839997292,
0.014384040609002113,
-0.05215068161487579,
-0.014347768388688564,
0.0007561289821751416,
-0.08608408272266388,
0.025823676958680153,
0.04742822423577309,
-0.03263231739401817,
0.03138406574726105,
0.04968663677573204,
-0.0783466100692749,
-0.021906910464167595,
0.0... |
e8c002f5-ecdf-4451-9120-39738fa3dd45 | Syntax
sql
gcd(x, y)
Arguments
x
β First integer -
y
β Second integer
Returned value
The greatest common divisor of
x
and
y
.
Examples
Usage example
sql title=Query
SELECT gcd(12, 18)
response title=Response
6
ifNotFinite {#ifNotFinite}
Introduced in: v20.3
Checks whether a floating point value is finite.
You can get a similar result by using the
ternary operator
:
isFinite(x) ? x : y
.
Syntax
sql
ifNotFinite(x,y)
Arguments
x
β Value to check if infinite.
Float*
y
β Fallback value.
Float*
Returned value
x
if
x
is finite.
y
if
x
is not finite.
Examples
Usage example
sql title=Query
SELECT 1/0 AS infimum, ifNotFinite(infimum,42)
response title=Response
inf 42
intDiv {#intDiv}
Introduced in: v1.1
Performs an integer division of two values
x
by
y
. In other words it
computes the quotient rounded down to the next smallest integer.
The result has the same width as the dividend (the first parameter).
An exception is thrown when dividing by zero, when the quotient does not fit
in the range of the dividend, or when dividing a minimal negative number by minus one.
Syntax
sql
intDiv(x, y)
Arguments
x
β Left hand operand. -
y
β Right hand operand.
Returned value
Result of integer division of
x
and
y
Examples
Integer division of two floats
sql title=Query
SELECT intDiv(toFloat64(1), 0.001) AS res, toTypeName(res)
response title=Response
βββresββ¬βtoTypeName(intDiv(toFloat64(1), 0.001))ββ
β 1000 β Int64 β
ββββββββ΄ββββββββββββββββββββββββββββββββββββββββββ
Quotient does not fit in the range of the dividend
sql title=Query
SELECT
intDiv(1, 0.001) AS res,
toTypeName(res)
response title=Response
Received exception from server (version 23.2.1):
Code: 153. DB::Exception: Received from localhost:9000. DB::Exception:
Cannot perform integer division, because it will produce infinite or too
large number: While processing intDiv(1, 0.001) AS res, toTypeName(res).
(ILLEGAL_DIVISION)
intDivOrNull {#intDivOrNull}
Introduced in: v25.5
Same as
intDiv
but returns NULL when dividing by zero or when dividing a
minimal negative number by minus one.
Syntax
sql
intDivOrNull(x, y)
Arguments
x
β Left hand operand.
(U)Int*
y
β Right hand operand.
(U)Int*
Returned value
Result of integer division of
x
and
y
, or NULL.
Examples
Integer division by zero
sql title=Query
SELECT intDivOrNull(1, 0)
response title=Response
\N
Dividing a minimal negative number by minus 1
sql title=Query
SELECT intDivOrNull(-9223372036854775808, -1)
response title=Response
\N
intDivOrZero {#intDivOrZero}
Introduced in: v1.1
Same as
intDiv
but returns zero when dividing by zero or when dividing a
minimal negative number by minus one.
Syntax
sql
intDivOrZero(a, b)
Arguments
a
β Left hand operand.
(U)Int*
b
β Right hand operand.
(U)Int*
Returned value | {"source_file": "arithmetic-functions.md"} | [
-0.00471923965960741,
0.01131201907992363,
-0.08018656820058823,
-0.026844194158911705,
0.05654219910502434,
-0.09934525936841965,
0.0684371367096901,
0.0536993071436882,
-0.012944203801453114,
0.01516631804406643,
0.02988376095890999,
-0.014958889223635197,
0.025394419208168983,
-0.005421... |
c3cbbd96-08c4-44c0-b453-b11b533d59ad | Syntax
sql
intDivOrZero(a, b)
Arguments
a
β Left hand operand.
(U)Int*
b
β Right hand operand.
(U)Int*
Returned value
Result of integer division of a and b, or zero.
Examples
Integer division by zero
sql title=Query
SELECT intDivOrZero(1, 0)
response title=Response
0
Dividing a minimal negative number by minus 1
sql title=Query
SELECT intDivOrZero(0.05, -1)
response title=Response
0
isFinite {#isFinite}
Introduced in: v1.1
Returns
1
if the Float32 or Float64 argument not infinite and not a
NaN
,
otherwise this function returns
0
.
Syntax
sql
isFinite(x)
Arguments
x
β Number to check for finiteness.
Float*
Returned value
1
if x is not infinite and not
NaN
, otherwise
0
.
Examples
Test if a number is finite
sql title=Query
SELECT isFinite(inf)
response title=Response
0
isInfinite {#isInfinite}
Introduced in: v1.1
Returns `1` if the Float32 or Float64 argument is infinite, otherwise this function returns `0`.
Note that `0` is returned for a `NaN`.
Syntax
sql
isInfinite(x)
Arguments
x
β Number to check for infiniteness.
Float*
Returned value
1
if x is infinite, otherwise
0
(including for
NaN
).
Examples
Test if a number is infinite
sql title=Query
SELECT isInfinite(inf), isInfinite(NaN), isInfinite(10))
response title=Response
1 0 0
isNaN {#isNaN}
Introduced in: v1.1
Returns
1
if the Float32 and Float64 argument is
NaN
, otherwise returns
0
.
Syntax
sql
isNaN(x)
Arguments
x
β Argument to evaluate for if it is
NaN
.
Float*
Returned value
1
if
NaN
, otherwise
0
Examples
Usage example
sql title=Query
SELECT isNaN(NaN)
response title=Response
1
lcm {#lcm}
Introduced in: v1.1
Returns the least common multiple of two values
x
and
y
.
An exception is thrown when dividing by zero or when dividing a minimal negative number by minus one.
Syntax
sql
lcm(x, y)
Arguments
x
β First integer.
(U)Int*
y
β Second integer.
(U)Int*
Returned value
Returns the least common multiple of
x
and
y
.
(U)Int*
Examples
Usage example
sql title=Query
SELECT lcm(6, 8)
response title=Response
24
max2 {#max2}
Introduced in: v21.11
Returns the bigger of two numeric values `x` and `y`.
Syntax
sql
max2(x, y)
Arguments
x
β First value
(U)Int8/16/32/64
or
Float*
or
Decimal
y
β Second value
(U)Int8/16/32/64
or
Float*
or
Decimal
Returned value
Returns the bigger value of
x
and
y
.
Float64
Examples
Usage example
sql title=Query
SELECT max2(-1, 2)
response title=Response
2
midpoint {#midpoint}
Introduced in: v25.11
Computes and returns the average value of the provided arguments.
Supports numerical and temporal types.
Syntax
sql
midpoint(x1[, x2, ...])
Arguments
x1[, x2, ...]
β Accepts a single value or multiple values for averaging.
Returned value | {"source_file": "arithmetic-functions.md"} | [
0.008092856034636497,
-0.009447852149605751,
-0.06163206696510315,
0.021897127851843834,
-0.004290115088224411,
-0.09525517374277115,
0.06285468488931656,
0.017528509721159935,
-0.02637193165719509,
0.0381942018866539,
0.005467725917696953,
-0.0777713879942894,
0.040969446301460266,
-0.012... |
887a89ec-15d2-44d9-92ad-01d87a6065f2 | Syntax
sql
midpoint(x1[, x2, ...])
Arguments
x1[, x2, ...]
β Accepts a single value or multiple values for averaging.
Returned value
Returns the average value of the provided arguments, promoted to the largest compatible type.
Examples
Numeric types
sql title=Query
SELECT midpoint(1, toUInt8(3), 0.5) AS result, toTypeName(result) AS type;
-- The type returned is a Float64 as the UInt8 must be promoted to 64 bit for the comparison.
response title=Response
ββresultββ¬βtypeβββββ
β 1.5 β Float64 β
ββββββββββ΄ββββββββββ
Decimal types
sql title=Query
SELECT midpoint(toDecimal32(1.5, 2), toDecimal32(1, 1), 2) AS result, toTypeName(result) AS type;
response title=Response
ββresultββ¬βtypeβββββββββββ
β 1.5 β Decimal(9, 2) β
ββββββββββ΄ββββββββββββββββ
Date types
sql title=Query
SELECT midpoint(toDate('2025-01-01'), toDate('2025-01-05')) AS result, toTypeName(result) AS type;
response title=Response
ββββββresultββ¬βtypeββ
β 2025-01-03 β Date β
ββββββββββββββ΄βββββββ
DateTime types
sql title=Query
SELECT midpoint(toDateTime('2025-01-01 00:00:00'), toDateTime('2025-01-03 12:00:00')) AS result, toTypeName(result) AS type;
response title=Response
βββββββββββββββresultββ¬βtypeββββββ
β 2025-01-02 06:00:00 β DateTime β
βββββββββββββββββββββββ΄βββββββββββ
Time64 types
sql title=Query
SELECT midpoint(toTime64('12:00:00', 0), toTime64('14:00:00', 0)) AS result, toTypeName(result) AS type;
response title=Response
ββββresultββ¬βtypeβββββββ
β 13:00:00 β Time64(0) β
ββββββββββββ΄ββββββββββββ
min2 {#min2}
Introduced in: v21.11
Returns the smaller of two numeric values `x` and `y`.
Syntax
sql
min2(x, y)
Arguments
x
β First value
(U)Int8/16/32/64
or
Float*
or
Decimal
y
β Second value
(U)Int8/16/32/64
or
Float*
or
Decimal
Returned value
Returns the smaller value of
x
and
y
.
Float64
Examples
Usage example
sql title=Query
SELECT min2(-1, 2)
response title=Response
-1
minus {#minus}
Introduced in: v1.1
Calculates the difference of two values
a
and
b
. The result is always signed.
Similar to plus, it is possible to subtract an integer from a date or date with time.
Additionally, subtraction between date with time is supported, resulting in the time difference between them.
Syntax
sql
minus(x, y)
Arguments
x
β Minuend. -
y
β Subtrahend.
Returned value
x minus y
Examples
Subtracting two numbers
sql title=Query
SELECT minus(10, 5)
response title=Response
5
Subtracting an integer and a date
sql title=Query
SELECT minus(toDate('2025-01-01'),5)
response title=Response
2024-12-27
modulo {#modulo}
Introduced in: v1.1
Calculates the remainder of the division of two values a by b.
The result type is an integer if both inputs are integers. If one of the
inputs is a floating-point number, the result type is Float64.
The remainder is computed like in C++. Truncated division is used for
negative numbers. | {"source_file": "arithmetic-functions.md"} | [
0.04420715570449829,
-0.010811557061970234,
0.055823806673288345,
0.008614422753453255,
-0.04783331975340843,
-0.04950971156358719,
0.02996988594532013,
0.12142167240381241,
-0.03552113100886345,
-0.011088411323726177,
-0.06625999510288239,
-0.1240687370300293,
0.0408238023519516,
0.012269... |
dbdbc63c-5123-4a42-bb39-1e30cbf2f2ea | The remainder is computed like in C++. Truncated division is used for
negative numbers.
An exception is thrown when dividing by zero or when dividing a minimal
negative number by minus one.
Syntax
sql
modulo(a, b)
Aliases
:
mod
Arguments
a
β The dividend -
b
β The divisor (modulus)
Returned value
The remainder of a % b
Examples
Usage example
sql title=Query
SELECT modulo(5, 2)
response title=Response
1
moduloOrNull {#moduloOrNull}
Introduced in: v25.5
Calculates the remainder when dividing
a
by
b
. Similar to function
modulo
except that
moduloOrNull
will return NULL
if the right argument is 0.
Syntax
sql
moduloOrNull(x, y)
Aliases
:
modOrNull
Arguments
x
β The dividend.
(U)Int*
or
Float*
y
β The divisor (modulus).
(U)Int*
or
Float*
Returned value
Returns the remainder of the division of
x
by
y
, or null when the divisor is zero.
Examples
moduloOrNull by zero
sql title=Query
SELECT moduloOrNull(5, 0)
response title=Response
\N
moduloOrZero {#moduloOrZero}
Introduced in: v20.3
Like modulo but returns zero when the divisor is zero, as opposed to an
exception with the modulo function.
Syntax
sql
moduloOrZero(a, b)
Arguments
a
β The dividend.
(U)Int*
or
Float*
b
β The divisor (modulus).
(U)Int*
or
Float*
Returned value
Returns the remainder of a % b, or
0
when the divisor is
0
.
Examples
Usage example
sql title=Query
SELECT moduloOrZero(5, 0)
response title=Response
0
multiply {#multiply}
Introduced in: v1.1
Calculates the product of two values
x
and
y
.
Syntax
sql
multiply(x, y)
Arguments
x
β factor.
(U)Int*
or
Float*
or
Decimal
y
β factor.
(U)Int*
or
Float*
or
Decimal
Returned value
Returns the product of x and y
Examples
Multiplying two numbers
sql title=Query
SELECT multiply(5,5)
response title=Response
25
multiplyDecimal {#multiplyDecimal}
Introduced in: v22.12
Performs multiplication on two decimals. Result value will be of type
Decimal256
.
Result scale can be explicitly specified by
result_scale
argument (const Integer in range
[0, 76]
). If not specified, the result scale is the max scale of given arguments.
:::note
These functions work significantly slower than usual
multiply
.
In case you don't really need controlled precision and/or need fast computation, consider using
multiply
:::
Syntax
sql
multiplyDecimal(a, b[, result_scale])
Arguments
a
β First value.
Decimal
b
β Second value.
Decimal
result_scale
β Scale of result.
(U)Int*
Returned value
The result of multiplication with the given scale. Type:
Decimal256
Examples
Usage example
sql title=Query
SELECT multiplyDecimal(toDecimal256(-12, 0), toDecimal32(-2.1, 1), 1)
response title=Response
25.2
Difference with regular multiplication
sql title=Query
SELECT multiplyDecimal(toDecimal256(-12, 0), toDecimal32(-2.1, 1), 1) | {"source_file": "arithmetic-functions.md"} | [
-0.007057083770632744,
0.00793254841119051,
-0.03706342354416847,
0.002277146792039275,
-0.016667546704411507,
-0.10211402177810669,
0.05690259858965874,
0.09003935009241104,
-0.02323441207408905,
-0.006050189025700092,
0.06119773909449577,
-0.009981576353311539,
0.06023029610514641,
-0.02... |
c6df6028-0458-45ed-8d6e-000d29970f75 | response title=Response
25.2
Difference with regular multiplication
sql title=Query
SELECT multiplyDecimal(toDecimal256(-12, 0), toDecimal32(-2.1, 1), 1)
response title=Response
ββmultiply(toDecimal64(-12.647, 3), toDecimal32(2.1239, 4))ββ
β -26.8609633 β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ββmultiplyDecimal(toDecimal64(-12.647, 3), toDecimal32(2.1239, 4))ββ
β -26.8609 β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Decimal overflow
sql title=Query
SELECT
toDecimal64(-12.647987876, 9) AS a,
toDecimal64(123.967645643, 9) AS b,
multiplyDecimal(a, b);
SELECT
toDecimal64(-12.647987876, 9) AS a,
toDecimal64(123.967645643, 9) AS b,
a * b;
response title=Response
ββββββββββββββaββ¬βββββββββββββbββ¬βmultiplyDecimal(toDecimal64(-12.647987876, 9), toDecimal64(123.967645643, 9))ββ
β -12.647987876 β 123.967645643 β -1567.941279108 β
βββββββββββββββββ΄ββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Received exception from server (version 22.11.1):
Code: 407. DB::Exception: Received from localhost:9000. DB::Exception: Decimal math overflow:
While processing toDecimal64(-12.647987876, 9) AS a, toDecimal64(123.967645643, 9) AS b, a * b. (DECIMAL_OVERFLOW)
negate {#negate}
Introduced in: v1.1
Negates the argument
x
. The result is always signed.
Syntax
sql
negate(x)
Arguments
x
β The value to negate.
Returned value
Returns -x from x
Examples
Usage example
sql title=Query
SELECT negate(10)
response title=Response
-10
plus {#plus}
Introduced in: v1.1
Calculates the sum of two values
x
and
y
. Alias:
x + y
(operator).
It is possible to add an integer and a date or date with time. The former
operation increments the number of days in the date, the latter operation
increments the number of seconds in the date with time.
Syntax
sql
plus(x, y)
Arguments
x
β Left hand operand. -
y
β Right hand operand.
Returned value
Returns the sum of x and y
Examples
Adding two numbers
sql title=Query
SELECT plus(5,5)
response title=Response
10
Adding an integer and a date
sql title=Query
SELECT plus(toDate('2025-01-01'),5)
response title=Response
2025-01-06
positiveModulo {#positiveModulo}
Introduced in: v22.11
Calculates the remainder when dividing
x
by
y
. Similar to function
modulo
except that
positiveModulo
always return non-negative number.
Syntax
sql
positiveModulo(x, y)
Aliases
:
positive_modulo
,
pmod
Arguments
x
β The dividend.
(U)Int*
or
Float*
or
Decimal
y
β The divisor (modulus).
(U)Int*
or
Float*
or
Decimal
Returned value
Returns the difference between
x
and the nearest integer not greater than
x
divisible by
y
.
Examples
Usage example | {"source_file": "arithmetic-functions.md"} | [
-0.023806091398000717,
-0.007855504751205444,
0.006997611373662949,
-0.04579285904765129,
-0.06927947700023651,
-0.09112538397312164,
0.012248825281858444,
0.014618433080613613,
0.0538194477558136,
0.01044409442692995,
0.03498050197958946,
-0.10338514298200607,
-0.0015889833448454738,
-0.0... |
d74e09fb-4d52-4743-ae85-0785842a59ff | Returned value
Returns the difference between
x
and the nearest integer not greater than
x
divisible by
y
.
Examples
Usage example
sql title=Query
SELECT positiveModulo(-1, 10)
response title=Response
9
positiveModuloOrNull {#positiveModuloOrNull}
Introduced in: v25.5
Calculates the remainder when dividing
a
by
b
. Similar to function
positiveModulo
except that
positiveModuloOrNull
will return NULL
if the right argument is 0.
Syntax
sql
positiveModuloOrNull(x, y)
Aliases
:
positive_modulo_or_null
,
pmodOrNull
Arguments
x
β The dividend.
(U)Int*
/
Float32/64
. -
x
β The divisor (modulus).
(U)Int*
/
Float32/64
.
Returned value
Returns the difference between
x
and the nearest integer not greater than
x
divisible by
y
,
null
when the divisor is zero.
Examples
positiveModuloOrNull
sql title=Query
SELECT positiveModuloOrNull(5, 0)
response title=Response
\N | {"source_file": "arithmetic-functions.md"} | [
-0.009725306183099747,
0.057258348912000656,
-0.07956019043922424,
-0.012211126275360584,
0.005106484051793814,
-0.07239317148923874,
0.04605786129832268,
0.04506196454167366,
-0.03963252156972885,
-0.012263402342796326,
0.08029282093048096,
-0.05324758589267731,
0.08473976701498032,
0.002... |
49ca3b37-414a-4f61-97cc-648f1328d4e8 | description: 'Documentation for Type Conversion Functions'
sidebar_label: 'Type conversion'
slug: /sql-reference/functions/type-conversion-functions
title: 'Type Conversion Functions'
doc_type: 'reference'
Type conversion functions
Common issues with data conversion {#common-issues-with-data-conversion}
ClickHouse generally uses the
same behavior as C++ programs
.
to<type>
functions and
cast
behave differently in some cases, for example in case of
LowCardinality
:
cast
removes
LowCardinality
trait
to<type>
functions don't. The same with
Nullable
, this behaviour is not compatible with SQL standard, and it can be changed using
cast_keep_nullable
setting.
:::note
Be aware of potential data loss if values of a datatype are converted to a smaller datatype (for example from
Int64
to
Int32
) or between
incompatible datatypes (for example from
String
to
Int
). Make sure to check carefully if the result is as expected.
:::
Example:
```sql
SELECT
toTypeName(toLowCardinality('') AS val) AS source_type,
toTypeName(toString(val)) AS to_type_result_type,
toTypeName(CAST(val, 'String')) AS cast_result_type
ββsource_typeβββββββββββββ¬βto_type_result_typeβββββ¬βcast_result_typeββ
β LowCardinality(String) β LowCardinality(String) β String β
ββββββββββββββββββββββββββ΄βββββββββββββββββββββββββ΄βββββββββββββββββββ
SELECT
toTypeName(toNullable('') AS val) AS source_type,
toTypeName(toString(val)) AS to_type_result_type,
toTypeName(CAST(val, 'String')) AS cast_result_type
ββsource_typeβββββββ¬βto_type_result_typeββ¬βcast_result_typeββ
β Nullable(String) β Nullable(String) β String β
ββββββββββββββββββββ΄ββββββββββββββββββββββ΄βββββββββββββββββββ
SELECT
toTypeName(toNullable('') AS val) AS source_type,
toTypeName(toString(val)) AS to_type_result_type,
toTypeName(CAST(val, 'String')) AS cast_result_type
SETTINGS cast_keep_nullable = 1
ββsource_typeβββββββ¬βto_type_result_typeββ¬βcast_result_typeββ
β Nullable(String) β Nullable(String) β Nullable(String) β
ββββββββββββββββββββ΄ββββββββββββββββββββββ΄βββββββββββββββββββ
```
Notes on
toString
functions {#to-string-functions}
The
toString
family of functions allows for converting between numbers, strings (but not fixed strings), dates, and dates with times.
All of these functions accept one argument.
When converting to or from a string, the value is formatted or parsed using the same rules as for the TabSeparated format (and almost all other text formats). If the string can't be parsed, an exception is thrown and the request is canceled.
When converting dates to numbers or vice versa, the date corresponds to the number of days since the beginning of the Unix epoch.
When converting dates with times to numbers or vice versa, the date with time corresponds to the number of seconds since the beginning of the Unix epoch. | {"source_file": "type-conversion-functions.md"} | [
0.04497753083705902,
-0.006253688130527735,
-0.027816446498036385,
0.06911084055900574,
-0.08946242928504944,
-0.0043761092238128185,
0.0826980397105217,
0.017930282279849052,
-0.1367632895708084,
-0.03195952624082565,
0.01437892485409975,
-0.08943168818950653,
0.026635320857167244,
-0.080... |
bfd33c3c-70ae-4492-b28c-155cdb7f1cc6 | When converting dates with times to numbers or vice versa, the date with time corresponds to the number of seconds since the beginning of the Unix epoch.
The
toString
function of the
DateTime
argument can take a second String argument containing the name of the time zone, for example:
Europe/Amsterdam
. In this case, the time is formatted according to the specified time zone.
Notes on
toDate
/
toDateTime
functions {#to-date-and-date-time-functions}
The date and date-with-time formats for the
toDate
/
toDateTime
functions are defined as follows:
response
YYYY-MM-DD
YYYY-MM-DD hh:mm:ss
As an exception, if converting from UInt32, Int32, UInt64, or Int64 numeric types to Date, and if the number is greater than or equal to 65536, the number is interpreted as a Unix timestamp (and not as the number of days) and is rounded to the date.
This allows support for the common occurrence of writing
toDate(unix_timestamp)
, which otherwise would be an error and would require writing the more cumbersome
toDate(toDateTime(unix_timestamp))
.
Conversion between a date and a date with time is performed the natural way: by adding a null time or dropping the time.
Conversion between numeric types uses the same rules as assignments between different numeric types in C++.
Example
Query:
sql
SELECT
now() AS ts,
time_zone,
toString(ts, time_zone) AS str_tz_datetime
FROM system.time_zones
WHERE time_zone LIKE 'Europe%'
LIMIT 10
Result:
response
βββββββββββββββββββtsββ¬βtime_zoneββββββββββ¬βstr_tz_datetimeββββββ
β 2023-09-08 19:14:59 β Europe/Amsterdam β 2023-09-08 21:14:59 β
β 2023-09-08 19:14:59 β Europe/Andorra β 2023-09-08 21:14:59 β
β 2023-09-08 19:14:59 β Europe/Astrakhan β 2023-09-08 23:14:59 β
β 2023-09-08 19:14:59 β Europe/Athens β 2023-09-08 22:14:59 β
β 2023-09-08 19:14:59 β Europe/Belfast β 2023-09-08 20:14:59 β
β 2023-09-08 19:14:59 β Europe/Belgrade β 2023-09-08 21:14:59 β
β 2023-09-08 19:14:59 β Europe/Berlin β 2023-09-08 21:14:59 β
β 2023-09-08 19:14:59 β Europe/Bratislava β 2023-09-08 21:14:59 β
β 2023-09-08 19:14:59 β Europe/Brussels β 2023-09-08 21:14:59 β
β 2023-09-08 19:14:59 β Europe/Bucharest β 2023-09-08 22:14:59 β
βββββββββββββββββββββββ΄ββββββββββββββββββββ΄ββββββββββββββββββββββ
Also see the
toUnixTimestamp
function.
toBool {#tobool}
Converts an input value to a value of type
Bool
. Throws an exception in case of an error.
Syntax
sql
toBool(expr)
Arguments
expr
β Expression returning a number or a string.
Expression
.
Supported arguments:
- Values of type (U)Int8/16/32/64/128/256.
- Values of type Float32/64.
- Strings
true
or
false
(case-insensitive).
Returned value
Returns
true
or
false
based on evaluation of the argument.
Bool
.
Example
Query:
sql
SELECT
toBool(toUInt8(1)),
toBool(toInt8(-1)),
toBool(toFloat32(1.01)),
toBool('true'),
toBool('false'),
toBool('FALSE')
FORMAT Vertical
Result: | {"source_file": "type-conversion-functions.md"} | [
0.00045755563769489527,
0.0476207435131073,
-0.01703335903584957,
-0.0177101269364357,
0.01914013922214508,
-0.04019445925951004,
-0.05510954558849335,
0.08655595034360886,
0.02136569283902645,
-0.015579218044877052,
-0.04344185069203377,
-0.09285084158182144,
-0.022663123905658722,
-0.000... |
bf71629a-2cd7-421d-ad80-25763c11dd7c | Example
Query:
sql
SELECT
toBool(toUInt8(1)),
toBool(toInt8(-1)),
toBool(toFloat32(1.01)),
toBool('true'),
toBool('false'),
toBool('FALSE')
FORMAT Vertical
Result:
response
toBool(toUInt8(1)): true
toBool(toInt8(-1)): true
toBool(toFloat32(1.01)): true
toBool('true'): true
toBool('false'): false
toBool('FALSE'): false
toInt8 {#toint8}
Converts an input value to a value of type
Int8
. Throws an exception in case of an error.
Syntax
sql
toInt8(expr)
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
.
Supported arguments:
- Values or string representations of type (U)Int8/16/32/64/128/256.
- Values of type Float32/64.
Unsupported arguments:
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toInt8('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
Int8
, overflow or underflow of the result occurs.
This is not considered an error.
For example:
SELECT toInt8(128) == -128;
.
:::
Returned value
8-bit integer value.
Int8
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toInt8(-8),
toInt8(-8.8),
toInt8('-8')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toInt8(-8): -8
toInt8(-8.8): -8
toInt8('-8'): -8
See also
toInt8OrZero
.
toInt8OrNull
.
toInt8OrDefault
.
toInt8OrZero {#toint8orzero}
Like
toInt8
, this function converts an input value to a value of type
Int8
but returns
0
in case of an error.
Syntax
sql
toInt8OrZero(x)
Arguments
x
β A String representation of a number.
String
.
Supported arguments:
- String representations of (U)Int8/16/32/128/256.
Unsupported arguments (return
0
):
- String representations of ordinary Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toInt8OrZero('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
Int8
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
8-bit integer value if successful, otherwise
0
.
Int8
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toInt8OrZero('-8'),
toInt8OrZero('abc')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toInt8OrZero('-8'): -8
toInt8OrZero('abc'): 0
See also
toInt8
.
toInt8OrNull
.
toInt8OrDefault
.
toInt8OrNull {#toInt8OrNull}
Like
toInt8
, this function converts an input value to a value of type
Int8
but returns
NULL
in case of an error.
Syntax
sql
toInt8OrNull(x)
Arguments
x
β A String representation of a number.
String
. | {"source_file": "type-conversion-functions.md"} | [
-0.01564730331301689,
-0.026482075452804565,
-0.05949321389198303,
0.07595085352659225,
-0.05717385187745094,
0.029766149818897247,
0.09620429575443268,
0.07659199088811874,
-0.03159540891647339,
-0.02449210360646248,
-0.06152556464076042,
-0.06885484606027603,
0.06994912773370743,
-0.0065... |
3c658b50-8de0-4a12-aba7-046b1a6d506a | Syntax
sql
toInt8OrNull(x)
Arguments
x
β A String representation of a number.
String
.
Supported arguments:
- String representations of (U)Int8/16/32/128/256.
Unsupported arguments (return
\N
)
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toInt8OrNull('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
Int8
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
8-bit integer value if successful, otherwise
NULL
.
Int8
/
NULL
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toInt8OrNull('-8'),
toInt8OrNull('abc')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toInt8OrNull('-8'): -8
toInt8OrNull('abc'): α΄Ία΅α΄Έα΄Έ
See also
toInt8
.
toInt8OrZero
.
toInt8OrDefault
.
toInt8OrDefault {#toint8ordefault}
Like
toInt8
, this function converts an input value to a value of type
Int8
but returns the default value in case of an error.
If no
default
value is passed then
0
is returned in case of an error.
Syntax
sql
toInt8OrDefault(expr[, default])
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
/
String
.
default
(optional) β The default value to return if parsing to type
Int8
is unsuccessful.
Int8
.
Supported arguments:
- Values or string representations of type (U)Int8/16/32/64/128/256.
- Values of type Float32/64.
Arguments for which the default value is returned:
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toInt8OrDefault('0xc0fe', CAST('-1', 'Int8'));
.
:::note
If the input value cannot be represented within the bounds of
Int8
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
8-bit integer value if successful, otherwise returns the default value if passed or
0
if not.
Int8
.
:::note
- The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
- The default value type should be the same as the cast type.
:::
Example
Query:
sql
SELECT
toInt8OrDefault('-8', CAST('-1', 'Int8')),
toInt8OrDefault('abc', CAST('-1', 'Int8'))
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toInt8OrDefault('-8', CAST('-1', 'Int8')): -8
toInt8OrDefault('abc', CAST('-1', 'Int8')): -1
See also
toInt8
.
toInt8OrZero
.
toInt8OrNull
.
toInt16 {#toint16}
Converts an input value to a value of type
Int16
. Throws an exception in case of an error.
Syntax
sql
toInt16(expr)
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
. | {"source_file": "type-conversion-functions.md"} | [
0.0285625159740448,
0.03230224922299385,
-0.0438997820019722,
0.018187621608376503,
-0.07505126297473907,
0.00010187344742007554,
0.057640593498945236,
0.07535108923912048,
-0.08754542469978333,
-0.010993266478180885,
-0.00940866582095623,
-0.09069278091192245,
0.07005233317613602,
-0.0088... |
949c6d86-aa58-4bee-a841-0c3a36cc7dcd | Syntax
sql
toInt16(expr)
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
.
Supported arguments:
- Values or string representations of type (U)Int8/16/32/64/128/256.
- Values of type Float32/64.
Unsupported arguments:
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toInt16('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
Int16
, overflow or underflow of the result occurs.
This is not considered an error.
For example:
SELECT toInt16(32768) == -32768;
.
:::
Returned value
16-bit integer value.
Int16
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toInt16(-16),
toInt16(-16.16),
toInt16('-16')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toInt16(-16): -16
toInt16(-16.16): -16
toInt16('-16'): -16
See also
toInt16OrZero
.
toInt16OrNull
.
toInt16OrDefault
.
toInt16OrZero {#toint16orzero}
Like
toInt16
, this function converts an input value to a value of type
Int16
but returns
0
in case of an error.
Syntax
sql
toInt16OrZero(x)
Arguments
x
β A String representation of a number.
String
.
Supported arguments:
- String representations of (U)Int8/16/32/128/256.
Unsupported arguments (return
0
):
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toInt16OrZero('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
Int16
, overflow or underflow of the result occurs.
This is not considered as an error.
:::
Returned value
16-bit integer value if successful, otherwise
0
.
Int16
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toInt16OrZero('-16'),
toInt16OrZero('abc')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toInt16OrZero('-16'): -16
toInt16OrZero('abc'): 0
See also
toInt16
.
toInt16OrNull
.
toInt16OrDefault
.
toInt16OrNull {#toint16ornull}
Like
toInt16
, this function converts an input value to a value of type
Int16
but returns
NULL
in case of an error.
Syntax
sql
toInt16OrNull(x)
Arguments
x
β A String representation of a number.
String
.
Supported arguments:
- String representations of (U)Int8/16/32/128/256.
Unsupported arguments (return
\N
)
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toInt16OrNull('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
Int16
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value | {"source_file": "type-conversion-functions.md"} | [
0.046614937484264374,
0.027503130957484245,
-0.05826215818524361,
-0.016479339450597763,
-0.028096502646803856,
-0.06969369202852249,
0.05517103895545006,
0.0633556917309761,
-0.08582834154367447,
-0.014168414287269115,
-0.0038642992731183767,
-0.082957923412323,
0.04198194667696953,
0.037... |
fb15e576-21c4-44cc-8705-2d18692c8582 | :::note
If the input value cannot be represented within the bounds of
Int16
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
16-bit integer value if successful, otherwise
NULL
.
Int16
/
NULL
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toInt16OrNull('-16'),
toInt16OrNull('abc')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toInt16OrNull('-16'): -16
toInt16OrNull('abc'): α΄Ία΅α΄Έα΄Έ
See also
toInt16
.
toInt16OrZero
.
toInt16OrDefault
.
toInt16OrDefault {#toint16ordefault}
Like
toInt16
, this function converts an input value to a value of type
Int16
but returns the default value in case of an error.
If no
default
value is passed then
0
is returned in case of an error.
Syntax
sql
toInt16OrDefault(expr[, default])
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
/
String
.
default
(optional) β The default value to return if parsing to type
Int16
is unsuccessful.
Int16
.
Supported arguments:
- Values or string representations of type (U)Int8/16/32/64/128/256.
- Values of type Float32/64.
Arguments for which the default value is returned:
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toInt16OrDefault('0xc0fe', CAST('-1', 'Int16'));
.
:::note
If the input value cannot be represented within the bounds of
Int16
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
16-bit integer value if successful, otherwise returns the default value if passed or
0
if not.
Int16
.
:::note
- The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
- The default value type should be the same as the cast type.
:::
Example
Query:
sql
SELECT
toInt16OrDefault('-16', CAST('-1', 'Int16')),
toInt16OrDefault('abc', CAST('-1', 'Int16'))
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toInt16OrDefault('-16', CAST('-1', 'Int16')): -16
toInt16OrDefault('abc', CAST('-1', 'Int16')): -1
See also
toInt16
.
toInt16OrZero
.
toInt16OrNull
.
toInt32 {#toint32}
Converts an input value to a value of type
Int32
. Throws an exception in case of an error.
Syntax
sql
toInt32(expr)
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
.
Supported arguments:
- Values or string representations of type (U)Int8/16/32/64/128/256.
- Values of type Float32/64.
Unsupported arguments:
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toInt32('0xc0fe');
. | {"source_file": "type-conversion-functions.md"} | [
0.03897770121693611,
0.06621483713388443,
-0.052571654319763184,
-0.003557324642315507,
-0.07293956726789474,
-0.014611279591917992,
0.04977947473526001,
0.07331597059965134,
-0.07292044907808304,
-0.0018449350027367473,
0.02148464135825634,
-0.06091995909810066,
0.05504060164093971,
0.006... |
c478c6fc-2128-4dce-a73b-768e4f4010a2 | Unsupported arguments:
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toInt32('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
Int32
, the result over or under flows.
This is not considered an error.
For example:
SELECT toInt32(2147483648) == -2147483648;
:::
Returned value
32-bit integer value.
Int32
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toInt32(-32),
toInt32(-32.32),
toInt32('-32')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toInt32(-32): -32
toInt32(-32.32): -32
toInt32('-32'): -32
See also
toInt32OrZero
.
toInt32OrNull
.
toInt32OrDefault
.
toInt32OrZero {#toint32orzero}
Like
toInt32
, this function converts an input value to a value of type
Int32
but returns
0
in case of an error.
Syntax
sql
toInt32OrZero(x)
Arguments
x
β A String representation of a number.
String
.
Supported arguments:
- String representations of (U)Int8/16/32/128/256.
Unsupported arguments (return
0
):
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toInt32OrZero('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
Int32
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
32-bit integer value if successful, otherwise
0
.
Int32
:::note
The function uses
rounding towards zero
, meaning it truncate fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toInt32OrZero('-32'),
toInt32OrZero('abc')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toInt32OrZero('-32'): -32
toInt32OrZero('abc'): 0
See also
toInt32
.
toInt32OrNull
.
toInt32OrDefault
.
toInt32OrNull {#toint32ornull}
Like
toInt32
, this function converts an input value to a value of type
Int32
but returns
NULL
in case of an error.
Syntax
sql
toInt32OrNull(x)
Arguments
x
β A String representation of a number.
String
.
Supported arguments:
- String representations of (U)Int8/16/32/128/256.
Unsupported arguments (return
\N
)
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toInt32OrNull('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
Int32
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
32-bit integer value if successful, otherwise
NULL
.
Int32
/
NULL
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toInt32OrNull('-32'),
toInt32OrNull('abc')
FORMAT Vertical;
Result: | {"source_file": "type-conversion-functions.md"} | [
0.0007340150186792016,
-0.014095989987254143,
-0.1053013727068901,
-0.0037413707468658686,
-0.04732148349285126,
-0.053976964205503464,
0.049947477877140045,
0.05012315884232521,
-0.043786752969026566,
0.006571974139660597,
-0.03948104381561279,
-0.10849489271640778,
0.008981465362012386,
... |
948414a9-be47-4d04-99f5-57916f3b9f10 | Example
Query:
sql
SELECT
toInt32OrNull('-32'),
toInt32OrNull('abc')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toInt32OrNull('-32'): -32
toInt32OrNull('abc'): α΄Ία΅α΄Έα΄Έ
See also
toInt32
.
toInt32OrZero
.
toInt32OrDefault
.
toInt32OrDefault {#toint32ordefault}
Like
toInt32
, this function converts an input value to a value of type
Int32
but returns the default value in case of an error.
If no
default
value is passed then
0
is returned in case of an error.
Syntax
sql
toInt32OrDefault(expr[, default])
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
/
String
.
default
(optional) β The default value to return if parsing to type
Int32
is unsuccessful.
Int32
.
Supported arguments:
- Values or string representations of type (U)Int8/16/32/64/128/256.
- Values of type Float32/64.
Arguments for which the default value is returned:
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toInt32OrDefault('0xc0fe', CAST('-1', 'Int32'));
.
:::note
If the input value cannot be represented within the bounds of
Int32
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
32-bit integer value if successful, otherwise returns the default value if passed or
0
if not.
Int32
.
:::note
- The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
- The default value type should be the same as the cast type.
:::
Example
Query:
sql
SELECT
toInt32OrDefault('-32', CAST('-1', 'Int32')),
toInt32OrDefault('abc', CAST('-1', 'Int32'))
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toInt32OrDefault('-32', CAST('-1', 'Int32')): -32
toInt32OrDefault('abc', CAST('-1', 'Int32')): -1
See also
toInt32
.
toInt32OrZero
.
toInt32OrNull
.
toInt64 {#toint64}
Converts an input value to a value of type
Int64
. Throws an exception in case of an error.
Syntax
sql
toInt64(expr)
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
.
Supported arguments:
- Values or string representations of type (U)Int8/16/32/64/128/256.
- Values of type Float32/64.
Unsupported types:
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toInt64('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
Int64
, the result over or under flows.
This is not considered an error.
For example:
SELECT toInt64(9223372036854775808) == -9223372036854775808;
:::
Returned value
64-bit integer value.
Int64
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query: | {"source_file": "type-conversion-functions.md"} | [
0.040355414152145386,
-0.009334113448858261,
-0.05855618417263031,
0.05837629735469818,
-0.07015995681285858,
-0.004908485803753138,
0.06289724260568619,
0.08049783110618591,
-0.03745449706912041,
0.0025926704984158278,
-0.030533812940120697,
-0.09447772800922394,
0.04397681728005409,
0.00... |
39d19c98-39e0-44cf-b624-315c2673291a | :::
Returned value
64-bit integer value.
Int64
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toInt64(-64),
toInt64(-64.64),
toInt64('-64')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toInt64(-64): -64
toInt64(-64.64): -64
toInt64('-64'): -64
See also
toInt64OrZero
.
toInt64OrNull
.
toInt64OrDefault
.
toInt64OrZero {#toint64orzero}
Like
toInt64
, this function converts an input value to a value of type
Int64
but returns
0
in case of an error.
Syntax
sql
toInt64OrZero(x)
Arguments
x
β A String representation of a number.
String
.
Supported arguments:
- String representations of (U)Int8/16/32/128/256.
Unsupported arguments (return
0
):
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toInt64OrZero('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
Int64
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
64-bit integer value if successful, otherwise
0
.
Int64
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toInt64OrZero('-64'),
toInt64OrZero('abc')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toInt64OrZero('-64'): -64
toInt64OrZero('abc'): 0
See also
toInt64
.
toInt64OrNull
.
toInt64OrDefault
.
toInt64OrNull {#toint64ornull}
Like
toInt64
, this function converts an input value to a value of type
Int64
but returns
NULL
in case of an error.
Syntax
sql
toInt64OrNull(x)
Arguments
x
β A String representation of a number.
Expression
/
String
.
Supported arguments:
- String representations of (U)Int8/16/32/128/256.
Unsupported arguments (return
\N
)
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toInt64OrNull('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
Int64
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
64-bit integer value if successful, otherwise
NULL
.
Int64
/
NULL
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toInt64OrNull('-64'),
toInt64OrNull('abc')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toInt64OrNull('-64'): -64
toInt64OrNull('abc'): α΄Ία΅α΄Έα΄Έ
See also
toInt64
.
toInt64OrZero
.
toInt64OrDefault
.
toInt64OrDefault {#toint64ordefault} | {"source_file": "type-conversion-functions.md"} | [
0.06505885720252991,
0.041396427899599075,
-0.07832472026348114,
0.04575009271502495,
-0.05093134939670563,
-0.019949719309806824,
0.036864351481199265,
0.04585231840610504,
-0.05294003710150719,
0.0025831768289208412,
-0.031730785965919495,
-0.04220321774482727,
0.012308124452829361,
-0.0... |
071a5195-1fdf-4586-a459-b9838a3b1f77 | Result:
response
Row 1:
ββββββ
toInt64OrNull('-64'): -64
toInt64OrNull('abc'): α΄Ία΅α΄Έα΄Έ
See also
toInt64
.
toInt64OrZero
.
toInt64OrDefault
.
toInt64OrDefault {#toint64ordefault}
Like
toInt64
, this function converts an input value to a value of type
Int64
but returns the default value in case of an error.
If no
default
value is passed then
0
is returned in case of an error.
Syntax
sql
toInt64OrDefault(expr[, default])
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
/
String
.
default
(optional) β The default value to return if parsing to type
Int64
is unsuccessful.
Int64
.
Supported arguments:
- Values or string representations of type (U)Int8/16/32/64/128/256.
- Values of type Float32/64.
Arguments for which the default value is returned:
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toInt64OrDefault('0xc0fe', CAST('-1', 'Int64'));
.
:::note
If the input value cannot be represented within the bounds of
Int64
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
64-bit integer value if successful, otherwise returns the default value if passed or
0
if not.
Int64
.
:::note
- The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
- The default value type should be the same as the cast type.
:::
Example
Query:
sql
SELECT
toInt64OrDefault('-64', CAST('-1', 'Int64')),
toInt64OrDefault('abc', CAST('-1', 'Int64'))
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toInt64OrDefault('-64', CAST('-1', 'Int64')): -64
toInt64OrDefault('abc', CAST('-1', 'Int64')): -1
See also
toInt64
.
toInt64OrZero
.
toInt64OrNull
.
toInt128 {#toint128}
Converts an input value to a value of type
Int128
. Throws an exception in case of an error.
Syntax
sql
toInt128(expr)
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
.
Supported arguments:
- Values or string representations of type (U)Int8/16/32/64/128/256.
- Values of type Float32/64.
Unsupported arguments:
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toInt128('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
Int128
, the result over or under flows.
This is not considered an error.
:::
Returned value
128-bit integer value.
Int128
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toInt128(-128),
toInt128(-128.8),
toInt128('-128')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toInt128(-128): -128
toInt128(-128.8): -128
toInt128('-128'): -128
See also
toInt128OrZero
. | {"source_file": "type-conversion-functions.md"} | [
0.052871935069561005,
0.030789609998464584,
-0.0928928330540657,
0.03505496680736542,
-0.06514143943786621,
0.008783403784036636,
0.04528774321079254,
0.05352010950446129,
-0.07159075140953064,
0.017666976898908615,
0.012872295454144478,
-0.0771256759762764,
0.03219906985759735,
0.00157530... |
1a173804-bb54-4ee7-bd71-b541dd09e221 | Result:
response
Row 1:
ββββββ
toInt128(-128): -128
toInt128(-128.8): -128
toInt128('-128'): -128
See also
toInt128OrZero
.
toInt128OrNull
.
toInt128OrDefault
.
toInt128OrZero {#toint128orzero}
Like
toInt128
, this function converts an input value to a value of type
Int128
but returns
0
in case of an error.
Syntax
sql
toInt128OrZero(expr)
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
/
String
.
Supported arguments:
- String representations of (U)Int8/16/32/128/256.
Unsupported arguments (return
0
):
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toInt128OrZero('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
Int128
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
128-bit integer value if successful, otherwise
0
.
Int128
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toInt128OrZero('-128'),
toInt128OrZero('abc')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toInt128OrZero('-128'): -128
toInt128OrZero('abc'): 0
See also
toInt128
.
toInt128OrNull
.
toInt128OrDefault
.
toInt128OrNull {#toint128ornull}
Like
toInt128
, this function converts an input value to a value of type
Int128
but returns
NULL
in case of an error.
Syntax
sql
toInt128OrNull(x)
Arguments
x
β A String representation of a number.
Expression
/
String
.
Supported arguments:
- String representations of (U)Int8/16/32/128/256.
Unsupported arguments (return
\N
)
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toInt128OrNull('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
Int128
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
128-bit integer value if successful, otherwise
NULL
.
Int128
/
NULL
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toInt128OrNull('-128'),
toInt128OrNull('abc')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toInt128OrNull('-128'): -128
toInt128OrNull('abc'): α΄Ία΅α΄Έα΄Έ
See also
toInt128
.
toInt128OrZero
.
toInt128OrDefault
.
toInt128OrDefault {#toint128ordefault}
Like
toInt128
, this function converts an input value to a value of type
Int128
but returns the default value in case of an error.
If no
default
value is passed then
0
is returned in case of an error.
Syntax
sql
toInt128OrDefault(expr[, default])
Arguments | {"source_file": "type-conversion-functions.md"} | [
0.016352172940969467,
0.051780954003334045,
-0.08285735547542572,
0.03729378432035446,
-0.046238385140895844,
-0.009746565483510494,
0.07008258998394012,
0.07644157856702805,
-0.0962265357375145,
-0.014751981012523174,
-0.040824033319950104,
-0.0739031657576561,
0.04313013702630997,
-0.024... |
0bf2e38a-de36-49b0-a704-b9409226e5af | Syntax
sql
toInt128OrDefault(expr[, default])
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
/
String
.
default
(optional) β The default value to return if parsing to type
Int128
is unsuccessful.
Int128
.
Supported arguments:
- (U)Int8/16/32/64/128/256.
- Float32/64.
- String representations of (U)Int8/16/32/128/256.
Arguments for which the default value is returned:
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toInt128OrDefault('0xc0fe', CAST('-1', 'Int128'));
.
:::note
If the input value cannot be represented within the bounds of
Int128
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
128-bit integer value if successful, otherwise returns the default value if passed or
0
if not.
Int128
.
:::note
- The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
- The default value type should be the same as the cast type.
:::
Example
Query:
sql
SELECT
toInt128OrDefault('-128', CAST('-1', 'Int128')),
toInt128OrDefault('abc', CAST('-1', 'Int128'))
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toInt128OrDefault('-128', CAST('-1', 'Int128')): -128
toInt128OrDefault('abc', CAST('-1', 'Int128')): -1
See also
toInt128
.
toInt128OrZero
.
toInt128OrNull
.
toInt256 {#toint256}
Converts an input value to a value of type
Int256
. Throws an exception in case of an error.
Syntax
sql
toInt256(expr)
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
.
Supported arguments:
- Values or string representations of type (U)Int8/16/32/64/128/256.
- Values of type Float32/64.
Unsupported arguments:
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toInt256('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
Int256
, the result over or under flows.
This is not considered an error.
:::
Returned value
256-bit integer value.
Int256
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toInt256(-256),
toInt256(-256.256),
toInt256('-256')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toInt256(-256): -256
toInt256(-256.256): -256
toInt256('-256'): -256
See also
toInt256OrZero
.
toInt256OrNull
.
toInt256OrDefault
.
toInt256OrZero {#toint256orzero}
Like
toInt256
, this function converts an input value to a value of type
Int256
but returns
0
in case of an error.
Syntax
sql
toInt256OrZero(x)
Arguments
x
β A String representation of a number.
String
.
Supported arguments:
- String representations of (U)Int8/16/32/128/256. | {"source_file": "type-conversion-functions.md"} | [
0.03523910790681839,
0.00956770684570074,
-0.07221923023462296,
-0.018509946763515472,
-0.044528085738420486,
-0.042357437312603,
0.07843869179487228,
0.09093637019395828,
-0.08471307158470154,
-0.02387179248034954,
-0.02825530432164669,
-0.0542563758790493,
-0.009079999290406704,
0.034738... |
29ba66ce-51a6-4ac0-aefe-4a880135f9a0 | Syntax
sql
toInt256OrZero(x)
Arguments
x
β A String representation of a number.
String
.
Supported arguments:
- String representations of (U)Int8/16/32/128/256.
Unsupported arguments (return
0
):
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toInt256OrZero('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
Int256
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
256-bit integer value if successful, otherwise
0
.
Int256
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toInt256OrZero('-256'),
toInt256OrZero('abc')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toInt256OrZero('-256'): -256
toInt256OrZero('abc'): 0
See also
toInt256
.
toInt256OrNull
.
toInt256OrDefault
.
toInt256OrNull {#toint256ornull}
Like
toInt256
, this function converts an input value to a value of type
Int256
but returns
NULL
in case of an error.
Syntax
sql
toInt256OrNull(x)
Arguments
x
β A String representation of a number.
String
.
Supported arguments:
- String representations of (U)Int8/16/32/128/256.
Unsupported arguments (return
\N
)
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toInt256OrNull('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
Int256
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
256-bit integer value if successful, otherwise
NULL
.
Int256
/
NULL
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toInt256OrNull('-256'),
toInt256OrNull('abc')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toInt256OrNull('-256'): -256
toInt256OrNull('abc'): α΄Ία΅α΄Έα΄Έ
See also
toInt256
.
toInt256OrZero
.
toInt256OrDefault
.
toInt256OrDefault {#toint256ordefault}
Like
toInt256
, this function converts an input value to a value of type
Int256
but returns the default value in case of an error.
If no
default
value is passed then
0
is returned in case of an error.
Syntax
sql
toInt256OrDefault(expr[, default])
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
/
String
.
default
(optional) β The default value to return if parsing to type
Int256
is unsuccessful.
Int256
.
Supported arguments:
- Values or string representations of type (U)Int8/16/32/64/128/256.
- Values of type Float32/64.
Arguments for which the default value is returned:
- String representations of Float32/64 values, including
NaN
and
Inf | {"source_file": "type-conversion-functions.md"} | [
0.027844293043017387,
0.0024955642875283957,
-0.0886588767170906,
0.0012895484687760472,
-0.04050426930189133,
-0.04436272010207176,
0.08371832966804504,
0.025289159268140793,
-0.07777788490056992,
0.00837738811969757,
-0.019730709493160248,
-0.085232213139534,
0.05089106783270836,
-0.0290... |
fe2f82c7-7bd0-4203-b876-1c23b8786e6e | Arguments for which the default value is returned:
- String representations of Float32/64 values, including
NaN
and
Inf
- String representations of binary and hexadecimal values, e.g.
SELECT toInt256OrDefault('0xc0fe', CAST('-1', 'Int256'));
:::note
If the input value cannot be represented within the bounds of
Int256
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
256-bit integer value if successful, otherwise returns the default value if passed or
0
if not.
Int256
.
:::note
- The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
- The default value type should be the same as the cast type.
:::
Example
Query:
sql
SELECT
toInt256OrDefault('-256', CAST('-1', 'Int256')),
toInt256OrDefault('abc', CAST('-1', 'Int256'))
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toInt256OrDefault('-256', CAST('-1', 'Int256')): -256
toInt256OrDefault('abc', CAST('-1', 'Int256')): -1
See also
toInt256
.
toInt256OrZero
.
toInt256OrNull
.
toUInt8 {#touint8}
Converts an input value to a value of type
UInt8
. Throws an exception in case of an error.
Syntax
sql
toUInt8(expr)
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
.
Supported arguments:
- Values or string representations of type (U)Int8/16/32/64/128/256.
- Values of type Float32/64.
Unsupported arguments:
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toUInt8('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
UInt8
, overflow or underflow of the result occurs.
This is not considered an error.
For example:
SELECT toUInt8(256) == 0;
.
:::
Returned value
8-bit unsigned integer value.
UInt8
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toUInt8(8),
toUInt8(8.8),
toUInt8('8')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toUInt8(8): 8
toUInt8(8.8): 8
toUInt8('8'): 8
See also
toUInt8OrZero
.
toUInt8OrNull
.
toUInt8OrDefault
.
toUInt8OrZero {#touint8orzero}
Like
toUInt8
, this function converts an input value to a value of type
UInt8
but returns
0
in case of an error.
Syntax
sql
toUInt8OrZero(x)
Arguments
x
β A String representation of a number.
String
.
Supported arguments:
- String representations of (U)Int8/16/32/128/256.
Unsupported arguments (return
0
):
- String representations of ordinary Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toUInt8OrZero('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
UInt8
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value | {"source_file": "type-conversion-functions.md"} | [
0.04442860558629036,
-0.016680607572197914,
-0.09892929345369339,
-0.009501135908067226,
-0.07967661321163177,
-0.04503362998366356,
0.09101378917694092,
0.052930958569049835,
-0.08067851513624191,
0.023179545998573303,
-0.013949023559689522,
-0.06813111901283264,
0.009120278060436249,
-0.... |
c48347c0-2206-43e1-8b3d-47386bdddfca | :::note
If the input value cannot be represented within the bounds of
UInt8
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
8-bit unsigned integer value if successful, otherwise
0
.
UInt8
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toUInt8OrZero('-8'),
toUInt8OrZero('abc')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toUInt8OrZero('-8'): 0
toUInt8OrZero('abc'): 0
See also
toUInt8
.
toUInt8OrNull
.
toUInt8OrDefault
.
toUInt8OrNull {#touint8ornull}
Like
toUInt8
, this function converts an input value to a value of type
UInt8
but returns
NULL
in case of an error.
Syntax
sql
toUInt8OrNull(x)
Arguments
x
β A String representation of a number.
String
.
Supported arguments:
- String representations of (U)Int8/16/32/128/256.
Unsupported arguments (return
\N
)
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toUInt8OrNull('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
UInt8
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
8-bit unsigned integer value if successful, otherwise
NULL
.
UInt8
/
NULL
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toUInt8OrNull('8'),
toUInt8OrNull('abc')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toUInt8OrNull('8'): 8
toUInt8OrNull('abc'): α΄Ία΅α΄Έα΄Έ
See also
toUInt8
.
toUInt8OrZero
.
toUInt8OrDefault
.
toUInt8OrDefault {#touint8ordefault}
Like
toUInt8
, this function converts an input value to a value of type
UInt8
but returns the default value in case of an error.
If no
default
value is passed then
0
is returned in case of an error.
Syntax
sql
toUInt8OrDefault(expr[, default])
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
/
String
.
default
(optional) β The default value to return if parsing to type
UInt8
is unsuccessful.
UInt8
.
Supported arguments:
- Values or string representations of type (U)Int8/16/32/64/128/256.
- Values of type Float32/64.
Arguments for which the default value is returned:
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toUInt8OrDefault('0xc0fe', CAST('0', 'UInt8'));
.
:::note
If the input value cannot be represented within the bounds of
UInt8
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
8-bit unsigned integer value if successful, otherwise returns the default value if passed or
0
if not.
UInt8
. | {"source_file": "type-conversion-functions.md"} | [
-0.01912241242825985,
0.03664986789226532,
-0.06061168015003204,
0.02316254936158657,
-0.10080637037754059,
-0.0025859579909592867,
0.07097847759723663,
0.06910055130720139,
-0.03342859819531441,
-0.017517544329166412,
-0.004434060771018267,
-0.0388963483273983,
0.0581212192773819,
-0.0147... |
4215efc7-1a78-4818-98d7-4c27d9f230f8 | Returned value
8-bit unsigned integer value if successful, otherwise returns the default value if passed or
0
if not.
UInt8
.
:::note
- The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
- The default value type should be the same as the cast type.
:::
Example
Query:
sql
SELECT
toUInt8OrDefault('8', CAST('0', 'UInt8')),
toUInt8OrDefault('abc', CAST('0', 'UInt8'))
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toUInt8OrDefault('8', CAST('0', 'UInt8')): 8
toUInt8OrDefault('abc', CAST('0', 'UInt8')): 0
See also
toUInt8
.
toUInt8OrZero
.
toUInt8OrNull
.
toUInt16 {#touint16}
Converts an input value to a value of type
UInt16
. Throws an exception in case of an error.
Syntax
sql
toUInt16(expr)
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
.
Supported arguments:
- Values or string representations of type (U)Int8/16/32/64/128/256.
- Values of type Float32/64.
Unsupported arguments:
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toUInt16('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
UInt16
, overflow or underflow of the result occurs.
This is not considered an error.
For example:
SELECT toUInt16(65536) == 0;
.
:::
Returned value
16-bit unsigned integer value.
UInt16
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toUInt16(16),
toUInt16(16.16),
toUInt16('16')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toUInt16(16): 16
toUInt16(16.16): 16
toUInt16('16'): 16
See also
toUInt16OrZero
.
toUInt16OrNull
.
toUInt16OrDefault
.
toUInt16OrZero {#touint16orzero}
Like
toUInt16
, this function converts an input value to a value of type
UInt16
but returns
0
in case of an error.
Syntax
sql
toUInt16OrZero(x)
Arguments
x
β A String representation of a number.
String
.
Supported arguments:
- String representations of (U)Int8/16/32/128/256.
Unsupported arguments (return
0
):
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toUInt16OrZero('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
UInt16
, overflow or underflow of the result occurs.
This is not considered as an error.
:::
Returned value
16-bit unsigned integer value if successful, otherwise
0
.
UInt16
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toUInt16OrZero('16'),
toUInt16OrZero('abc')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toUInt16OrZero('16'): 16
toUInt16OrZero('abc'): 0
See also | {"source_file": "type-conversion-functions.md"} | [
0.015253057703375816,
0.032629068940877914,
-0.08383172005414963,
0.009728604927659035,
-0.13158273696899414,
-0.007909913547337055,
0.07492486387491226,
0.09245771914720535,
-0.02315385825932026,
-0.02004430815577507,
-0.0022208383306860924,
-0.05365375056862831,
-0.01315819751471281,
-0.... |
f01f4f79-eef8-437d-b999-bdef727b0fb0 | Example
Query:
sql
SELECT
toUInt16OrZero('16'),
toUInt16OrZero('abc')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toUInt16OrZero('16'): 16
toUInt16OrZero('abc'): 0
See also
toUInt16
.
toUInt16OrNull
.
toUInt16OrDefault
.
toUInt16OrNull {#touint16ornull}
Like
toUInt16
, this function converts an input value to a value of type
UInt16
but returns
NULL
in case of an error.
Syntax
sql
toUInt16OrNull(x)
Arguments
x
β A String representation of a number.
String
.
Supported arguments:
- String representations of (U)Int8/16/32/128/256.
Unsupported arguments (return
\N
)
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toUInt16OrNull('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
UInt16
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
16-bit unsigned integer value if successful, otherwise
NULL
.
UInt16
/
NULL
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toUInt16OrNull('16'),
toUInt16OrNull('abc')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toUInt16OrNull('16'): 16
toUInt16OrNull('abc'): α΄Ία΅α΄Έα΄Έ
See also
toUInt16
.
toUInt16OrZero
.
toUInt16OrDefault
.
toUInt16OrDefault {#touint16ordefault}
Like
toUInt16
, this function converts an input value to a value of type
UInt16
but returns the default value in case of an error.
If no
default
value is passed then
0
is returned in case of an error.
Syntax
sql
toUInt16OrDefault(expr[, default])
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
/
String
.
default
(optional) β The default value to return if parsing to type
UInt16
is unsuccessful.
UInt16
.
Supported arguments:
- Values or string representations of type (U)Int8/16/32/64/128/256.
- Values of type Float32/64.
Arguments for which the default value is returned:
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toUInt16OrDefault('0xc0fe', CAST('0', 'UInt16'));
.
:::note
If the input value cannot be represented within the bounds of
UInt16
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
16-bit unsigned integer value if successful, otherwise returns the default value if passed or
0
if not.
UInt16
.
:::note
- The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
- The default value type should be the same as the cast type.
:::
Example
Query:
sql
SELECT
toUInt16OrDefault('16', CAST('0', 'UInt16')),
toUInt16OrDefault('abc', CAST('0', 'UInt16'))
FORMAT Vertical;
Result: | {"source_file": "type-conversion-functions.md"} | [
0.053384002298116684,
0.01748235896229744,
-0.09798377007246017,
0.01685357093811035,
-0.10966838151216507,
-0.0033732561860233545,
0.058283913880586624,
0.04239233583211899,
-0.06911415606737137,
-0.010427599772810936,
0.014488954097032547,
-0.08981767296791077,
0.04340837150812149,
0.005... |
93a74413-a335-4b85-abbe-77ffe421a128 | Example
Query:
sql
SELECT
toUInt16OrDefault('16', CAST('0', 'UInt16')),
toUInt16OrDefault('abc', CAST('0', 'UInt16'))
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toUInt16OrDefault('16', CAST('0', 'UInt16')): 16
toUInt16OrDefault('abc', CAST('0', 'UInt16')): 0
See also
toUInt16
.
toUInt16OrZero
.
toUInt16OrNull
.
toUInt32 {#touint32}
Converts an input value to a value of type
UInt32
. Throws an exception in case of an error.
Syntax
sql
toUInt32(expr)
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
.
Supported arguments:
- Values or string representations of type (U)Int8/16/32/64/128/256.
- Values of type Float32/64.
Unsupported arguments:
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toUInt32('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
UInt32
, the result over or under flows.
This is not considered an error.
For example:
SELECT toUInt32(4294967296) == 0;
:::
Returned value
32-bit unsigned integer value.
UInt32
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toUInt32(32),
toUInt32(32.32),
toUInt32('32')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toUInt32(32): 32
toUInt32(32.32): 32
toUInt32('32'): 32
See also
toUInt32OrZero
.
toUInt32OrNull
.
toUInt32OrDefault
.
toUInt32OrZero {#touint32orzero}
Like
toUInt32
, this function converts an input value to a value of type
UInt32
but returns
0
in case of an error.
Syntax
sql
toUInt32OrZero(x)
Arguments
x
β A String representation of a number.
String
.
Supported arguments:
- String representations of (U)Int8/16/32/128/256.
Unsupported arguments (return
0
):
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toUInt32OrZero('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
UInt32
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
32-bit unsigned integer value if successful, otherwise
0
.
UInt32
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toUInt32OrZero('32'),
toUInt32OrZero('abc')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toUInt32OrZero('32'): 32
toUInt32OrZero('abc'): 0
See also
toUInt32
.
toUInt32OrNull
.
toUInt32OrDefault
.
toUInt32OrNull {#touint32ornull}
Like
toUInt32
, this function converts an input value to a value of type
UInt32
but returns
NULL
in case of an error.
Syntax
sql
toUInt32OrNull(x)
Arguments
x
β A String representation of a number.
String
. | {"source_file": "type-conversion-functions.md"} | [
0.019399870187044144,
-0.011828499846160412,
-0.10562089085578918,
0.017157401889562607,
-0.1086169108748436,
0.020581232383847237,
0.06891347467899323,
0.06724913418292999,
-0.02772006019949913,
-0.004467260558158159,
-0.03487896919250488,
-0.06088900938630104,
0.025428449735045433,
0.029... |
701fa006-b9bf-4961-afa1-f0008d1cce9a | Syntax
sql
toUInt32OrNull(x)
Arguments
x
β A String representation of a number.
String
.
Supported arguments:
- String representations of (U)Int8/16/32/128/256.
Unsupported arguments (return
\N
)
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toUInt32OrNull('0xc0fe');
.
:::note
If the input value cannot be represented within the bounds of
UInt32
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
32-bit unsigned integer value if successful, otherwise
NULL
.
UInt32
/
NULL
.
:::note
The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
:::
Example
Query:
sql
SELECT
toUInt32OrNull('32'),
toUInt32OrNull('abc')
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toUInt32OrNull('32'): 32
toUInt32OrNull('abc'): α΄Ία΅α΄Έα΄Έ
See also
toUInt32
.
toUInt32OrZero
.
toUInt32OrDefault
.
toUInt32OrDefault {#touint32ordefault}
Like
toUInt32
, this function converts an input value to a value of type
UInt32
but returns the default value in case of an error.
If no
default
value is passed then
0
is returned in case of an error.
Syntax
sql
toUInt32OrDefault(expr[, default])
Arguments
expr
β Expression returning a number or a string representation of a number.
Expression
/
String
.
default
(optional) β The default value to return if parsing to type
UInt32
is unsuccessful.
UInt32
.
Supported arguments:
- Values or string representations of type (U)Int8/16/32/64/128/256.
- Values of type Float32/64.
Arguments for which the default value is returned:
- String representations of Float32/64 values, including
NaN
and
Inf
.
- String representations of binary and hexadecimal values, e.g.
SELECT toUInt32OrDefault('0xc0fe', CAST('0', 'UInt32'));
.
:::note
If the input value cannot be represented within the bounds of
UInt32
, overflow or underflow of the result occurs.
This is not considered an error.
:::
Returned value
32-bit unsigned integer value if successful, otherwise returns the default value if passed or
0
if not.
UInt32
.
:::note
- The function uses
rounding towards zero
, meaning it truncates fractional digits of numbers.
- The default value type should be the same as the cast type.
:::
Example
Query:
sql
SELECT
toUInt32OrDefault('32', CAST('0', 'UInt32')),
toUInt32OrDefault('abc', CAST('0', 'UInt32'))
FORMAT Vertical;
Result:
response
Row 1:
ββββββ
toUInt32OrDefault('32', CAST('0', 'UInt32')): 32
toUInt32OrDefault('abc', CAST('0', 'UInt32')): 0
See also
toUInt32
.
toUInt32OrZero
.
toUInt32OrNull
.
toUInt64 {#touint64}
Converts an input value to a value of type
UInt64
. Throws an exception in case of an error.
Syntax
sql
toUInt64(expr)
Arguments | {"source_file": "type-conversion-functions.md"} | [
0.028608955442905426,
-0.012030167505145073,
-0.09887653589248657,
-0.007534450851380825,
-0.08358293771743774,
-0.0020761704072356224,
0.06060405448079109,
0.03526933118700981,
-0.03909246623516083,
0.004162466153502464,
-0.00866349320858717,
-0.09235050529241562,
0.04907074570655823,
-0.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.