Showing posts with label MariaDB Group By. Show all posts
Showing posts with label MariaDB Group By. Show all posts

Friday, 13 October 2023

MySQL Group By

The MySQL GROUP BY clause groups rows in a result set based on the values of one or more columns. It is often used with aggregate functions, such as SUM(), COUNT(), AVG(), MAX(), and MIN(), to summarize the data in each group.

The basic syntax for the GROUP BY clause is as follows:

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

The column_name(s) in the GROUP BY clause are the columns that you want to use to group the rows. The SELECT clause can include any columns from the table, but it must also include at least one of the columns from the GROUP BY clause.

Here is an example of a GROUP BY query:

SQL
SELECT country, COUNT(*) AS num_customers
FROM customers
GROUP BY country
ORDER BY num_customers DESC;

This query groups the rows in the customers table by the country column and counts the number of customers in each country. The results are returned in descending order by the number of customers.

You can also use the GROUP BY clause to group rows by multiple columns. To do this, simply list the columns in the GROUP BY clause in the order that you want to group them by.

Here is an example of a GROUP BY query that groups rows by two columns:

SQL
SELECT product_category, product_name, COUNT(*) AS num_orders
FROM orders
GROUP BY product_category, product_name
ORDER BY num_orders DESC;

This query groups the rows in the orders table by the product_category and product_name columns and counts the number of orders for each product category and product name. The results are returned in descending order by the number of orders.

The GROUP BY clause is a powerful tool that can be used to summarize and analyze data in MySQL. It is often used in conjunction with aggregate functions to produce meaningful insights from large datasets.