Skip to main content

Command Palette

Search for a command to run...

๐Ÿ“Š PostgreSQL โ€“ Aggregating and Grouping

Updated
โ€ข4 min read
M

As a former 3D Animator with more than 12 years of experience, I have always been fascinated by the intersection of technology and creativity. That's why I recently shifted my career towards MERN stack development and software engineering, where I have been serving since 2021.

With my background in 3D animation, I bring a unique perspective to software development, combining creativity and technical expertise to build innovative and visually engaging applications. I have a passion for learning and staying up-to-date with the latest technologies and best practices, and I enjoy collaborating with cross-functional teams to solve complex problems and create seamless user experiences.

In my current role as a MERN stack developer, I have been responsible for developing and implementing web applications using MongoDB, Express, React, and Node.js. I have also gained experience in Agile development methodologies, version control with Git, and cloud-based deployment using platforms like Heroku and AWS.

I am committed to delivering high-quality work that meets the needs of both clients and end-users, and I am always seeking new challenges and opportunities to grow both personally and professionally.

So far in this course, every query weโ€™ve written has done one simple thing:

๐Ÿ‘‰ It fetched rows exactly as they exist in the database.

For example:

SELECT * FROM users;

This simply returns all rows.

But in real-world applications, we usually donโ€™t just want raw rows.

We want insights like:

  • How many users are there?

  • What is the average salary?

  • How many orders did each user place?

  • What is the total revenue?

To answer questions like these, we use:

  • Aggregation

  • Grouping

Letโ€™s break them down step by step.


๐Ÿงฎ 1๏ธโƒฃ Aggregation โ€“ Reducing Many Values Into One

Aggregation means:

Taking many values and reducing them into a single summarized value.

Think of it like calculating the total marks of a class.


๐Ÿ”น Example Table: orders

id amount
1 100
2 200
3 300

If we want the total sales:

SELECT SUM(amount) FROM orders;

Result:

600

We had 3 rows.
Now we have 1 single summarized value.

That is aggregation.


๐Ÿ”น Common Aggregate Functions

Function What It Does
COUNT() Counts rows
SUM() Adds values
AVG() Calculates average
MAX() Finds highest value
MIN() Finds lowest value

๐Ÿ”ธ Example: Count total users

SELECT COUNT(*) FROM users;

๐Ÿ”ธ Example: Find average salary

SELECT AVG(salary) FROM employees;

๐Ÿง  Key Idea

Aggregation:

Many values โžœ One single value


๐Ÿงฉ 2๏ธโƒฃ GROUP BY โ€“ Dividing Rows Into Categories

Now comes the powerful concept: GROUP BY

GROUP BY means:

Divide rows into groups based on a column.


๐ŸŽ“ Real-Life Example

Imagine a students table:

name city
Ali Karachi
Ahmed Lahore
Sana Karachi
Bilal Lahore
Fatima Karachi

Now we ask:

How many students are from each city?

We need to group by city first.

SELECT city, COUNT(*)
FROM students
GROUP BY city;

Result:

city count
Karachi 3
Lahore 2

Hereโ€™s what happened internally:

  1. PostgreSQL looked at all rows.

  2. It divided them into groups based on city.

  3. Then it applied COUNT to each group.


๐Ÿง  Important Mental Model

Think of GROUP BY like sorting students into classrooms by city.

Then aggregation calculates something for each classroom.


๐Ÿ“Œ General Pattern

SELECT column_name, AGG_FUNCTION(column)
FROM table_name
GROUP BY column_name;

๐Ÿšจ Common Beginner Mistake

This query will cause an error:

SELECT city, name
FROM students
GROUP BY city;

Why?

Because when you use GROUP BY:

  • Every selected column must either:

    • Be included in GROUP BY

    • OR be inside an aggregate function

Correct version:

SELECT city, COUNT(*)
FROM students
GROUP BY city;

๐Ÿงฎ Aggregation + Grouping Together

Now letโ€™s combine both concepts.

Example Table: orders

id user_id amount
1 1 100
2 1 200
3 2 150

Question:

How much did each user spend in total?

SELECT user_id, SUM(amount)
FROM orders
GROUP BY user_id;

Result:

user_id sum
1 300
2 150

This is how real business reporting works.


๐Ÿ”Ž Difference Between GROUP BY and Aggregation

Concept Purpose
Aggregation Reduce many values into one
GROUP BY Divide rows into categories

Together, they allow powerful data summaries.


๐Ÿข Real-World Use Cases

  • Total revenue per month

  • Number of users per country

  • Average rating per product

  • Total orders per customer

  • Highest salary per department


๐ŸŽฏ Final Summary

Aggregation:

Reduces many values into one.

GROUP BY:

Divides rows into groups before applying aggregation.

Together:

They turn raw data into meaningful insights.


๐Ÿง  Practice Exercises

  1. Count employees per department.

  2. Find average salary per city.

  3. Find highest order amount per user.

  4. Count orders per month.