Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if value in column for all rows is exactly value

Tags:

sql

For example, I want follow the number 2 as target

This should return positive indication:

ID       Status
123      2
432      2
531      2
123      2

This should return negative indication:

ID       Status
123      1
432      3
531      2
123      2

This should return negative indication:

ID       Status
123      1
432      1
531      1
123      1

Thanks

like image 892
gilhanan Avatar asked Mar 27 '11 12:03

gilhanan


1 Answers

EXISTS should be used in preference to COUNT so it can return as soon as the first non matching row is found.

SELECT CASE
         WHEN NOT EXISTS(SELECT *
                         FROM   your_table
                         WHERE  status <> 2) THEN 'Y'
         ELSE 'N'
       END AS your_result  

You don't state RDBMS. You might need to append FROM DUAL onto the end of the above dependant on flavour.

like image 165
Martin Smith Avatar answered Oct 05 '22 16:10

Martin Smith