gen_random_uuid UUID Primary Keys
Give tables random UUID primary keys with the built-in gen_random_uuid default, and validate external identifiers with ::uuid casts.
Code
-- 随机 UUID 主键:gen_random_uuid() 是 PG 13+ 内建函数,无需扩展
CREATE TABLE api_keys (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
label text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO api_keys (label) VALUES ('ci-runner') RETURNING id, label;
-- 随机键写散在 B 树各处:按时间查询的索引建在 created_at 上
CREATE INDEX idx_api_keys_created ON api_keys (created_at);
-- 解析外部标识:::uuid 强转校验格式,非法串当场报错
SELECT 'a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d'::uuid;
SELECT 'not-a-uuid'::uuid; -- invalid input syntax for type uuidWhat the code does
Several statements share this file — SELECT / INSERT / CREATE, with api_keys among the objects involved.
Breaking the statements into their working parts: a RETURNING clause that hands the affected rows back to the caller; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns.
Applying it
Run it in the api_keys database context.
Statements that matter
CREATE TABLE api_keys (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
label text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO api_keys (label) VALUES ('ci-runner') RETURNING id, label;
CREATE INDEX idx_api_keys_created ON api_keys (created_at);
Interactive Tools for This Topic
UUID v4 GeneratorGenerate cryptographically random UUIDs version 4 using the Web Crypto API. Produce single or batch UUIDs with optional uppercase formatting and copy-to-clipboard support.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- Which tables does this file reference?
- The references are `api_keys`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.