100 Days of SQL

sql

Day 22 – SQL GROUP BY Statement

The SQL GROUP BY statement is used to group rows that have the same values in one or more columns, and perform aggregate functions on them.

The syntax for the GROUP BY statement is as follows:


SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)

In this syntax, column_name(s) refers to the column(s) that you want to group the results by, table_name refers to the table that you want to retrieve data from, and condition is an optional parameter that can be used to filter the results.

When you use the GROUP BY statement, the result set is divided into groups based on the values in the specified column(s). The aggregate functions (such as COUNT, SUM, AVG, MAX, and MIN) are then applied to each group, and the result is returned as a single row for each group.

For example, suppose you have a table called orders with columns customer_name, order_date, and order_amount. You could use the following query to group the orders by customer and calculate the total amount of orders for each customer:


SELECT customer_name, SUM(order_amount)
FROM orders
GROUP BY customer_name

This query would return a result set that shows the total order amount for each customer in the orders table.

Note that when you use the GROUP BY statement, all columns in the SELECT statement must either be included in the GROUP BY clause or be included in an aggregate function.