SQL Group By - How to use it

SQL Group By – How to use it

The SQL Group By clause is very important and is always tested by employers during an interview. That’s why it is primordial for you to understand it and being able to apply it.

In this article we will look at what the Group By clause does, and how you can use it to create groups.

SQL Group By – The theory

Let’s take a look at the following table:

SQL Group By - How to use it Goal

You can see that the customer name is repeated multiple times since one line represent one item sold. It’s perfectly fine until someone ask questions such as: “How much did each customer spend?”, or “What’s the average item value for each customer?” That’s when the need for grouping lines together arises.

Instead of keeping individual records, the Group By clause will allow you to create groups. That means you will have only one line representing each group.

Since you can have multiple values for each group, you will also need to summarize them by either using SUM, AVG, COUNT, or another aggregate function.

SQL Group By - How to use it process

Group BY Syntax

The Group By clause will be at the bottom, after the WHERE clause, and your aggregate function will be in your select statement. Here’s an example:

SQL Group By - How to use it - example

As you can see, we end up with the Item AVG Sales Price for each customer.

You can also use more than one column in your GROUP BY clause as follow:


  • The Group By clause lets you group individual records together.
  • You need to use an aggregate function with the Group By clause.
  • All the columns that are not aggregated needs to be grouped.
  • You can group by multiple columns.

2 thoughts on “SQL Group By – How to use it”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.