Home > Software design >  PostgreSQL - Can I get the inverse of distinct rows?
PostgreSQL - Can I get the inverse of distinct rows?

Time:08-09

I have a table of contacts. Each contact has an associating website. Each website can have multiple contacts.

I ran a query to get one contact with Select distinct on (website). This works fine.

But I want to do something the the rest of the data not selected but Select distinct on (website). Is there an inverse command where I can find all records from websites that have NOT been processed?

CodePudding user response:

Use except. Here is an illustration. order by is for clarity.

create temporary table the_table (i integer, tx text);
insert into the_table values
(1, 'one'),
(1, 'one more one'),
(1, 'yet another one'),
(2, 'two'),
(2, 'one more two'),
(2, 'yet another two'),
(3, 'three'),
(3, 'three alternative');

select * from the_table
EXCEPT
select distinct on (i) * from the_table
order by i;
i tx
1 one more one
1 yet another one
2 yet another two
2 one more two
3 three alternative
  • Related