An important feature in MariaDB, and SQL in general, is the GROUP BY clause. This article explains the important features of the GROUP BY clause in MariaDB. This article explains you the syntax of the GROUP BY clause and its practical applications. Examples include using the aggregate functions, grouping by single and multiple columns, and using GROUP BY with HAVING clause.
GROUP BY Clause
The GROUP BY clause in MariaDB is used to group rows with similar values in the specified columns into grouped rows, such as "total" or "count" It is often used with aggregation functions such as COUNT(), SUM(), AVG(), MIN(), or MAX() to perform calculations on any of a group of rows.
Syntax:
SELECT col1, aggregate_function(col2) FROM table_name GROUP BY col1;
- SELECT Clause: It specifies the columns you want to retrieve from the table like col1.
- Aggregate Function: It is applied to the values in col2. Aggregate functions perform calculations on multiple values and return a single value. Examples of aggregate functions are SUM, COUNT, AVG, MIN, and MAX.
- FROM Clause: It specifies the table from which the data will be retrieved.
- GROUP BY Clause: It groups the result set by the specified column (col1).
Example: GROUP BY Clause
Let's look at how to use the GROUP BY clause by creating an example table and inserting the data into it.
Create Table
CREATE TABLE products (
product_id INT PRIMARY KEY,
product_name VARCHAR(100),
category VARCHAR(50),
unit_price DECIMAL(10, 2),
stock_quantity INT
);
Insert Data
INSERT INTO products VALUES
(1, 'Laptop', 'Electronics', 1200.00, 50),
(2, 'Smartphone', 'Electronics', 800.00, 100),
(3, 'Coffee Maker', 'Appliances', 50.00, 30),
(4, 'Backpack', 'Fashion', 40.00, 80),
(5, 'Desk Chair', 'Furniture', 150.00, 20);
Example 1: Using Aggregate Function SUM
Aggregate function SUM used to calculate the sum of values in a specified column. Lets see how to use the GROUP BY clause with the SUM function:
Syntax:
SELECT category, SUM(stock_quantity) AS total_stock FROM products GROUP BY category;
This query groups products by their categories and calculates the total stock quantity using the aggregate function SUM for each category. The output shows the total stock quantity for each category in the products table.
Output:
GROUP BY ClauseExample 2: Grouping by Multiple Columns
Grouping by multiple column means that the result set is organized into groups on unique combinations of values in more than one column. When we will use the GROUP BY clause with the multiple columns , the query groups the rows that have same values into a single result row.
SELECT category, unit_price, AVG(stock_quantity) AS avg_quantity FROM products GROUP BY category, unit_price;
This query groups products by their categories and calculates the average unit price using the aggregate function AVG for each category. The output of this query will be the three columns: category, unit_price and stock_quantity that contain the average stock quantity for each unique combination of category and unit_price in the products table.
Output:
GROUP BY ClauseExample 3: Grouping by a Single Column Number
Grouping by a single column means that you want to group the rows based on the distinct values in that particular column. The result contains the set of rows where each row represents a unique value in the specified column.
SELECT category, COUNT(*) AS product_count FROM products GROUP BY category;
This query counts the number of products in each category. The output shows the count of products for each unique category.
Output:
GROUP BY ClauseExample 4: Using Aggregate Function MAX
Aggregate function MAX used to calculate the maximum values in a specified column. Lets see how to use the GROUP BY clause with the MAX function:
SELECT category, MAX(unit_price) AS max_price FROM products GROUP BY category;
This query identifies the products with the maximum unit price in each category. The out contains the maximum unit price for each category in the products table. In this example, for the Appliances the maximum unit price is 50, for Electronics it is 1200, for Fashion it is 40 and for Furniture it is 150.
Output:
GROUP BY ClauseExample 5: Using Aggregate Function SUM.
SELECT category, SUM(unit_price * stock_quantity) AS total_value FROM products GROUP BY category;
This query calculates the total value of stock for each category by multiplying unit price with stock quantity. The output shows the total value for each unique category in the products table.
Output:
GROUP BY ClauseExample 6: Total Stock Value for the Entire Inventory Using SUM Aggregate Function.
SELECT SUM(unit_price * stock_quantity) AS total_inventory_value FROM products;
This query calculates the total value of the entire inventory by summing the product of unit price and stock quantity for all products.
Output:
GROUP BY ClauseExample 7: Filtering Groups with HAVING Clause.
Having clause is used to filter the results based on a condition after grouping. Let's see an example to filter the groups using the HAVING clause with GROUP BY clause:
SELECT category, AVG(unit_price) AS avg_price FROM products GROUP BY category HAVING AVG(unit_price) > 100;
This query groups products by category and calculates the average unit price for each category, but it only includes categories where the average unit price is greater than 100. In this example, the Electronics has an average price 1000 and Furniture has 200.
Output:
GROUP BY ClauseExample 8: Grouping by Expression
Grouping by expression means the ability to group data based on the result of an expression or calculation, rather than directly on a column. This is often achieved using a combination of functions and operators within the GROUP BY clause. It is useful when you want to categorize your data into different groups based on some criteria before performing the aggregate functions.
SELECT
category,
CASE
WHEN stock_quantity > 50 THEN 'High Stock'
WHEN stock_quantity <= 50 AND stock_quantity > 0 THEN 'Low Stock'
ELSE 'Out of Stock'
END AS stock_status,
COUNT(*) AS product_count
FROM products
GROUP BY category, stock_status;
This query groups products by category and a custom expression stock_status, categorizing products based on their stock quantity. It then counts the number of products in each category and stock status combination. The output shows the count of products for each unique combination of category and stock_status.
Output:
GROUP BY ClauseConclusion
The GROUP BY clause in MariaDB is a fundamental feature. It is effective and helps to organize and evaluate data easily. In this guide, we had explored the syntax of the GROUP BY clause and also examined its practical applications through various examples. Developers can accurately perform aggregate calculations by grouping rows. They can obtain totals, counts, averages, and identify max/min values.
Similar Reads
MySQL Group By Clause
In MySQL, the GROUP BY clause is a powerful tool for grouping rows with the same values into summary rows, enabling efficient data analysis. It is often used with aggregate functions like SUM, COUNT, AVG, MIN, and MAX to perform calculations on grouped data. In this article, We will learn about the
5 min read
SQLite Group By Clause
SQLite is a server-less database engine and it is written in C programming language. It is developed by D. Richard Hipp in the year 2000. The main moto for developing SQLite is to escape from using complex database engines like MYSQL etc. It has become one of the most popular database engines as we
6 min read
MariaDB Having Clause
The HAVING clause is crucial for filtering and aggregating data in database queries. The MariaDB HAVING clause syntax is outlined. It breaks down into components. These include the SELECT clause, aggregate functions, and the GROUP BY clause. The SELECT clause specifies columns. Aggregate functions p
6 min read
PL/SQL GROUP BY Clause
The GROUP BY clause in PL/SQL is a powerful tool used to organize data into aggregated groups based on one or more columns. It is essential for performing summary operations on large datasets, enabling efficient data analysis by grouping rows that share common values.In this article, We will learn a
7 min read
PostgreSQL - GROUP BY clause
The GROUP BY clause in PostgreSQL is an essential tool that allows us to group rows that share the same values in one or more columns. This powerful functionality is commonly used to perform aggregate calculations such as SUM(), COUNT(), AVG(), and more, enabling us to summarize data efficiently. In
4 min read
JPA - Criteria GROUP BY Clause
JPA in Java can be called the Java Persistence API. It provides the Criteria API as a programming mechanism for creating queries dynamically. One of these important features is the GROUP BY clause which allows developers to group query results based on specific criteria. GROUP BY ClauseThe Group BY
7 min read
Pandas Group by Multiple Columns
Grouping by multiple columns in pandas allows you to perform complex data analysis by segmenting your dataset based on more than one variable. Let's learn how to group by multiple columns in Pandas. Grouping Data by Multiple ColumnsThe groupby() function in Pandas is the primary method used to group
5 min read
SQL COUNT() with GROUP BY Clause
The SQL COUNT() function is a powerful tool used to count the number of rows in a dataset. When combined with the GROUP BY clause, it helps group data by specific attributes and count rows within each group. This is particularly useful for summarising data and generating insights.In this article, we
3 min read
MariaDB Drop View
MariaDB is an open-source relational database management system that is based on SQL(Structured query language). It is an improved version of MySQL and has various features, security, and performance when compared to MySQL. This database is open source with a strong community that can be trusted in
4 min read
MariaDB COUNT Functions
MariaDB is an open-source and relational database to operates available data and displays the required value. the count, max, min, and other functions used to get particular information or count of the database data. the mariaDB count() function is used to get a COUNT of the row or available informa
4 min read