WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

SQL Server Β· Basic Β· question 12 of 100

What is the purpose of the GROUP BY clause in a SQL query?

πŸ“• Buy this interview preparation book: 100 SQL Server questions & answers β€” PDF + EPUB for $5

The GROUP BY clause is an essential part of SQL queries which allows the grouping of rows based on the values of one or more columns. The primary purpose of the GROUP BY clause is to aggregate data by applying various aggregate functions such as SUM, AVG, MAX, MIN, COUNT to the grouped rows.

The syntax of the GROUP BY clause is as follows:

SELECT column1, column2, aggregate_function(column3)
FROM table_name
GROUP BY column1, column2;

In this syntax, the SELECT statement lists the columns we want to retrieve, and the GROUP BY clause specifies the columns that we want to use for grouping the data. The aggregate function operates on the column, which is not included in the GROUP BY clause.

For example, let’s consider a table "Orders" with the following columns: OrderID, CustomerID, OrderDate, OrderAmount. To find the total revenue generated by each customer, we can use the following query:

SELECT CustomerID, SUM(OrderAmount) AS TotalRevenue
FROM Orders
GROUP BY CustomerID;

This query uses the SUM() function to add up all the order amounts for each customer, and the GROUP BY clause groups the rows based on the CustomerID column.

Another example is finding the number of orders placed by each customer in a given time period. To do this, we can use the COUNT() function as follows:

SELECT CustomerID, COUNT(OrderID) AS TotalOrders
FROM Orders
WHERE OrderDate BETWEEN '2021-01-01' AND '2021-03-31'
GROUP BY CustomerID;

This query counts the number of orders placed by each customer between 1st Jan and 31st March 2021, and groups the rows based on the CustomerID column.

In summary, the GROUP BY clause is used to group rows based on one or more columns and apply aggregate functions to generate summary information for each group.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic SQL Server interview β€” then scores it.
πŸ“ž Practice SQL Server β€” free 15 min
πŸ“• Buy this interview preparation book: 100 SQL Server questions & answers β€” PDF + EPUB for $5

All 100 SQL Server questions Β· All topics