# How do I get the total number of unique pairs of a set in the database?

52

4 items:

``````A
B
C
D
``````

6 unique pairs possible:

``````AB
AC
BC
BD
CD
``````

What if I have 100 starting items? How many unique pairs are there? Is there a formula I can throw this into?

This question is tagged with `database` `math`

79

TLDR; The formula is `n(n-1)/2` where `n` is the number of items in the set.

## Explanation:

To find the number of unique pairs in a set, where the pairs are subject to the commutative property `(AB = BA)`, you can calculate the summation of `1 + 2 + ... + (n-1)` where `n` is the number of items in the set.

The reasoning is as follows, say you have 4 items:

``````A
B
C
D
``````

The number of items that can be paired with `A` is 3, or `n-1`:

``````AB
AC
``````

It follows that the number of items that can be paired with `B` is `n-2` (because `B` has already been paired with `A`):

``````BC
BD
``````

and so on...

``````(n-1) + (n-2) + ... + (n-(n-1))
``````

which is the same as

``````1 + 2 + ... + (n-1)
``````

or

``````n(n-1)/2
``````