# UUID (/docs/reference/sql/functions/uuid)



This page describes the RawTree engine binary used to generate this reference. It does not define Query API support. Descriptions retain upstream ClickHouse terminology. See [SQL interface scope](/docs/reference/clickhouse-compatibility#service-interfaces).

UUIDNumToString [#uuidnumtostring]

Takes a binary representation of a UUID, with its format optionally specified by `variant` (`Big-endian` by default), and returns a string containing 36 characters in text format.

**Syntax**

```sql
UUIDNumToString(binary[, variant])
```

**Arguments**

* `binary` — Binary representation of a UUID. [`FixedString(16)`](/reference/data-types/fixedstring)
* `variant` — Variant as specified by [RFC4122](https://datatracker.ietf.org/doc/html/rfc4122#section-4.1.1). 1 = `Big-endian` (default), 2 = `Microsoft`. [`(U)Int*`](/reference/data-types/int-uint)

**Returned value**

Returns the UUID as a string. [`String`](/reference/data-types/string)

**Examples**

**Usage example**

```sql title=Query
SELECT
    'a/<@];!~p{jTj={)' AS bytes,
    UUIDNumToString(toFixedString(bytes, 16)) AS uuid
```

```text title=Response
┌─bytes────────────┬─uuid─────────────────────────────────┐
│ a/<@];!~p{jTj={) │ 612f3c40-5d3b-217e-707b-6a546a3d7b29 │
└──────────────────┴──────────────────────────────────────┘
```

**Microsoft variant**

```sql title=Query
SELECT
    '@</a;]~!p{jTj={)' AS bytes,
    UUIDNumToString(toFixedString(bytes, 16), 2) AS uuid
```

```text title=Response
┌─bytes────────────┬─uuid─────────────────────────────────┐
│ @</a;]~!p{jTj={) │ 612f3c40-5d3b-217e-707b-6a546a3d7b29 │
└──────────────────┴──────────────────────────────────────┘
```

*Introduced in version 1.1.0.*

UUIDStringToNum [#uuidstringtonum]

Accepts a string containing 36 characters in the format `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`, and returns a [FixedString(16)](/reference/data-types/fixedstring) as its binary representation, with its format optionally specified by `variant` (`Big-endian` by default).

**Syntax**

```sql
UUIDStringToNum(string[, variant = 1])
```

**Arguments**

* `string` — A string or fixed-string of 36 characters) [`String`](/reference/data-types/string) or [`FixedString(36)`](/reference/data-types/fixedstring)
* `variant` — Variant as specified by [RFC4122](https://datatracker.ietf.org/doc/html/rfc4122#section-4.1.1). 1 = `Big-endian` (default), 2 = `Microsoft`. [`(U)Int*`](/reference/data-types/int-uint)

**Returned value**

Returns the binary representation of `string`. [`FixedString(16)`](/reference/data-types/fixedstring)

**Examples**

**Usage example**

```sql title=Query
SELECT
    '612f3c40-5d3b-217e-707b-6a546a3d7b29' AS uuid,
    UUIDStringToNum(uuid) AS bytes
```

```text title=Response
┌─uuid─────────────────────────────────┬─bytes────────────┐
│ 612f3c40-5d3b-217e-707b-6a546a3d7b29 │ a/<@];!~p{jTj={) │
└──────────────────────────────────────┴──────────────────┘
```

**Microsoft variant**

```sql title=Query
SELECT
    '612f3c40-5d3b-217e-707b-6a546a3d7b29' AS uuid,
    UUIDStringToNum(uuid, 2) AS bytes
```

```text title=Response
┌─uuid─────────────────────────────────┬─bytes────────────┐
│ 612f3c40-5d3b-217e-707b-6a546a3d7b29 │ @</a;]~!p{jTj={) │
└──────────────────────────────────────┴──────────────────┘
```

*Introduced in version 1.1.0.*

UUIDToNum [#uuidtonum]

Accepts a [UUID](/reference/data-types/uuid) and returns its binary representation as a [FixedString(16)](/reference/data-types/fixedstring), with its format optionally specified by `variant` (`Big-endian` by default).
This function replaces calls to two separate functions `UUIDStringToNum(toString(uuid))` so no intermediate conversion from UUID to string is required to extract bytes from a UUID.

**Syntax**

```sql
UUIDToNum(uuid[, variant = 1])
```

**Arguments**

* `uuid` — UUID. [`String`](/reference/data-types/string) or [`FixedString`](/reference/data-types/fixedstring)
* `variant` — Variant as specified by [RFC4122](https://datatracker.ietf.org/doc/html/rfc4122#section-4.1.1). 1 = `Big-endian` (default), 2 = `Microsoft`. [`(U)Int*`](/reference/data-types/int-uint)

**Returned value**

Returns a binary representation of the UUID. [`FixedString(16)`](/reference/data-types/fixedstring)

**Examples**

**Usage example**

```sql title=Query
SELECT
    toUUID('612f3c40-5d3b-217e-707b-6a546a3d7b29') AS uuid,
    UUIDToNum(uuid) AS bytes
```

```text title=Response
┌─uuid─────────────────────────────────┬─bytes────────────┐
│ 612f3c40-5d3b-217e-707b-6a546a3d7b29 │ a/<@];!~p{jTj={) │
└──────────────────────────────────────┴──────────────────┘
```

**Microsoft variant**

```sql title=Query
SELECT
    toUUID('612f3c40-5d3b-217e-707b-6a546a3d7b29') AS uuid,
    UUIDToNum(uuid, 2) AS bytes
```

```text title=Response
┌─uuid─────────────────────────────────┬─bytes────────────┐
│ 612f3c40-5d3b-217e-707b-6a546a3d7b29 │ @</a;]~!p{jTj={) │
└──────────────────────────────────────┴──────────────────┘
```

*Introduced in version 24.5.0.*

UUIDv7ToDateTime [#uuidv7todatetime]

Returns the timestamp component of a UUID version 7.

**Syntax**

```sql
UUIDv7ToDateTime(uuid[, timezone])
```

**Arguments**

* `uuid` — A UUID version 7. [`String`](/reference/data-types/string)
* `timezone` — Optional. [Timezone name](/reference/settings/server-settings/settings/other#timezone) for the returned value. [`String`](/reference/data-types/string)

**Returned value**

Returns a timestamp with milliseconds precision. If the UUID is not a valid version 7 UUID, it returns `1970-01-01 00:00:00.000`. [`DateTime64(3)`](/reference/data-types/datetime64)

**Examples**

**Usage example**

```sql title=Query
SELECT UUIDv7ToDateTime(toUUID('018f05c9-4ab8-7b86-b64e-c9f03fbd45d1'))
```

```text title=Response
┌─UUIDv7ToDateTime(toUUID('018f05c9-4ab8-7b86-b64e-c9f03fbd45d1'))─┐
│                                          2024-04-22 15:30:29.048 │
└──────────────────────────────────────────────────────────────────┘
```

**With timezone**

```sql title=Query
SELECT UUIDv7ToDateTime(toUUID('018f05c9-4ab8-7b86-b64e-c9f03fbd45d1'), 'America/New_York')
```

```text title=Response
┌─UUIDv7ToDateTime(toUUID('018f05c9-4ab8-7b86-b64e-c9f03fbd45d1'), 'America/New_York')─┐
│                                                              2024-04-22 08:30:29.048 │
└──────────────────────────────────────────────────────────────────────────────────────┘
```

*Introduced in version 24.5.0.*

dateTime64ToSnowflakeID [#datetime64tosnowflakeid]

Converts a [DateTime64](/reference/data-types/datetime64) value to the first [Snowflake ID](https://en.wikipedia.org/wiki/Snowflake_ID) at the giving time.

**Syntax**

```sql
dateTime64ToSnowflakeID(value[, epoch])
```

**Arguments**

* `value` — Date with time. [`DateTime64`](/reference/data-types/datetime64)
* `epoch` — Epoch of the Snowflake ID in milliseconds since 1970-01-01. Defaults to 0 (1970-01-01). For the Twitter/X epoch (2015-01-01), provide 1288834974657. [`UInt*`](/reference/data-types/int-uint)

**Returned value**

Input value converted to [`UInt64`](/reference/data-types/int-uint)

**Examples**

**simple**

```sql title=Query
SELECT dateTime64ToSnowflakeID(toDateTime64('2021-08-15 18:57:56', 3, 'Asia/Shanghai'))
```

```text title=Response
6832626394434895872
```

*Introduced in version 24.6.0.*

dateTimeToSnowflakeID [#datetimetosnowflakeid]

Converts a [DateTime](/reference/data-types/datetime) value to the first [Snowflake ID](https://en.wikipedia.org/wiki/Snowflake_ID) at the giving time.

**Syntax**

```sql
dateTimeToSnowflakeID(value[, epoch])
```

**Arguments**

* `value` — Date with time. [`DateTime`](/reference/data-types/datetime)
* `epoch` — Epoch of the Snowflake ID in milliseconds since 1970-01-01. Defaults to 0 (1970-01-01). For the Twitter/X epoch (2015-01-01), provide 1288834974657. [`UInt*`](/reference/data-types/int-uint)

**Returned value**

Input value converted to [`UInt64`](/reference/data-types/int-uint)

**Examples**

**simple**

```sql title=Query
SELECT dateTimeToSnowflakeID(toDateTime('2021-08-15 18:57:56', 'Asia/Shanghai'))
```

```text title=Response
6832626392367104000
```

*Introduced in version 24.6.0.*

dateTimeToUUIDv7 [#datetimetouuidv7]

Converts a [DateTime](/reference/data-types/datetime) value to a [UUIDv7](https://www.rfc-editor.org/rfc/rfc9562) at the given time, as defined by [RFC 9562](https://www.rfc-editor.org/rfc/rfc9562).

See section ["UUIDv7 generation"](#uuidv7-generation) for details on UUID structure, counter management, and concurrency guarantees.

**Syntax**

```sql
dateTimeToUUIDv7(value)
```

**Arguments**

* `value` — Date with time. [`DateTime`](/reference/data-types/datetime)

**Returned value**

Returns a UUIDv7. [`UUID`](/reference/data-types/uuid)

**Examples**

**Usage example**

```sql title=Query
SELECT dateTimeToUUIDv7(toDateTime('2021-08-15 18:57:56', 'Asia/Shanghai'));
```

```text title=Response
┌─dateTimeToUUIDv7(toDateTime('2021-08-15 18:57:56', 'Asia/Shanghai'))─┐
│ 018f05af-f4a8-778f-beee-1bedbc95c93b                                 │
└──────────────────────────────────────────────────────────────────────┘
```

**multiple UUIDs for the same timestamp**

```sql title=Query
SELECT dateTimeToUUIDv7(toDateTime('2021-08-15 18:57:56'));
SELECT dateTimeToUUIDv7(toDateTime('2021-08-15 18:57:56'));
```

```text title=Response
┌─dateTimeToUUIDv7(t⋯08-15 18:57:56'))─┐
│ 017b4b2d-7720-76ed-ae44-bbcc23a8c550 │
└──────────────────────────────────────┘
┌─dateTimeToUUIDv7(t⋯08-15 18:57:56'))─┐
│ 017b4b2d-7720-76ed-ae44-bbcf71ed0fd3 │
└──────────────────────────────────────┘
```

*Introduced in version 25.8.0.*

generateSnowflakeID [#generatesnowflakeid]

Generates a [Snowflake ID](https://en.wikipedia.org/wiki/Snowflake_ID).

Function `generateSnowflakeID` guarantees that the counter field within a timestamp increments monotonically across all function invocations in concurrently running threads and queries.

See section ["Snowflake ID generation"](#snowflake-id-generation) for implementation details.

**Syntax**

```sql
generateSnowflakeID([expr, [machine_id]])
```

**Arguments**

* `expr` — An arbitrary [expression](/reference/syntax#expressions) used to bypass [common subexpression elimination](/reference/functions/regular-functions/overview#common-subexpression-elimination) if the function is called multiple times in a query. The value of the expression has no effect on the returned Snowflake ID. Optional. - `machine_id` — A machine ID, the lowest 10 bits are used. [Int64](/reference/data-types/int-uint). Optional.

**Returned value**

Returns the Snowflake ID. [`UInt64`](/reference/data-types/int-uint)

**Examples**

**Usage example**

```sql title=Query
CREATE TABLE tab (id UInt64)
ENGINE = MergeTree()
ORDER BY tuple();

INSERT INTO tab SELECT generateSnowflakeID();

SELECT * FROM tab;
```

```text title=Response
┌──────────────────id─┐
│ 7199081390080409600 │
└─────────────────────┘
```

**Multiple Snowflake IDs generated per row**

```sql title=Query
SELECT generateSnowflakeID(1), generateSnowflakeID(2);
```

```text title=Response
┌─generateSnowflakeID(1)─┬─generateSnowflakeID(2)─┐
│    7199081609652224000 │    7199081609652224001 │
└────────────────────────┴────────────────────────┘
```

**With expression and a machine ID**

```sql title=Query
SELECT generateSnowflakeID('expr', 1);
```

```text title=Response
┌─generateSnowflakeID('expr', 1)─┐
│            7201148511606784002 │
└────────────────────────────────┘
```

*Introduced in version 24.6.0.*

generateUUIDv4 [#generateuuidv4]

Generates a [version 4](https://tools.ietf.org/html/rfc4122#section-4.4) [UUID](/reference/data-types/uuid).

**Syntax**

```sql
generateUUIDv4([expr])
```

**Arguments**

* `expr` — Optional. An arbitrary expression used to bypass [common subexpression elimination](/reference/functions/regular-functions/overview#common-subexpression-elimination) if the function is called multiple times in a query. The value of the expression has no effect on the returned UUID.

**Returned value**

Returns a UUIDv4. [`UUID`](/reference/data-types/uuid)

**Examples**

**Usage example**

```sql title=Query
SELECT generateUUIDv4(number) FROM numbers(3);
```

```text title=Response
┌─generateUUIDv4(number)───────────────┐
│ fcf19b77-a610-42c5-b3f5-a13c122f65b6 │
│ 07700d36-cb6b-4189-af1d-0972f23dc3bc │
│ 68838947-1583-48b0-b9b7-cf8268dd343d │
└──────────────────────────────────────┘
```

**Common subexpression elimination**

```sql title=Query
SELECT generateUUIDv4(1), generateUUIDv4(1);
```

```text title=Response
┌─generateUUIDv4(1)────────────────────┬─generateUUIDv4(2)────────────────────┐
│ 2d49dc6e-ddce-4cd0-afb8-790956df54c1 │ 2d49dc6e-ddce-4cd0-afb8-790956df54c1 │
└──────────────────────────────────────┴──────────────────────────────────────┘
```

*Introduced in version 1.1.0.*

generateUUIDv7 [#generateuuidv7]

Generates a [version 7](https://www.rfc-editor.org/rfc/rfc9562) [UUID](/reference/data-types/uuid) as defined by [RFC 9562](https://www.rfc-editor.org/rfc/rfc9562).

See section ["UUIDv7 generation"](#uuidv7-generation) for details on UUID structure, counter management, and concurrency guarantees.

**Syntax**

```sql
generateUUIDv7([expr])
```

**Arguments**

* `expr` — Optional. An arbitrary expression used to bypass [common subexpression elimination](/reference/functions/regular-functions/overview#common-subexpression-elimination) if the function is called multiple times in a query. The value of the expression has no effect on the returned UUID. [`Any`](/reference/data-types)

**Returned value**

Returns a UUIDv7. [`UUID`](/reference/data-types/uuid)

**Examples**

**Usage example**

```sql title=Query
SELECT generateUUIDv7(number) FROM numbers(3);
```

```text title=Response
┌─generateUUIDv7(number)───────────────┐
│ 019947fb-5766-7ed0-b021-d906f8f7cebb │
│ 019947fb-5766-7ed0-b021-d9072d0d1e07 │
│ 019947fb-5766-7ed0-b021-d908dca2cf63 │
└──────────────────────────────────────┘
```

**Common subexpression elimination**

```sql title=Query
SELECT generateUUIDv7(1), generateUUIDv7(1);
```

```text title=Response
┌─generateUUIDv7(1)────────────────────┬─generateUUIDv7(1)────────────────────┐
│ 019947ff-0f87-7d88-ace0-8b5b3a66e0c1 │ 019947ff-0f87-7d88-ace0-8b5b3a66e0c1 │
└──────────────────────────────────────┴──────────────────────────────────────┘
```

*Introduced in version 24.5.0.*

snowflakeIDToDateTime [#snowflakeidtodatetime]

Returns the timestamp component of a [Snowflake ID](https://en.wikipedia.org/wiki/Snowflake_ID) as a value of type [DateTime](/reference/data-types/datetime).

**Syntax**

```sql
snowflakeIDToDateTime(value[, epoch[, time_zone]])
```

**Arguments**

* `value` — Snowflake ID. [`UInt64`](/reference/data-types/int-uint)
* `epoch` — Optional. Epoch of the Snowflake ID in milliseconds since 1970-01-01. Defaults to 0 (1970-01-01). For the Twitter/X epoch (2015-01-01), provide 1288834974657. [`UInt*`](/reference/data-types/int-uint)
* `time_zone` — Optional. [Timezone](/reference/settings/server-settings/settings/other#timezone). The function parses `time_string` according to the timezone. [`String`](/reference/data-types/string)

**Returned value**

Returns the timestamp component of `value`. [`DateTime`](/reference/data-types/datetime)

**Examples**

**Usage example**

```sql title=Query
SELECT snowflakeIDToDateTime(7204436857747984384) AS res
```

```text title=Response
┌─────────────────res─┐
│ 2024-06-06 10:59:58 │
└─────────────────────┘
```

*Introduced in version 24.6.0.*

snowflakeIDToDateTime64 [#snowflakeidtodatetime64]

Returns the timestamp component of a [Snowflake ID](https://en.wikipedia.org/wiki/Snowflake_ID) as a value of type [DateTime64](/reference/data-types/datetime64).

**Syntax**

```sql
snowflakeIDToDateTime64(value[, epoch[, time_zone]])
```

**Arguments**

* `value` — Snowflake ID. [`UInt64`](/reference/data-types/int-uint)
* `epoch` — Optional. Epoch of the Snowflake ID in milliseconds since 1970-01-01. Defaults to 0 (1970-01-01). For the Twitter/X epoch (2015-01-01), provide 1288834974657. [`UInt*`](/reference/data-types/int-uint)
* `time_zone` — Optional. [Timezone](/reference/settings/server-settings/settings/other#timezone). The function parses `time_string` according to the timezone. [`String`](/reference/data-types/string)

**Returned value**

Returns the timestamp component of `value` as a `DateTime64` with scale = 3, i.e. millisecond precision. [`DateTime64`](/reference/data-types/datetime64)

**Examples**

**Usage example**

```sql title=Query
SELECT snowflakeIDToDateTime64(7204436857747984384) AS res
```

```text title=Response
┌─────────────────res─┐
│ 2024-06-06 10:59:58 │
└─────────────────────┘
```

*Introduced in version 24.6.0.*

toUUIDOrDefault [#touuidordefault]

Converts a String value to UUID type. If the conversion fails, returns a default UUID value instead of throwing an error.

This function attempts to parse a string of 36 characters in the standard UUID format (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).
If the string cannot be converted to a valid UUID, the function returns the provided default UUID value.

**Syntax**

```sql
toUUIDOrDefault(string, default)
```

**Arguments**

* `string` — String of 36 characters or FixedString(36) to be converted to UUID. - `default` — UUID value to be returned if the first argument cannot be converted to UUID type.

**Returned value**

Returns the converted UUID if successful, or the default UUID if conversion fails. [`UUID`](/reference/data-types/uuid)

**Examples**

**Successful conversion returns the parsed UUID**

```sql title=Query
SELECT toUUIDOrDefault('61f0c404-5cb3-11e7-907b-a6006ad3dba0', toUUID('59f0c404-5cb3-11e7-907b-a6006ad3dba0'));
```

```text title=Response
┌─toUUIDOrDefault('61f0c404-5cb3-11e7-907b-a6006ad3dba0', toUUID('59f0c404-5cb3-11e7-907b-a6006ad3dba0'))─┐
│ 61f0c404-5cb3-11e7-907b-a6006ad3dba0                                                                    │
└─────────────────────────────────────────────────────────────────────────────────────────────────────────┘
```

**Failed conversion returns the default UUID**

```sql title=Query
SELECT toUUIDOrDefault('-----61f0c404-5cb3-11e7-907b-a6006ad3dba0', toUUID('59f0c404-5cb3-11e7-907b-a6006ad3dba0'));
```

```text title=Response
┌─toUUIDOrDefault('-----61f0c404-5cb3-11e7-907b-a6006ad3dba0', toUUID('59f0c404-5cb3-11e7-907b-a6006ad3dba0'))─┐
│ 59f0c404-5cb3-11e7-907b-a6006ad3dba0                                                                         │
└──────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
```

*Introduced in version 21.1.0.*

toUUIDOrNull [#touuidornull]

Converts an input value to a value of type `UUID` but returns `NULL` in case of an error.

Like [`toUUID`](/reference/functions/regular-functions/type-conversion-functions#toUUID) but returns `NULL` instead of throwing an exception on conversion errors.

Supported arguments:

* String representations of UUID in standard format (8-4-4-4-12 hexadecimal digits).
* String representations of UUID without hyphens (32 hexadecimal digits).

Unsupported arguments (return `NULL`):

* Invalid string formats.
* Non-string types.
* Malformed UUIDs.

**Syntax**

```sql
toUUIDOrNull(x)
```

**Arguments**

* `x` — A string representation of a UUID. [`String`](/reference/data-types/string)

**Returned value**

Returns a UUID value if successful, otherwise `NULL`. [`UUID`](/reference/data-types/uuid) or [`NULL`](/reference/syntax#null)

**Examples**

**Usage examples**

```sql title=Query
SELECT
    toUUIDOrNull('550e8400-e29b-41d4-a716-446655440000') AS valid_uuid,
    toUUIDOrNull('invalid-uuid') AS invalid_uuid
```

```text title=Response
┌─valid_uuid───────────────────────────┬─invalid_uuid─┐
│ 550e8400-e29b-41d4-a716-446655440000 │         ᴺᵁᴸᴸ │
└──────────────────────────────────────┴──────────────┘
```

*Introduced in version 20.12.0.*
