Question

I just a MySQL beginner. This is first time for me asking you guys at STACKOVERFLOW about query using HAVING and WHERE:

SELECT 
    BOXNUMBER
    ,COUNT(BOXNUMBER) AS QTY
    ,CDATETIME 
FROM 
    HSS_SNO 
WHERE 
    year(CDATETIME) IN ('2008','2010','2014') 
GROUP BY 
    BOXNUMBER ;

/* Affected rows: 0  Found rows: 13,928  Warnings: 0  Duration for 1 query: 0.031 sec. (+ 2.782 sec. network) */

SELECT 
    BOXNUMBER
    ,COUNT(BOXNUMBER) AS QTY
    ,CDATETIME 
FROM 
    HSS_SNO 
GROUP BY 
    BOXNUMBER 
HAVING 
    year(CDATETIME) IN ('2008','2010','2014');

 /* Affected rows: 0  Found rows: 13,922  Warnings: 0  Duration for 1 query: 0.047 sec. (+ 2.594 sec. network) */

I think these queries will give me same result, but 'found rows' different each other. Could you tell me why like that ?

Thanks Tobing (Sorry for my English)

Was it helpful?

Solution

    .......
     WHERE 
        year(CDATETIME) IN ('2008','2010','2014') 
    GROUP BY 
        BOXNUMBER ;

The above query gives more rows because you are not applying any condition on Group by clause and the other query

......
GROUP BY 
    BOXNUMBER 
HAVING 
    year(CDATETIME) IN ('2008','2010','2014');

here you are applying the condition on group by that what type of records you wanted, as a result u got less records when compared.

have a look at this link which will helps in understanding of sql query execution in detail http://social.msdn.microsoft.com/Forums/sqlserver/en-US/70efeffe-76b9-4b7e-b4a1-ba53f5d21916/order-of-execution-of-sql-queries

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top