PostgreSQL

Group By

The GROUP BY clause groups data with same values as specified. The SUM and COUNT aggregate functions are typically used to get the size of a group.

Syntax

SELECT <column> FROM <table> GROUP BY <column>;

with aggregate function:

SELECT <column>, <aggregate-function> 
FROM <table> 
GROUP BY <column>;

Example #1

SELECT hq, COUNT(*) FROM Companies GROUP BY hq;
Result from Example #1
HQ Count
United States 3
Canada 1

Group By Having

The HAVING clause acts as a filter for the GROUP BY clause.

Syntax

SELECT <column>, <aggregate-function> 
FROM <table> 
GROUP BY <column>
HAVING <condition>;

Example #2

SELECT hq, COUNT(*) 
FROM Companies 
GROUP BY hq
HAVING COUNT(*) > 0
ORDER BY hq;
Result from Example #2
HQ Count
Canada 1
United States 3