Skip to content
Advertisement

How to prevent logical duplicates in a unary one to many SQL relationship table

In a non directional unary relationship what would be the best option to prevent logical duplicates?

E.G.

Main table

Relational table

Entry two in the relational table is already logically represented by the first entry as the relationship is non directional

Advertisement

Answer

In many cases, having both rows in the table is very handy for queries. That said, if you only want one, there here are two options.

First, insist that id1 < id2 and that the pair be unique:

This might have some unintended consequences. You are not able to insert (2, 1) into the table.

A second approach is to create a function-based unique index. Not all databases support this directly, but there is often similar syntax available. Most databases support least() and greatest(), so:

In SQL Server, you can do this with computed columns:

Here is a db<>fiddle.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement