UUID
A Universally Unique Identifier (UUID) is a 16-byte value used to identify records. For detailed information about UUIDs, see Wikipedia.
While different UUID variants exist, e.g. UUIDv4 and UUIDv7 (see here), ClickHouse does not validate that inserted UUIDs conform to a particular variant. UUIDs are internally treated as a sequence of 16 random bytes with 8-4-4-4-12 representation at SQL level.
Example UUID value:
The default UUID is all-zero. It is used, for example, when a new record is inserted but no value for a UUID column is specified:
Due to historical reasons, UUIDs are sorted by their second half.
While this is fine for UUIDv4 values, this can deteriorate performance with UUIDv7 columns used in primary index definitions (usage in ordering keys or partition keys is fine). More specifically, UUIDv7 values consist of a timestamp in the first half and a counter in the second half. UUIDv7 sorting in sparse primary key indexes (i.e., the first values of each index granule) will therefore be by counter field. Assuming UUIDs were sorted by the first half (timestamp), then the primary key index analysis step at the beginning of queries is expected to prune all marks in all but one part. However, with sorting by the second half (counter), at least one mark is expected to be returned for all parts, leading to unnecessary unnecessary disk accesses.
Example:
Result:
As a workaround, the UUID can be converted to a timestamp extracted from the second half:
ORDER BY (UUIDv7ToDateTime(uuid), uuid)
Generating UUIDs
ClickHouse provides the generateUUIDv4 function to generate random UUID version 4 values.
Usage Example
Example 1
This example demonstrates the creation of a table with a UUID column and the insertion of a value into the table.
Result:
Example 2
In this example, no UUID column value is specified when the record is inserted, i.e. the default UUID value is inserted:
Restrictions
The UUID data type only supports functions which String data type also supports (for example, min, max, and count).
The UUID data type is not supported by arithmetic operations (for example, abs) or aggregate functions, such as sum and avg.