Search code examples
sqlgroup-bycounthaving-clause

Return count of ids where occurrence is equal to 1 in SQL


I have a dataset with a column of ids (e.g.)

ID
1
2
3
3
3
4
4
5

I want to return the count of the rows where an id only appears once. For example, from the above table the query would return count = 3 as only ID 1, 2 and 5 appear once.


Solution

  • This query:

    SELECT id
    FROM tablename
    GROUP BY id
    HAVING COUNT(*) = 1
    

    returns all the ids that you want to count, so count them like this:

    SELECT COUNT(*)
    FROM (
      SELECT id
      FROM tablename
      GROUP BY id
      HAVING COUNT(*) = 1
    ) t
    

    See the demo.