100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
HomeBlogSQL Aggregations and GROUP BY Explained
Data Science

SQL Aggregations and GROUP BY Explained

SV

SkillVeris Team

Data Science Team

Jun 13, 2025 10 min read
Share:
SQL Aggregations and GROUP BY Explained
Key Takeaway

SQL aggregation functions summarize many rows into a single value, and GROUP BY splits rows into groups so each group gets its own summary.

In this guide, you'll learn:

  • The core aggregates are COUNT, SUM, AVG, MIN, and MAX, each ignoring NULL values except COUNT(*).
  • GROUP BY collapses rows sharing the same column values into one row per group.
  • WHERE filters rows before grouping; HAVING filters groups after aggregation.
  • Every non-aggregated column in the SELECT list must appear in GROUP BY.

1What Are SQL Aggregations and GROUP BY?

SQL aggregation functions take many rows and reduce them to a single summary value, and GROUP BY divides rows into groups so each group produces its own summary. Together they answer questions like total sales per region, average order value per customer, or how many orders each product received.

Without GROUP BY, an aggregate like SUM collapses the entire table into one number. Add GROUP BY, and you get one number per group instead. This pairing is the foundation of almost every report and dashboard built on a database.

2The Core Aggregate Functions

Five aggregate functions cover the vast majority of analytical needs. Each takes a column and returns one value that summarizes all the rows in scope. Crucially, all of them except COUNT(*) skip NULL values, which is a frequent source of surprise.

COUNT reports how many rows or non-NULL values exist, SUM adds numeric values, AVG computes the mean, and MIN and MAX return the smallest and largest. You combine them freely in a single SELECT to build a compact summary.

  • COUNT(*) # number of rows, including those with NULLs
  • COUNT(email) # number of rows where email is not NULL
  • SUM(total) # sum of the total column, ignoring NULLs
  • AVG(price) # mean price of non-NULL rows
  • MIN(created_at), MAX(created_at) # earliest and latest timestamps

3How GROUP BY Works

GROUP BY collapses all rows that share the same value in the grouped columns into a single output row. The database sorts or hashes rows into buckets by the grouping key, then applies each aggregate function within each bucket. The result has one row per distinct group.

For example, grouping an orders table by customer_id and selecting SUM(total) returns each customer's total spend. You can group by multiple columns to create finer buckets, such as region and month together, which produces one row per region-month combination.

  • SELECT customer_id, SUM(total) AS spend
  • FROM orders
  • GROUP BY customer_id;
  • # One row per customer, with their total spend.

4WHERE vs HAVING

WHERE and HAVING both filter, but at different stages. WHERE filters individual rows before grouping happens, so it cannot reference aggregate results. HAVING filters entire groups after aggregation, so it can test aggregate values like SUM or COUNT.

A common pattern combines both: use WHERE to narrow the rows that enter the grouping, then HAVING to keep only groups meeting a threshold. For instance, filter to this year's orders with WHERE, group by customer, then keep only customers whose total exceeds a limit with HAVING.

💡Filter Early

Put every row-level condition in WHERE, not HAVING. WHERE runs before grouping and shrinks the data early, which is faster than aggregating everything and discarding groups afterward.

5Logical Order of Execution

SQL clauses do not run in the order they are written. Understanding the logical execution order explains why WHERE cannot see aggregates and why column aliases sometimes fail in certain clauses. The database processes FROM first and SELECT nearly last.

The logical sequence is: FROM and JOIN gather rows, WHERE filters them, GROUP BY buckets them, aggregates and HAVING run on those buckets, then SELECT chooses columns, and finally ORDER BY sorts and LIMIT trims. This is why HAVING can reference SUM but WHERE cannot.

  • FROM / JOIN # gather and combine source rows
  • WHERE # filter individual rows
  • GROUP BY # bucket rows into groups
  • HAVING # filter groups on aggregate results
  • SELECT # compute columns and aggregates
  • ORDER BY / LIMIT # sort and trim the final output

6The GROUP BY Column Rule

Every column in the SELECT list must either be aggregated or listed in GROUP BY. If you select a column that is neither, the result is ambiguous because the group might contain many different values for it, and databases handle this differently.

Strict databases like PostgreSQL and SQL Server reject such queries outright. MySQL historically allowed them and returned an arbitrary value, which quietly produced misleading results. Always include non-aggregated select columns in GROUP BY to stay correct and portable.

DISTINCT vs GROUP BY

SELECT DISTINCT and GROUP BY with no aggregate both remove duplicates, but GROUP BY is intended for producing summaries. Reach for DISTINCT when you only want unique rows and for GROUP BY when you want per-group calculations.

7Common Mistakes to Avoid

Aggregation bugs are often silent — the query runs but the numbers are wrong. Watch for these.

  • Selecting a non-aggregated column that is missing from GROUP BY, giving arbitrary values on lenient databases.
  • Using WHERE to filter an aggregate — that condition belongs in HAVING.
  • Forgetting that AVG and SUM ignore NULLs, which can skew results versus what you expect.
  • Confusing COUNT(*) with COUNT(column); the latter skips NULLs and can undercount.
  • Aggregating over a one-to-many join without realizing rows were duplicated, inflating SUM and COUNT.

⚠️Joins Inflate Aggregates

If you aggregate after joining a one-to-many relationship, each row on the one side is duplicated, so SUM and COUNT come out too high. Aggregate in a subquery before joining, or use COUNT(DISTINCT ...).

8Key Takeaways

Aggregations and GROUP BY power nearly every summary query you will write.

  • Aggregate functions reduce many rows to one value; GROUP BY produces one summary per group.
  • COUNT, SUM, AVG, MIN, and MAX are the core five; all but COUNT(*) skip NULLs.
  • WHERE filters rows before grouping; HAVING filters groups after aggregation.
  • Every non-aggregated SELECT column must be in GROUP BY.
  • Beware one-to-many joins inflating aggregate totals.

9Frequently Asked Questions

Q: What is the difference between WHERE and HAVING? A: WHERE filters individual rows before grouping and cannot reference aggregate functions, while HAVING filters whole groups after aggregation and can test values like SUM or COUNT. Use WHERE for row conditions and HAVING for conditions on group summaries.

Q: What is the difference between COUNT(*) and COUNT(column)? A: COUNT(*) counts every row regardless of NULLs, while COUNT(column) counts only rows where that column is not NULL. If a column contains missing values, the two will return different numbers, so choose deliberately.

Q: Why do I get an error about a column not being in GROUP BY? A: Strict databases require every non-aggregated column in the SELECT list to appear in GROUP BY, because otherwise the value is ambiguous within a group. Add the column to GROUP BY, or wrap it in an aggregate function like MAX.

Q: Do aggregate functions include NULL values? A: With the exception of COUNT(*), aggregate functions ignore NULLs entirely. AVG divides by the count of non-NULL values, and SUM skips them, which can produce results that differ from a naive expectation if your data has missing values.

📄

Get The Print Version

Download a PDF of this article for offline reading.

About the Publisher

SV

SkillVeris Team

Data Science Team

Our data team shares real-world analytics, ML, and SQL insights grounded in industry practice.

View all posts

Never miss an update

Get the latest tutorials and guides delivered to your inbox.

No spam. Unsubscribe anytime.

Frequently Asked Questions

21 categories · pick one to explore

Does SkillVeris have a tech blog, and what does it cover?
Yes, the SkillVeris blog has over 500 articles covering AI and machine learning, programming, web development, DevOps, cloud, security, databases and career guidance. Articles are practical and answer-first, and many use the Learn Through Hobbies approach, teaching technical concepts through cricket, music, gaming or cooking analogies. Everything is free to read.
What is the SkillVeris tech glossary and how big is it?
The SkillVeris glossary is a free reference of roughly 2,000-plus technology terms, each with a clear plain-language definition. It spans AI, programming, web, DevOps, cloud, security and database vocabulary, so whenever a lesson, article or job description uses jargon you do not recognise, the glossary gives you a fast, reliable answer.
Are the developer cheat sheets on SkillVeris free to download?
The cheat sheets are completely free to use, like everything else on SkillVeris. Each sheet condenses a language or tool into its essential syntax, commands and patterns for quick reference while coding. They are designed for rapid lookup during real work, complementing the deeper explanations found in study notes and courses.
Which programming references and cheat sheets are available?
Cheat sheets cover the platform's main domains, including programming languages, AI and ML tooling, web development, DevOps, cloud, security and databases, matching the topics of the 37 live courses. Each sheet lists related reading links and hashtags, so you can jump from a quick reference into fuller study notes or blog articles.
How do I find the meaning of a technical term quickly?
Search the SkillVeris glossary, which holds around 2,000-plus terms with concise, plain-language definitions. Each entry gets to the point in its first sentence, then links to related reading like blog posts or study notes for deeper context. It is faster and more consistent than sifting through scattered search results.
Is the SkillVeris blog good for beginners learning to code?
Yes, many blog articles are written specifically for beginners, and the Learn Through Hobbies style makes them unusually approachable: you might learn Python concepts through cricket or understand APIs through cooking. With 500-plus articles across skill levels, beginners can start with fundamentals and keep reading as they advance, entirely free.
Can cheat sheets replace full courses for learning a language?
No, cheat sheets are references, not teaching tools; they assume you already understand the concepts and just need syntax or commands fast. To actually learn a language, take a structured SkillVeris course with its 24–40 lessons and assessments, then keep the cheat sheet beside you while practising in Code Lab.
How often are new blog articles published on SkillVeris?
The blog grows regularly and already exceeds 500 articles, with new posts added as courses launch and technologies evolve. Topics track the platform's catalogue across AI, programming, web development, DevOps, cloud and security, so checking the Blog section periodically surfaces fresh tutorials, explainers and career-focused pieces, all free to read.
Does the glossary cover AI and machine learning terms?
Yes, AI and machine learning vocabulary is a major part of the roughly 2,000-plus term glossary, covering everything from foundational terms to modern concepts around LLMs, RAG and MLOps. Definitions are plain-language and answer-first, which helps when dense AI papers or course lessons throw unfamiliar jargon at you.
Are there cheat sheets for interview preparation?
Cheat sheets work well as interview-day refreshers because they compress syntax, commands and key concepts into scannable references. For dedicated preparation, combine them with the SkillVeris interview questions feature, which includes readiness scoring, plus study notes for depth. Reviewing a relevant cheat sheet just before an interview steadies recall under pressure.
Can I read the tech blog without signing up?
Yes, the blog is freely readable, and SkillVeris never charges for content. All 500-plus articles are open, covering tutorials, concept explainers and career advice. Creating a free account adds value elsewhere on the platform, like course progress tracking and certificates, but reading the blog requires no commitment at all.
How is the SkillVeris glossary different from Wikipedia?
The glossary is purpose-built for learners: definitions are short, plain-language and answer-first, sized for a quick lookup mid-lesson rather than a deep encyclopedic read. Entries also cross-link to related SkillVeris study notes, blog posts and courses, so a definition becomes a doorway into structured learning instead of a dead end.
Do blog articles use the Learn Through Hobbies method?
Many blog articles teach technical topics through hobby analogies, a hallmark of the SkillVeris blog, so you will find articles explaining programming through cricket, machine learning through music, or system design through cooking. The analogy is the teaching device; the article still delivers the real technical concept underneath.
Where can I find quick programming references while coding?
Open the SkillVeris cheat sheets, which are built exactly for that moment: compact, scannable references for syntax, commands and common patterns across languages and tools. Keep the relevant sheet in a browser tab while you work in Code Lab or your own editor, and dip into the glossary for terminology.
Is there a glossary entry for terms I meet in job descriptions?
Very likely yes, with roughly 2,000-plus terms across AI, programming, web, DevOps, cloud, security and databases, the glossary covers most jargon that appears in tech job descriptions. Decoding a listing this way helps you judge role fit honestly and prepares you to discuss those terms in interviews.
Are the blog articles written for the Indian tech audience?
The blog serves Indian learners plus a worldwide audience. Content stays globally relevant while acknowledging realities that matter in India, such as free access being essential for students and freshers, and career guidance that connects naturally to the SkillVeris jobs portal, which aggregates roles across India, UK, USA, Germany and Remote.
Can I suggest a topic for the blog or glossary?
SkillVeris content grows in response to what learners need, so feedback is welcome through the platform's support channels. If a term is missing from the glossary or a topic deserves an article, telling the team helps prioritise it. Meanwhile, the AI Mentor can answer the question immediately, 24/7, at any depth.
Do cheat sheets and glossary entries link to deeper learning?
Yes, every cheat sheet and glossary entry carries related reading links into study notes, blog articles and courses, plus concept hashtags for discovering similar content. This cross-linking means a thirty-second lookup can smoothly become a structured learning session whenever you decide you want more than a quick answer.
What makes SkillVeris programming references trustworthy?
The references are written to strict internal quality standards, kept consistent with the platform's 37 live courses, and never padded with invented statistics or hype. Definitions and cheat sheets are reviewed against the same content contracts that govern courses, and the answer-first style makes any inaccuracy easy to spot and correct.
How do the blog, glossary and cheat sheets fit into my learning routine?
Use them as satellites around your main course: read blog articles for context and motivation, hit the glossary the instant jargon appears, and keep cheat sheets open while coding. Together with study notes, Code Lab and the 24/7 AI Mentor, they turn passive reading into a complete, free learning system.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse