I'm trying to make a table to store the edges of a directed graph, but want to avoid duplicate edges in both directions.
I can of course make it one direction :
CREATE TABLE edge (parent integer, child integer, UNIQUE(parent, child));
But how can I make sure that I also don't allow a new (parent, child) that already exists as (child, parent) ?
Any ideas would be greatly appreciated !
Best Answer
Using
GREATEST
andLEAST
Essentially, if we can sort of the columns in the index, we can ensure that the duplicate entry causes a collision and a constraint violation this is because
sort(5,2) = sort(2,5)
. Because there is nosort
, we usegreatest
andleast
.