Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
up vote 2 down vote accepted
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;
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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