Search code examples
sqlgroup-bywhere-clauseaggregate-functionshaving

SQL - HAVING MIN() vs WHERE


Are these queries exactly the same, or is it possible to get different results depending on the data?

SELECT A, B, C, D 
FROM Table_A 
GROUP BY A, B, C, D , E
HAVING A in (1,2) AND E = 1 AND MIN(status) = 100

SELECT A, B, C, D 
FROM Table_A 
WHERE A IN (1,2) AND E = 1 AND status = 100
GROUP BY A, B, C, D , E

Solution

  • They're not equal.

    When you consider the following block

    create table Table_A(A int, B int, C int, D int, E int, status int);
    insert into Table_A values(1,1,1,1,1,100);
    insert into Table_A values(1,1,1,1,1,10);
    insert into Table_A values(2,1,1,1,1,10);
    
    SELECT A, B, C, D, 'First Query' as query 
    FROM Table_A 
    GROUP BY A, B, C, D , E
    HAVING A in (1,2) AND E = 1 AND MIN(status) = 100;
    
    SELECT A, B, C, D, 'Second Query' as query   
    FROM Table_A 
    WHERE A IN (1,2) AND E = 1 AND status = 100
    GROUP BY A, B, C, D , E
    

    you get

    A   B   C   D   query
    -   -   -   -   -------------
    1   1   1   1   Second Query
    

    as a result ( only the second one returns ),

    since for both of the groupings 1,1,1,1,1 and 2,1,1,1,1 -> min(status)=10.

    For this reason min(status)=100 case never occurs and first query returns no result.

    Rextester Demo