Difference Between the HAVING and WHERE Clauses in a SQL
- 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.
- The WHERE clause selects rows before grouping. The HAVING clause selects rows after grouping.
- The WHERE clause cannot contain aggregate functions. The HAVING clause can contain aggregate functions. source
Using the code
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- SELECT cusnum, lstnam, init
- FROM Test
- WHERE state IN ('CA', 'LA')
- CUSNUM LSTNAM INIT BALDUE
- ====== ============ ==== ========
- 938472 John G K 37.00
- 938485 Mark J A 3987.50
- 593029 Lily E D 25.00
Using HavingCode- SELECT state,SUM(baldue)
- FROM Test
- GROUP BY state
- ORDER BY state
- State Sum(Baldue)
- ===== ===========
- CA 250.00
- CO 58.75
- GA 3987.50
- MN 510.00
- NY 589.50
- TX 62.00
- VT 439.00
- WY .00
Code- SELECT state,SUM(baldue)
- FROM Test
- GROUP BY state
- HAVING SUM(baldue) > 250
- State Sum(Baldue)
- ===== ===========
- GA 3987.50
- MN 510.00
- NY 589.50
- VT 439.00
No comments:
Post a Comment