For a simple example, let's say I have a list
table and a list_entry
table:
CREATE TABLE list
(
id SERIAL PRIMARY KEY,
);
CREATE TABLE list_entry
(
id SERIAL PRIMARY KEY,
list_id INTEGER NOT NULL
REFERENCES list(id)
ON DELETE CASCADE,
position INTEGER NOT NULL,
value TEXT NOT NULL,
CONSTRAINT list_entry__position_in_list_unique
UNIQUE(list_id, position)
);
I now want to add the following constraint: all list entries with the same list_id
have position
entries that form a contiguous sequence starting at 1
.
And I have no idea how.
I first thought about EXCLUDE
constraints, but that seems to lead nowhere.
Could of course create a trigger, but I'd prefer not to, if at all possible.
You can use a generated column to reference the previous number in the list, essentially building a linked list. This works in Postgres:
In this implementation, the first item (
pos=0
) points to itself.