This tutorial will show you how to use the GROUP BY statement in SQL Server. Using GROUP BY allows you to arrange the rows specified in the clause. Think of it as an organizer that groups a column and removes any duplicates.It will make sense when you see an output, so let’s get started.

Setting Up

For this tutorial we will be using a table called Employees with nine employees. If you have not done so, create a table called Employees. For each employee we recorded their employee ID, first name, last name, hire date, manager ID, social security number, and salary. Look at the data shown in the two screenshots below to add data into the Employees table.

Notice how there are three ‘Ryu’ first names, keep note of this as it will change when we group them.

Now that we have a table to work with, we can create a query that will group the employees by their first name.

We will select the first names of each employee in the Employees table and then group the names to organize and remove any duplicates. We will first use the SELECT statement to specify that we want the FirstName column. After specifying the column we want to use, we must specify from what table the column is from, in this case, Employees. Finally we use the GROUP BY statement to group the FirstName column.

Run the query and your results should be the same as the screenshot below:

Earlier we had three instances of the first name ‘Ryu’ and now we have only one because of the GROUP BY statement. Removing duplicates is a perk of this statement because it wouldn’t make sense to group identical things together separately.

Thanks for reading and make sure to download the source files to get a better understanding of how the code works.

Download Source Files