GROUP BY,HAVING and ORDER
BY clause
DEEPAM AGGARWAL
1
org payroll
X 1500
Y 3500
Z 3000
GROUP BY Clause
SELECT Statement – Grouping Rows
Find the payrollof each organization.
SELECT org, sum(salary) payroll
FROM salary_statistics GROUP BY org
Result:
salary_statistics
emp org salary
A X 500
B X 1000
C Y 1000
D Y 2500
E Z 3000
2
org payroll
X 1500
Z 3000
HAVING Clause
Find the organizations with payroll less than $3200.
SELECT org, sum(salary) payroll
FROM salary_statistics
GROUP BY org HAVING payroll < 3200
Result:
salary_statistics
emp org salary
A X 500
B X 1000
C Y 1000
D Y 2500
E Z 3000
3
The Difference Between WHERE and HAVING Clauses
 WHERE gets processed before any GROUP BY, and so it doesn't have access
to aggregated values (that is, the results of min(), max(), etc. functions).
 HAVING gets processed after GROUP BY and so can be used to constrain the
result set to only those with aggregated values that match a certain
predicate.
Find the organizations with payroll less than $3200.
SELECT org, sum(salary) payroll
FROM salary_statistics }✗Incorrect
WHERE payroll < 3200
GROUP BY org
SELECT org, sum(salary) payroll
FROM salary_statistics }✓ Correct
GROUP BY org
HAVING payroll < 3200
4
SELECT Statement – ORDER BY Clause
Find students ordered by merit position.
SELECT *
FROM result
ORDER BY marks DESC
result
student marks
A 25
B 56
C 82
D 25
E 39
5

Group By, Having Clause and Order By clause

  • 1.
    GROUP BY,HAVING andORDER BY clause DEEPAM AGGARWAL 1
  • 2.
    org payroll X 1500 Y3500 Z 3000 GROUP BY Clause SELECT Statement – Grouping Rows Find the payrollof each organization. SELECT org, sum(salary) payroll FROM salary_statistics GROUP BY org Result: salary_statistics emp org salary A X 500 B X 1000 C Y 1000 D Y 2500 E Z 3000 2
  • 3.
    org payroll X 1500 Z3000 HAVING Clause Find the organizations with payroll less than $3200. SELECT org, sum(salary) payroll FROM salary_statistics GROUP BY org HAVING payroll < 3200 Result: salary_statistics emp org salary A X 500 B X 1000 C Y 1000 D Y 2500 E Z 3000 3
  • 4.
    The Difference BetweenWHERE and HAVING Clauses  WHERE gets processed before any GROUP BY, and so it doesn't have access to aggregated values (that is, the results of min(), max(), etc. functions).  HAVING gets processed after GROUP BY and so can be used to constrain the result set to only those with aggregated values that match a certain predicate. Find the organizations with payroll less than $3200. SELECT org, sum(salary) payroll FROM salary_statistics }✗Incorrect WHERE payroll < 3200 GROUP BY org SELECT org, sum(salary) payroll FROM salary_statistics }✓ Correct GROUP BY org HAVING payroll < 3200 4
  • 5.
    SELECT Statement –ORDER BY Clause Find students ordered by merit position. SELECT * FROM result ORDER BY marks DESC result student marks A 25 B 56 C 82 D 25 E 39 5