Search code examples
sqlsql-serverunique-constraintundirected-graph

In SQL can you enforce unicity of undirected edge using sum and product computed columns?


create table Location (
  id integer primary key(1, 1),
  latitude decimal(8,6),
  longitude decimal(9,6),
  address varchar(100),
  name varchar(60) unique
);
create table Journey (
  id integer primary key(1,1),
  id_from integer foreign key references Location(id),
  id_to integer foreign key references Location(id),
  s = id_from + id_to persistent,
  p = id_from * id_to persistent,
  unique(s, p),
  name varchar(100) unique,
);

Is this a correct method to enforce a single journey (either way in or way back) for each pair of locations ?


Solution

  • No. If you want unique edges regardless of direction, then use the smallest and biggest values:

    create table Journey (
      id integer primary key(1,1),
      id_from integer foreign key references Location(id),
      id_to integer foreign key references Location(id),
      id_least as (case when id_from < id_to then id_from else id_to end) persistent,
      id_greatest as (case when id_from < id_to then id_to else id_from end) persistent,
      unique(least_id, greatest_id),
      name varchar(100) unique,
    );