PostgreSQL GROUP BY
PostgreSQL GROUP BY clause is used to collect data from multiple records and then to group the identical or similar results. It is used with the PostgreSQL SELECT statement. It, however, does not have a mandatory existence with the PostgreSQL SELECT statement.
Syntax: To group the rows by values in multiple columns.
SELECT expressions FROM table_name GROUP BY columns;
Example 1:
Employment Table:
ID | STATE | RATE |
1 | A | 60 |
2 | B | 70 |
3 | C | 60 |
4 | D | 80 |
5 | E | 70 |
Query:
SELECT “RATE”
FROM “EMPLOYMENT”
GROUP BY “RATE”
ORDER BY “RATE”; |
Output:
RATE
60
70
80
Explanation:
The EMPLOYMENT is an already existing table from which we are retrieving unique employment rates using the GROUP BY clause.
Example 2:
Employment Table:
ID | STATE | RATE |
1 | A | 60 |
2 | B | 70 |
3 | C | 60 |
4 | D | 80 |
5 | E | 70 |
Query:
SELECT “RATE”, COUNT (“RATE”) AS “TOTAL COUNT” FROM “EMPLOYMENT” GROUP BY “RATE”; |
Output:
RATE TOTAL COUNT 60 2 70 2 80 1
Explanation:
The EMPLOYMENT is an already existing table from which we are retrieving the count of the occurrence of each unique employment rates using the GROUP BY clause.