DuckDB Extension
TSID
Generate time-sorted identifiers in DuckDB SQL. Create IDs for rows and recover their embedded timestamps with the TSID extension.
On this page
Sample data for the examples
Each browser example starts with these sample tables; sample files are shared across examples on this page. Run this setup first when trying the examples in your own DuckDB session.
-- Fixtures for tsid cookbook / functions / technical-details examples.
-- Idempotent: uses CREATE OR REPLACE so re-running is safe.
--
-- tsid() is non-deterministic, so we seed the events table with literal
-- 32-char hex strings (the TSID rendering) rather than calling tsid().
-- The values are time-ordered by ordinary string compare, matching the
-- property the cookbook examples demonstrate.
CREATE OR REPLACE TABLE events (
id VARCHAR PRIMARY KEY,
payload JSON
);
INSERT INTO events(id, payload) VALUES
('675716e86985495e9cf575f0b9c4a8db', '{"type":"login"}'),
('675716e96985495e9cf575f0b9c4a8dc', '{"type":"click"}'),
('675716ea6985495e9cf575f0b9c4a8dd', '{"type":"logout"}');
-- Bind variable referenced as :last_id_from_page_1 in the pagination recipe.
SET VARIABLE last_id_from_page_1 = '675716ea6985495e9cf575f0b9c4a8dd';
Generate identifiers with an embedded timestamp
TSID creates identifiers whose leading portion represents their generation time. This gives IDs a chronological ordering and lets you recover a timestamp from the identifier later.
Use it for new rows when a timestamp-bearing ID is useful to your consumers. Keep an explicit event-time column when generation time and event time differ. If you need an exact insertion order across concurrent writers, record a separate sequence.
Example
Generate IDs for three rows
Each call generates a new identifier. The query sorts the output explicitly.
Tested with DuckDB 1.5.6. Browser examples use Haybarn-Wasm 2.0.0-rc12.
SET allow_extension_repositories = 'allowed';
CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
WITH PREFIX 'https://duckdb-extensions.query.farm';
INSTALL tsid FROM query_farm;
LOAD tsid FROM query_farm;
SELECT tsid() AS id
FROM range(3)
ORDER BY id;
SET allow_extension_repositories = 'allowed';
CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
WITH PREFIX 'https://haybarn-extensions.query.farm';
INSTALL tsid FROM query_farm;
LOAD tsid FROM query_farm;
SELECT tsid() AS id
FROM range(3)
ORDER BY id;
INSTALL tsid FROM community;
LOAD tsid;
SELECT tsid() AS id
FROM range(3)
ORDER BY id;
Your IDs will differ on each run. Sorting IDs does not guarantee insertion order across threads or machines; keep a separate sequence when that order matters.
Common tasks
Deep Dive
Technical Details
What you can do with one query
The shortest path from βI need a primary key defaultβ to βrows with time-sortable identifiersβ:
CREATE OR REPLACE TABLE events ( id VARCHAR DEFAULT tsid() PRIMARY KEY, payload JSON);
INSERT INTO events(payload) VALUES ('{"type":"login"}');INSERT INTO events(payload) VALUES ('{"type":"click"}');
-- Sort by the timestamp-bearing IDSELECT id, tsid_to_timestamp(id) AS created_at, payloadFROM eventsORDER BY id;tsid() returns a 32-character hex VARCHAR whose leading bits are a high-resolution timestamp. String comparison sorts by the embedded generation-time prefix; it does not guarantee insertion or commit order across concurrent producers. tsid_to_timestamp decodes the leading bits back to a TIMESTAMP when you need the wall-clock value.
The headline feature is also the headline caveat: the timestamp embedded in a TSID is recoverable by anyone holding the ID. Thatβs perfect for an internal primary key, an audit log, or a server-side pagination cursor. Itβs a leak when the ID surfaces externally β a public order URL, a referral link, a webhook payload β and the creation moment is competitively or personally sensitive (signup time, account age, when an order was placed).
For internal-only IDs, use tsid(). For public-facing identifiers where ordering doesnβt matter, stick with DuckDBβs built-in uuid() (UUIDv4 β random, opaque, leaks nothing).
TSID vs the alternatives
DuckDB ships uuid() β a UUIDv4 generator. Itβs random and unsortable, which is the right call for opaque external IDs and the wrong call when insertion order matters. TSID, UUIDv7, and ULID are three renderings of the same idea: high-resolution time prefix plus random tail.
DuckDB uuid() |
tsid() / tsid_uuid() |
DuckDB uuidv7() |
ULID | |
|---|---|---|---|---|
| Time-sortable | No | Yes | Yes | Yes |
| Embeds creation time | No | Yes (nanosecond field, 4 ns steps) | Yes (milliseconds) | Yes (milliseconds) |
| Rendering | UUID hex (36 chars w/ dashes) | 32 hex chars, or a native UUID |
UUID hex (36 chars w/ dashes) | 26 chars Crockford base32 |
| Decode the time | β | tsid_to_timestamp |
uuid_extract_timestamp |
β |
| Standardized | RFC 9562 | Library-specific (UUID v4 bit layout) | RFC 9562 | ulid/spec |
| In-DuckDB built-in | Yes | This extension | Yes | No |
DuckDBβs built-in uuidv7() and uuid_extract_timestamp() are the standards-based choice when another system needs to read the time back out of the ID: any RFC 9562 implementation can. Pick tsid() when you want sub-millisecond time resolution in the ID, the ability to mint an ID for a chosen timestamp (tsid(ts), DuckDB 2.0 build), or compatibility with TSIDs you already store. TSID values carry UUID version 4 bits, so uuid_extract_timestamp does not decode them β use tsid_to_timestamp.
The reference TSID concept also lives in non-DuckDB form as f4b6a3/tsid-creator on the JVM and similar libraries in other ecosystems; the rendering produced by this extension is library-specific, so donβt assume cross-ecosystem parsing without testing.
Sorting and storage
A timestamp prefix makes ID-based pagination possible with ORDER BY id and a last-seen-ID cursor. It does not physically cluster a DuckDB table or guarantee smaller indexes, compression, or faster inserts. Measure those properties on your data and storage layout.
Bit layout
| Bytes | Content |
|---|---|
| 0β3 | Seconds since 1970-01-01 UTC, unsigned big-endian (valid until 2106-02-07) |
| 4β7 | Nanoseconds in 4 ns steps, with the UUID version nibble (4) in byte 6 |
| 8β15 | Random, with the RFC 4122 variant bits (10) in byte 8 |
Because the time comes first and is big-endian, byte order, hex-string order and DuckDB UUID order all agree. tsid_to_timestamp returns microsecond precision.
Native UUID storage (DuckDB 2.0 build)
tsid_uuid() returns the same identifier as a native UUID β 16 bytes per value instead of a 32-character string β and tsid_to_timestamp accepts UUID input. tsid() still returns VARCHAR, so existing tables keep working. Convert between the two forms with casts:
SELECT tsid_uuid()::VARCHAR AS dashed, replace(tsid_uuid()::VARCHAR, '-', '') AS like_tsid, '65d4a2b6000000004000800000000000'::UUID AS as_uuid;Both generators also accept a TIMESTAMP, which is useful for backfilling rows or building ID range bounds:
SELECT tsid(TIMESTAMP '2024-06-01 00:00:00') AS lower_bound, tsid_uuid(TIMESTAMP '2024-06-01 00:00:00') AS lower_bound_uuid;The random tail still varies, so treat these as approximate bounds: compare on tsid_to_timestamp(id) when the boundary must be exact.
Changes in the DuckDB 2.0 release
- Strict parsing.
tsid_to_timestampaccepts exactly 32 hex digits or the dashed 8-4-4-4-12 form. Earlier builds could crash the DuckDB process on some malformed 36-character strings, and decoded strings such as'------------------------------------'as 1970-01-01; these now raiseInvalid TSID format. - Thread-safe randomness. Earlier builds drew the random tail from a single clock-seeded generator shared by all threads. Each thread now has its own generator seeded from the operating system, so parallel queries and separate processes donβt produce correlated tails.
- New:
tsid_uuid(),tsid(ts)/tsid_uuid(ts), andtsid_to_timestamp(UUID).
The Haybarn 1.5 build has only tsid() and tsid_to_timestamp(VARCHAR).
Bulk generation and ordering
There is no seed overload. Parallel calls can be evaluated in a different order from the input rows. Sort the generated values explicitly when needed:
SELECT tsid() AS idFROM range(1000)ORDER BY id;This sorts the output by ID. It does not make generation deterministic or guarantee strict insertion order across threads, processes, or clock changes. Keep an explicit sequence or application timestamp when that ordering is part of your data contract.
When to keep uuid() instead
- Public-facing IDs where leaking creation time matters β order URLs, share links, account references.
- Cross-system identifiers where a peer expects a canonical UUID format and you donβt control the consumer.
- You donβt care about insertion order and the table is small enough that index locality is irrelevant.
In every other case where uuid() was the reach-for default β internal primary keys, event logs, audit tables β a time-sorted ID (tsid(), tsid_uuid() or DuckDBβs uuidv7()) is the better fit.
Reference
Extension Contents
Quick reference to all available functions and settings organized by category.
| Name | Type | Description |
|---|---|---|
|
Generation
Generate a timestamp-prefixed TSID with tsid() (VARCHAR) or, in the DuckDB 2.0 build, tsid_uuid() (native UUID); both accept an optional TIMESTAMP. Use ORDER BY for sorted results; generation does not guarantee strict insertion or commit order. |
||
| tsid() | Object type: Scalar function | Generate a new Time-Sorted Unique Identifier as a 32-character lowercase hex string. |
| tsid_uuid() | Object type: Scalar function |
DuckDB 2.0 build only. Generate a TSID as a native UUID value: the same bits, layout and time ordering as tsid(), stored in 16 bytes instead of a 32-character string.
|
|
Inspection
Extract the embedded generation timestamp from a TSID string or (DuckDB 2.0 build) UUID. It need not equal insertion or transaction commit time. |
||
| tsid_to_timestamp() | Object type: Scalar function | Extract the embedded timestamp from a TSID. |
No extension contents match that search.
API Reference
Function Reference
Practical Examples
Cookbook
Real-world recipes and patterns for common use cases.
Generate IDs
-- Single TSIDSELECT tsid();-- '675716e86985495e9cf575f0b9c4a8db'-- Bulk: generate 100 IDs (use ORDER BY for sorted output)SELECT tsid() AS id FROM range(100);Use as a primary key
TSIDs have a generation-time prefix, so ordinary string comparison supports time-based sorting. This does not guarantee insertion or commit order across concurrent producers:
CREATE OR REPLACE TABLE events ( id VARCHAR DEFAULT tsid() PRIMARY KEY, payload JSON);
INSERT INTO events(payload) VALUES ('{"type":"login"}');INSERT INTO events(payload) VALUES ('{"type":"click"}');
-- Sort by the timestamp-bearing IDSELECT id, payload FROM events ORDER BY id;Recover the timestamp
You donβt need a separate created_at β the timestamp is embedded:
SELECT id, tsid_to_timestamp(id) AS created_atFROM eventsORDER BY id;Time-range pagination
Because TSIDs are sortable strings, you can paginate by ID without a separate timestamp index:
-- Page 1: 100 most recentSELECT * FROM events ORDER BY id DESC LIMIT 100;-- Page 2: next 100, using the last id from page 1 as a cursorSELECT * FROM eventsWHERE id < (SELECT min(id) FROM (SELECT id FROM events ORDER BY id DESC LIMIT 100))ORDER BY id DESC LIMIT 100;This is the same trick Twitter snowflake-style IDs enable β you avoid the offset cost on large tables.
Store IDs as native UUIDs
DuckDB 2.0 build. tsid_uuid() returns the same time-sorted ID as a 16-byte UUID, half the storage of the 32-character string:
CREATE OR REPLACE TABLE orders ( id UUID DEFAULT tsid_uuid() PRIMARY KEY, amount DECIMAL(10, 2));
INSERT INTO orders(amount) VALUES (9.99), (24.50);
SELECT id, tsid_to_timestamp(id) AS created_at FROM orders ORDER BY id;Backfill IDs for historical rows
DuckDB 2.0 build. Pass a TIMESTAMP to embed a past time instead of now:
SELECT tsid(ts) AS id, tsFROM (VALUES (TIMESTAMP '2023-01-15 08:00:00'), (TIMESTAMP '2023-03-02 17:30:00')) t(ts)ORDER BY id;TSID vs UUID
| TSID | UUIDv4 (uuid()) |
UUIDv7 (uuidv7()) |
|
|---|---|---|---|
| Time-sortable | β | β | β |
| Width | 32-char VARCHAR, or 16-byte UUID via tsid_uuid() |
16-byte UUID |
16-byte UUID |
| Embeds creation time | β
(decode with tsid_to_timestamp) |
β | β
(decode with uuid_extract_timestamp) |
| Time resolution | 4 ns field, decoded to Β΅s | β | 1 ms |
| Cross-system uniqueness | β | β | β |
UUIDv7, built into DuckDB as uuidv7(), is the closest standard alternative and the better choice when other systems must decode the time. Pick TSID for sub-millisecond resolution, IDs minted for a chosen timestamp, or compatibility with TSIDs you already store.
Platform Support
Compatibility
Extension availability may vary by platform and DuckDB version. Check below to ensure this extension supports your environment before installation.
Quick Facts
Platforms
DuckDB 2.0.0
- Linux x86_64aarch64
- Linux (musl) Not available
- macOS Apple Silicon
- Windows x86_64x86_64 (MinGW)
- WASM Not available
Compiled binary sizes
| Platform | Architecture | Size |
|---|---|---|
| Linux | x86_64 | 3.95 MB |
| Linux | aarch64 | 3.32 MB |
| macOS | Apple Silicon | 2.80 MB |
| Windows | x86_64 | 10.19 MB |
| Windows | x86_64 (MinGW) | 17.80 MB |
Compressed download sizes for the release shown above.
DuckDB & Haybarn
Release calendar- DuckDB v2.0.0 Query.Farm repository Supported
- Haybarn v1.5.6 Built-in community repository Supported
Browser examples use Haybarn-Wasm 2.0.0-rc12.
Checked .
Learn and explore
Tutorials and articles
Writing about TSID: how it works, what changed, and why.
-
TSID for DuckDB 2.0: native UUIDs and IDs from event time
TSID adds native UUID output and timestamp inputs in DuckDB 2.0, fixes concurrent random generation, and rejects malformed IDs without crashing the process.