PostgreSQL – How to Extract All Possible Couples of a Primary Key in a Table

duplicationpostgresql

I would like to find out a PostgreSQL command that reads the content of a table, and returns all the possible couplings of the primary key of the table.

Something like this:

input_table (ID is the primary key):

- - - - - - - - - - 
ID | label | name
- - - - - - - - - - 
11 | aaa | Jenny

24 | bbb | Larry

35 | ccc | Trevor

48 | ddd | Jules
- - - - - - - - - - 

The query should return all the possible couplings of the primary keys:

- - - - - - - - - - 
ID_left | ID_right
- - - - - - - - - - 
11 | 24

11 | 35

11 | 48

24 | 35

24 | 48

35 | 48
- - - - - - - - - - 

Is it possible to design this query? If yes, how?

Thanks

Best Answer

Sounds like a simple cross join:

select a.id, b.id
from input_table a
  cross join input_table b
where a.id <> b.id;