COUNT
is an aggregation result. You can count all rows in a table, all rows that match certain criteria, etc. As an aggregation result, you can use it in the SELECT
clause, in the HAVING
clause, and in the ORDER BY
clause. (You cannot use it in the WHERE
clause, because the WHERE
clause deals with the data in the table rows. You need a HAVING
clause instead, which deals with aggregation results.)
SELECT clause / ORDER BY clause example
select
supplier_id,
case when count(*) < 20 then 'less then 20 orders'
when count(*) < 40 then 'less beteen 20 and 40 orders'
else '40 or more orders'
end as number_of_orders
from orders
where order_date >= date '2018-01-01'
group by supplier_id
order by count(*) desc;
HAVING clause example
select sex, count(*)
from members
group by sex
having count(*) > 20;