SELECT03
SELECT03
of SQL language
grouping and aggregate
functions
Aggregate functions
2
Groupping – example
3
Groupping – HAVING clause
HAVING clause is used for selecting groups. It plays the same role for groups as WHERE
does for individual records.
In this clause a logical condition has to be defined. This condition applies to every group
separately, and if it returns TRUE, the group is appended to the result table. If it returns
FALSE, the group is rejected.
4
Groupping – HAVING clause – example
A query selecting information on how many books in every price (but greater than 10) there
are in a database but only if this quantity of books is greater than 1.
First, the query selects books whose prices are greater than 10…
books
book book …
_id _price
1 9 …
2 23 …
3 25 …
4 23 …
5 6 …
6 26 …
7 23 …
8 8 …
9 26 …
10 21 …
FROM books
WHERE book_price > 10
5
Groupping – HAVING clause – example, cont.
A query selecting information on how many books in every price (but greater than 10) there
are in a database but only if this quantity of books is greater than 1.
FROM books
WHERE book_price > 10
GROUP BY book_price
6
Groupping – HAVING clause – example, cont.
A query selecting information on how many books in every price (but greater than 10) there
are in a database but only if this quantity of books is greater than 1.
…and, finally, it chooses those groups which quantity is greater than 1 and selects columns.
books
book book … book book
_id _price _price _number
2 23 … 23 3
4 23 … 26 2
7 23 …
3 25 …
6 26 …
9 26 …
10 21 …
7
Groupping – the difference between COUNT(*) and COUNT(field)