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.

SqlData Integrity

Code

snippet
-- 图边表:一条边可在任一方向录入 (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

FAQ

Which tables does the SQL touch?
The references are `edges`.