Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL EXISTS operator with GROUP BY

Tags:

sql

I am currently looking through the EXISTS operator examples on http://www.w3resource.com/sql/special-operators/sql_exists.php# and have come across an example which doesn't quite make sense. The code is as follows:

SELECT cust_code,cust_name,cust_city,grade  
FROM customer  
WHERE grade=2 AND  
    EXISTS(  
        SELECT COUNT(*)
        FROM customer  
        WHERE grade=2  
        GROUP BY grade  
        HAVING COUNT(*)>2
    );

From my understanding, the subquery will always evaluate to TRUE and it doesn't relate to the customer table higher up - so it seems irrelevant to put it in there.

Can anybody explain what the code is trying to achieve here please?

Many Thanks!

like image 858
Jayba Avatar asked Dec 04 '25 16:12

Jayba


1 Answers

EXISTS will evaluate to false when count of records with grade=2 is less than or equal to 2. Query checks if there are more than two records with grade=2. If there are then show columns mentioned in the outer select.

like image 80
Akshey Bhat Avatar answered Dec 12 '25 13:12

Akshey Bhat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!