How do you use GROUP BY in PostgreSQL?

Answer

GROUP BY groups rows that have the same values in specified columns, typically used with aggregate functions to summarize data. SELECT department, COUNT(*), AVG(salary) FROM employees GROUP BY department;. All non-aggregate columns in SELECT must appear in GROUP BY. GROUP BY 1, 2 groups by the first and second SELECT columns (positional). GROUP BY ROLLUP(a, b) generates subtotals. GROUP BY CUBE(a, b) generates all combinations. GROUPING SETS allows specifying exactly which groupings to compute. Filter groups with HAVING. For counting distinct combinations: SELECT city, country, COUNT(*) FROM users GROUP BY city, country ORDER BY COUNT(*) DESC;.