Yogesh Chauhan's Blog

SQL GROUP BY Statement

in SQL/MySQL on September 4, 2019

SQL GROUP BY Statement

As per the name SQL GROUP BY Statement groups all the rows with same values. For example, people in each country, students in each class etc.

There are 5 most used aggregate functions in SQL: AVG,COUNT, MIN, MAX, SUM. This GROUP BY keyword often used with those aggregate functions to group the result set. Let’s take a look at the syntax:

SELECT column(s)
FROM table WHERE condition
GROUP BY column(s)
ORDER BY column(s);

It’s like any other syntax where you select the columns from table and add a condition to it. In this query we need to add GROUP BY keyword to combine those rows and give us one result set.

Let’s take a look at the example.

SELECT COUNT(CustomerID), Country
FROM customers
GROUP BY Country;

In the example query above, we are counting customers in each country from the table customers. If we remove the keyword, GROUP BY then the query will give us the total number of customers with the name of first country in the table. You can see the results in the DEMO. I’ve included it for comparison purpose only. 

We can use the GROUP BY keyword with 2 or more tables with JOIN keyword as well. Let’s take a look at that kind of example. 

SELECT merchants.MerchantName,COUNT(orders.OrderID) AS NumberOfOrders FROM orders
LEFT JOIN merchants ON orders.MerchantID = merchants.MerchantID
GROUP BY MerchantName;

In the query above, we are selecting merchant names from table merchants and then counting orders from the table order applying LEFT JOIN ot both the tables. So the query above counts orders per merchants because of the keyword GROUP BY.

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
The Drupal flowDrupalConditional operator in JavaScript (aka ternary operator)JavaScriptA short basic guide on states in ReactReactHow to change the Login Logo in WordPress?WordPressPHP Login System using PDO Part 2: Login using Email or UsernamePHPList of social media icon logo color codes in HEXMiscellaneous