Check column for unique value

mysql, sql

Solution

You could use this approach:

SELECT DISTINCT id, attribute 
FROM test t1 
WHERE (SELECT count(DISTINCT attribute) 
       FROM test t2 
       WHERE t2.id = t1.id) = 1

A better approach could be:

SELECT
   DISTINCT t1.id, t1.attribute
FROM
   test t1,
   (
      SELECT
         id,
         count(DISTINCT attribute) COUNT
      FROM
         test
      GROUP BY
         id
      HAVING
         COUNT = 1
   ) t2
WHERE
   t1.id = t2.id

Problem

My table: ``` id attribute 1 2 1 2 2 3 2 4 5 1 5 1 6 3 6 3 6 5 ``` Now I want only to output those `id` with `attribute`, if the attribute is the same for each `id`. In this sample table, the output would be ``` id attribute 1 2 5 1 ```

Original source