Unique Pairs In Any Column Order
Enforce uniqueness for an undirected pair: a unique index on LEAST and GREATEST normalizes both directions to the same key before comparing.
Code
-- 图边表:一条边可在任一方向录入 (a,b) 或 (b,a)
CREATE TABLE edges (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
endpoint_a bigint NOT NULL,
endpoint_b bigint NOT NULL,
CHECK (endpoint_a <> endpoint_b)
);
-- unique regardless of column order: LEAST/GREATEST normalize the pair
CREATE UNIQUE INDEX edges_pair_uniq
ON edges (LEAST(endpoint_a, endpoint_b), GREATEST(endpoint_a, endpoint_b));
INSERT INTO edges (endpoint_a, endpoint_b) VALUES (10, 20);
-- 反方向再插一次:归一化后与已有行同键,被唯一索引拒绝
-- ERROR: duplicate key value violates unique constraint "edges_pair_uniq"
-- INSERT INTO edges (endpoint_a, endpoint_b) VALUES (20, 10);
-- 不同顶点对不受影响
INSERT INTO edges (endpoint_a, endpoint_b) VALUES (20, 30);
SELECT id, endpoint_a, endpoint_b FROM edges ORDER BY id;What the code does
SELECT / INSERT / CREATE statements share the script, touching edges.
Mechanically, the statements are built from: an ORDER BY that fixes the output order; a CHECK constraint that rejects out-of-domain values at write time; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; UNIQUE constraints that keep duplicate values out; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Applying it
The edges table is the working surface here.
Statements that matter
CREATE TABLE edges (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
endpoint_a bigint NOT NULL,
endpoint_b bigint NOT NULL,
CHECK (endpoint_a <> endpoint_b)
);
CREATE UNIQUE INDEX edges_pair_uniq
ON edges (LEAST(endpoint_a, endpoint_b), GREATEST(endpoint_a, endpoint_b));
INSERT INTO edges (endpoint_a, endpoint_b) VALUES (10, 20);
Interactive Tools for This Topic
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.CSV Column AnalyzerProfile every CSV column with inferred types, empty-cell counts, unique values, and numeric min and max ranges.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 the SQL touch?
- The references are `edges`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.