Skip to content
Advertisement

How to find unique combinations for a table column in SQL?

I’ve below table: Test

create table test (Id char)

insert into test values
('A'),
('B'),
('C'),
('D'),
('E')

Fiddle Link for testing

Expected Output:

  1. a.ID b.ID
  • A B
  • A C
  • A D
  • A E
  • B C
  • B D
  • B E
  • C D
  • C E
  • D E

I tried below code:

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

But my current output has invalid combination which are already present above refer image here (highlighted records are invalid as they are present above in inverse order)

Advertisement

Answer

Should be fairly simple; switch from <> to <:

select a.id, b.id from test a cross join test b where a.id < b.id
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement