This presentation contains:
Definition of the group by, having and order by clauses
Examples with tables of the group by, having and order by clauses
SQL queries for the group by, having and order by clauses
2. 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
3. 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
4. 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
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