PostgreSQL GROUP BY Clause
PostgreSQL GROUP BY Clause
The GROUP BY clause in PostgreSQL is used to group rows that have the same values in one or more columns and apply aggregate functions like COUNT, SUM, AVG, MAX, and MIN.
1️⃣ Why GROUP BY?
Suppose you have an orders table:
| id | user_id | amount | status |
|---|---|---|---|
| 1 | 1 | 500 | completed |
| 2 | 1 | 700 | completed |
| 3 | 2 | 300 | pending |
To calculate total amount per user, we use GROUP BY.
2️⃣ Basic GROUP BY Syntax
3️⃣ Simple GROUP BY Example
✔ Groups rows by user_id.
4️⃣ GROUP BY with SUM
5️⃣ GROUP BY with Multiple Columns
✔ Creates groups for each combination of columns.
6️⃣ GROUP BY with HAVING
HAVING filters groups, not rows.
7️⃣ GROUP BY with WHERE
✔ WHERE filters rows before grouping
✔ HAVING filters after grouping
8️⃣ GROUP BY with JOIN
9️⃣ Common Aggregate Functions
| Function | Description |
|---|---|
COUNT(*) |
Total rows |
SUM() |
Total value |
AVG() |
Average |
MAX() |
Highest |
MIN() |
Lowest |
🔟 Rules of GROUP BY
✔ Every selected column must be in GROUP BY or be an aggregate
✔ Aliases cannot be used in GROUP BY (use column name)
✔ GROUP BY comes after WHERE and before HAVING
1️⃣1️⃣ Common Errors & Fixes
❌ column must appear in GROUP BY clause
✔ Add column to GROUP BY or aggregate it
❌ using HAVING without GROUP BY
✔ Use WHERE instead
1️⃣2️⃣ Best Practices
✔ Use WHERE before GROUP BY for performance
✔ Index grouped columns on large tables
✔ Use HAVING only for aggregated conditions
✔ Keep GROUP BY minimal
