I'm using postgresql and I have a large database. A simplified version of the datastructure for my table looks like this:

id (primary unique key), data, userID
1, foo, 4
2, foobar, 4
3, lala, 5
4, boo, 6

I want to find all the rows where the userID value is unique in the entire table structure. So in the above example, it would return the rows for id's 3 and 4. If the userID is listed in two or more rows, I just want to discard it.

Is this possible in one query?

Thanks in advance.

1 Answer 1

select *
from the_table
where userid in (select userid
                 from the_table
                 group by userid
                 having count(*) = 1)


select *
from the_table
   inner join (select userid
               from the_table
               group by userid
               having count(*) = 1) t on t.userid = the_table.userid;

or (possibly more efficient because only a single scan is needed):

select id, data, userid
from (
  select id, 
         count(*) over (partition by userid) as cnt
  from the_table
) t
where cnt = 1;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.