Tuesday, September 25, 2012

Difference Between the HAVING and WHERE Clauses in a SQL

Difference Between the HAVING and WHERE Clauses in a SQL
  1. The WHERE clause specifies the criteria which individual records must meet to be selcted by a query. It can be used without the GROUP BY clause. The HAVING clause cannot be used without the GROUP BY clause.
  2. The WHERE clause selects rows before grouping. The HAVING clause selects rows after grouping.
  3. The WHERE clause cannot contain aggregate functions. The HAVING clause can contain aggregate functions. source

    Using the code

    Code
    1. SELECT cusnum, lstnam, init
    2. FROM Test
    3. WHERE state IN ('CA', 'LA')
    4.  
    5. CUSNUM LSTNAM INIT BALDUE
    6. ====== ============ ==== ========
    7. 938472 John G K 37.00
    8. 938485 Mark J A 3987.50
    9. 593029 Lily E D 25.00
    Suppose I want the total amount due from customers by state. In that case, I would need to use the GROUP BY clause to build an aggregate query.
    Code
    1. SELECT state,SUM(baldue)
    2. FROM Test
    3. GROUP BY state
    4. ORDER BY state
    5.  
    6. State Sum(Baldue)
    7. ===== ===========
    8. CA 250.00
    9. CO 58.75
    10. GA 3987.50
    11. MN 510.00
    12. NY 589.50
    13. TX 62.00
    14. VT 439.00
    15. WY .00
    Using Having
    Code
    1. SELECT state,SUM(baldue)
    2. FROM Test
    3. GROUP BY state
    4. HAVING SUM(baldue) > 250
    5.  
    6.  
    7. State Sum(Baldue)
    8. ===== ===========
    9. GA 3987.50
    10. MN 510.00
    11. NY 589.50
    12. VT 439.00




No comments:

Post a Comment