EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials MySQL Tutorial MySQL GROUP BY Count
Secondary Sidebar
MySQL Tutorial
  • Queries
    • MySQL Queries
    • MySQL Query Commands
    • SELECT in MySQL
    • MySQL INSERT IGNORE
    • MySQL having
    • ORDER BY in MySQL
    • MySQL Cheat Sheet
    • MySQL ORDER BY Random
    • MySQL ORDER BY DESC
    • MySQL GROUP BY
    • MySQL GROUP BY Count
    • MySQL GROUP BY month
    • MySQL WHERE Clause
    • MySQL WITH
    • MySQL FETCH
    • MySQL DDL
    • MySQL DML
    • MySQL WHERE IN Array
    • MySQL Fetch Array
    • MySQL ISNULL
    • MySQL Index Types
    • Mysql? Export Schema
    • Amazon RDS for MySQL
    • MySQL greatest
  • Basic
    • MySQL floor
    • MySQL DESCRIBE table
    • MySQL encryption
    • Introduction to MySQL
    • Is SQL Server a Database?
    • What is MySQL
    • Is MySQL Programming Language
    • MySQL Server
    • MySQL AB
    • MySQL Community Server
    • How To Install MySQL
    • MySQL Versions
    • MySQL OpenSource
    • MySQL GUI Tools
    • MySQL Grant
    • MySQL Error 1064
    • MySQL Drop Database
    • MySQL not equal
    • MySQL SELECT INTO Variable
    • MySQL Commands
    • MySQL Operators
    • What is MySQL Schema
    • Wildcards in MySQL
    • MySQL Constraints
    • MySQL Administration
    • MySQL Data Type
    • MYSQL COMMIT
    • MySQL FORMAT
    • Timestamp to Date in MySQL
    • MySQL DATEDIFF
    • MySQL?Incremental Backup
    • MySQL JSON Data Type
    • MySQL ENUM
    • MySQL Default Port
    • Cheat Sheet MySQL
  • Database
    • What is Data Modeling
    • What is Data Processing
    • DBMS Architecture
    • DBMS Keys
    • Careers in Database Administration
    • What is MySQL Database
    • MySQL Relational Database
    • How to Connect Database to MySQL
    • MySQL Database Repair
    • RDBMS Interview Questions
    • DBMS Interview Questions
  • Functions
    • MySQL Function
    • MySQL Aggregate Function
    • MySQL String functions
    • MySQL Date Functions
    • MySQL Window Functions
    • MySQL Math Functions
    • MySQL Boolean
    • Cursor in MySQL
    • Condition in MySQL
    • MySQL BETWEEN
    • Insert in MySQL
    • MySQL IFNULL()
    • MySQL TIMESTAMPDIFF()
    • MySQL COALESCE()
    • MySQL count()
    • MIN() in MySQL
    • MySQL Numeric
    • MySQL field()
    • MySQL FIND_IN_SET()
    • MySQL avg()
    • MySQL MAX() Function
    • MySQL BIN()
    • MySQL Concat
    • MySQL DECODE()
    • MySQL REGEXP_REPLACE()
    • MySQL Asynchronous
    • MySQL innodb_buffer_pool_size
    • MySQL key_buffer_size
    • MySQL TRUNCATE()
    • MySQL ROW_NUMBER()
    • NOT in MySQL
    • MySQL IN Operator
    • LIKE in MySQL
    • ANY in MySQL
    • MySQL NOT IN
    • MySQL CHECK Constraint
    • MySQL DISTINCT
    • MySQL ALL
    • MySQL Union
    • MySQL UNION ALL
    • MySQL EXISTS
    • MySQL ON DELETE CASCADE
    • MySQL REGEXP
    • MySQL Index
    • MySQL Add Index
    • MySQL REINDEX
    • MySQL UNIQUE INDEX
    • MySQL Clustered Index
    • MySQL? InnoDB Cluster
    • Table in MySQL
    • ALTER TABLE MySQL
    • MySQL Temporary Table
    • MySQL Clone Table
    • MySQL Repair Table
    • MySQL Lock Table
    • MySQL Optimize Table
    • TRUNCATE TABLE MySQL
    • MySQL Table Dump
    • MySQL Update Set
    • MySQL ALTER TABLE Add Column
    • MySQL RANK()
    • MySQL CTE
    • MySQL LAG()
    • MySQL GROUP_CONCAT()
    • MySQL EXTRACT()
    • MySQL REPLACE
    • MySQL AUTO_INCREMENT
    • MySQL SYSDATE()
    • MySQL NULLIF()
    • MySQL Substring
    • MySQL SUBSTRING_INDEX()
    • MySQL LOWERCASE
    • MySQL Row
    • MySQL NOW
    • MySQL CEIL
    • MySQL Alias
    • MySQL Trigger
    • MySQL SHOW Triggers
    • MySQL UPDATE Trigger
    • MySQL DELETE Trigger
    • MySQL AFTER UPDATE Trigger
    • MySQL Stored Procedure
    • ROLLUP in MySQL
    • MySQL? INSTR()
    • MySQL Subquery
    • MySQL Timestamp
    • MySQL? Hour()
    • MySQL MOD()
    • MySQL DATE_FORMAT()
    • ALTER Column in MySQL
    • MySQL Rename Column
    • MySQL Interval
    • MySQL CURDATE
    • MySQL BIT
    • MySQL Binlog
    • MySQL Average
    • MySQL TEXT
    • MySQL SHOW
    • MySQL Offset
    • MySQL Timezone
    • mysql_real_escape_string
    • MySQL Datetime
    • MySQL DATE_SUB()
    • MySQL FULLTEXT
    • MySQL DATE_ADD()
    • MySQL sum()
    • MySQL Merge
    • MySQL BigInt
    • MySQL ROUND
    • MySQL VARCHAR
    • MySQL Decimal
    • MySQL Limit
    • MySQL today()
    • MySQL WEEKDAY
    • MySQL Split
    • MySQL Create Function
    • MySQL BLOB
    • MySQL encode()
    • MySQL Primary Key
    • MySQL Foreign Key
    • Unique Key in MySQL
    • MySQL Drop Foreign Key
    • MySQL DROP TRIGGER
    • MYSQL Database
    • Delete Database MySQL
    • MySQL Root
    • MySQL Root Password
    • MySQL Client
    • MySQL Users
    • MySQL?User Permissions
    • MySQL add user
    • MySQL List User
    • MySQL Show Users
    • MySQL User Password
    • MySQL?Cardinality
    • MySQL Workbench
    • MySQL Backup
    • MySQL REVOKE
    • MySQL Dump
    • MySQL Cluster
    • MySQL Partitioning
    • MySQL Full Text Search
    • MySQL Admin Tool
    • MySQL Export Database
    • MySQL Export to CSV
  • Joins
    • Joins in MySQL
    • MySQL Outer Join
    • Left Outer Join in MySQL
    • MySQL Self Join
    • Natural Join in MySQL
    • MySQL DELETE JOIN
    • MySQL Update Join
    • MySQL Cross Join
  • Advanced
    • MySQL Formatter
    • MySQL TINYINT
    • MySQL Grant All Privileges
    • MySQL DROP TABLE
    • MySQL rename database
    • MySQL Flush Privileges
    • MySQL super Privilege
    • MySQL Character Set
    • MySQL Log File
    • MySQL Flush Log
    • Grant Privileges MySQL
    • MySQL WHILE LOOP
    • IF Statement in MySQL
    • MySQL CASE Statement
    • MySQL IF Function
    • MySQL IF EXISTS
    • MySQL UUID
    • Views in MySQL
    • MySQL Replication
    • MySQL Partition
    • Toad for MySQL
    • Navicat for MySQL
    • MySQL AES_Encrypt
    • MySQL Performance Tuning
    • MySQL Transaction
    • MySQL? sort_buffer_size
    • MySQL? Sync
    • MySQL? Query Cache
    • MySQL Collation
    • MySQL ODBC Driver
    • MySQL Partitioning
    • MySQL InnoDB
    • MySQL Float vs Decimal
    • MySQL Union vs Union All
  • Interview Questions
    • MySQL Interview Questions

Related Courses

MS SQL Certification Courses

Oracle Certification Courses

PL/SQL Certification Courses

MySQL GROUP BY Count

By Aanchal SharmaAanchal Sharma

MySQL GROUP BY Count

Introduction to MySQL GROUP BY Count

MySQL GROUP BY Count is a MySQL query that is responsible to show the grouping of rows on the basis of column values along with the aggregate function Count. Basically, the GROUP BY clause forms a cluster of rows into a type of summary table rows using the table column value or any expression. We also implement the GROUP BY clause with MySQL aggregate functions for grouping the rows with some calculated value in the column. This may include MAX, MIN, COUNT, SUM, and AVG, where it is used with a SELECT statement that provides info about every group in the result set. Similarly, when we apply COUNT() function together with this GROUP BY clause then, it will show the number of counts for each specified grouped rows in the table query.

Syntax

The following syntax is the basic structure to query using GROUP BY Count clause in MySQL:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Code:

SELECT Col_1, Col_2,…., Col_n,  AggregateFunction(Col_i) FROM TableName
WHERE Cond_Expr GROUP BY Col_1, Col_2,…, Col_n;

Explanation: With the SELECT statement, the GROUP BY clause is an option to be used for providing a grouped result set according to a specified column value. The comma-separated lists: Col_1, Col_2,…, Col_n, denotes the column values to be fetched in the result set and one of them will be defined for aggregate function and GROUP BY clause to write the proper query. Here, the MySQL will evaluate the GROUP BY clause only after the SELECT, FROM, and WHERE clauses but should be placed before ORDER BY, HAVING, and LIMIT clauses.

How GROUP BY count works in MySQL?

The GROUP BY clause is essential when we want a collection of result set having rows with similar values arranged into subgroups type. It summarizes the rows by the column data specified in the query. In the output set, the MySQL GROUP BY clause returns a single row for every arranged group. This method helps to decrease the number of rows in the set of results provided by MySQL. Generally, with this GROUP BY clause, we add some aggregate functions that include COUNT, SUM, MIN, MAX, and AVG that gives information about the groups formed by using the GROUP BY query in the result rows.

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,768 ratings)

In MySQL, the aggregate function is responsible to execute the calculation of a set table rows and outputs a value. Thus, the COUNT() function here is used with the MySQL GROUP BY clause to complete calculation and then it gives a distinct value for every subgroup formed. If you want to display the result set with unique values to occur with the GROUP BY Count clause, then we need to use the DISTINCT operator just after the SELECT clause in the query and before the column names specified. For example,

SELECT DISTINCT ColumnName FROM TableName;

Using the COUNT() function with the GROUP BY clause, then the query will produce the number of values as the count for each subgroup created based on the table column values or expressions.

Examples to Implement MySQL GROUP BY Count

Let us demonstrate some examples using the GROUP BY clause and COUNT() function in MySQL to show the working of GROUP BY Count:

Example #1: Using GROUP BY Count on a single column

Step 1: Suppose, we have a Customer table in the database having the fields CustomerID, CustomerName, Credit_Limit, and City, where we have some records as follows:

Code:

SELECT * FROM Customer;

Output:

MySQL GROUP BY count1

Step 2: Now, we will implement the MySQL GROUP BY COUNT to query the data forming groups based on the particular column value and each group has its own count number that is for the identical values found in the group. The SQL statement to perform this information in the result set rows with the following command.

Code:

SELECT CustomerName, City, COUNT(*) FROM Customer GROUP BY City;

Output:

MySQL GROUP BY count2

Explanation: You can see that the result rows are grouped by city column and each grouped value contains the count for that value present by which the rows are arranged. Thus, MySQL has returned a number of customers available in the table for each grouped city name. The group operation performed on the Customer table has displayed the reduced form of output rows due to the grouping of column values.

Example #2: Using GROUP BY Count on Multiple columns

Step 1: Let us take another table named Books present in our MySQL database. The table contains the fields as BookID, BookName, Language, and Price. To view the contents of the table we will execute the below query

Code:

SELECT * FROM Books;

Output:

MySQL GROUP BY count3

Step2: Here, we have a language column with values either ‘English’ or ‘Hindi’ and similarly we can find book names as per English medium and Hindi version too. Then, we will write a query to perform the grouping of columns in the table and also implementing the count function in it. The SQL statement is as follows:

Code:

SELECT BookName, Language, COUNT(*) FROM Books GROUP BY BookName, Language;

Output:

grouping of columns

Explanation: As you can see the result rows are grouped based on multiple columns, BookName and Language using the GROUP BY operation and the next column is for the count that denotes values of books available for each group data in the table.

Example #3: Using GROUP BY Count with ORDER BY clause

For this illustration of an example, we will take the previous table named Books. In this query, along with the GROUP BY COUNT clause, we will also use the ORDER BY clause to evaluate the statement more properly. The ORDER BY clause in MySQL is responsible to arrange the column values irrespective of its data type either character or numeric, in ascending or descending order as mentioned in the query part. We will apply it after the GROUP BY clause. The query statement for this is as follows:

Code:

SELECT LANGUAGE, COUNT(*) FROM Books GROUP BY LANGUAGE ORDER BY 2 ASC;

Output:

ORDER BY clause

Explanation: Here, each group has its own respective counts and the counting for each group is queried in ascending order as shown above.

Conclusion

The COUNT() function in MySQL query will be used in conjunction with the clause GROUP BY which is useful to illustrate table records on the basis of several groupings. This GROUP BY COUNT query provides the count of values for the combination of identical column values that are preserved as a single group.

Recommended Articles

This is a guide to MySQL GROUP BY Count. Here we discuss an introduction to MySQL GROUP BY Count, how does it work with query examples. You can also go through our other related articles to learn more –

  1. MySQL count()
  2. MySQL Subquery
  3. MySQL avg()
  4. ROLLUP in MySQL
Popular Course in this category
MySQL Training Program (12 Courses, 10 Projects)
  12 Online Courses |  10 Hands-on Projects |  92+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

MS SQL Training (16 Courses, 11+ Projects)4.9
Oracle Training (14 Courses, 8+ Projects)4.8
PL SQL Training (4 Courses, 2+ Projects)4.7
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more