You can see the Count command before using GROUP BY command here. GROUP BY command will create groups in the field name specified and will count the number of records in the groups. This is very useful command.

We can also use WHERE command along with GROUP BY command in Mysql tables.
SELECT count(*) as total_records, class  FROM `student` group by class

This will display the total records in each class. Like this
1 Eight
3 Five
9 Four
2 Nine
10 Seven
7 Six
3 Three
Let us try to get the total number of girls records in each class by using GROUP BY query. Here we want to filter our query for only girls so we have to use one WHERE clause to restrict the records using the sex field. Here is the query.
SELECT count( * ) AS total_records, class FROM `student` WHERE sex='female' GROUP BY class

The output is here
total_records class
5 Four
1 Nine
5 Seven
5 Six
1 Three

Sample code

Here is a sample code to understand how to use group by query using PHP script and PDO.
require "../config.php"; // Database connection 
$sql="SELECT count(*) as total_records, class FROM `student` group by class ";
echo "<table>";
foreach ($dbo->query($sql) as $row) {
echo "<tr ><td>$row[class]</td><td>$row[total_records]</td></tr>";
echo "</table>";

PART II: We will try to apply group by command more than one fields. For this we will create a new table and discuss in detail. Next Part II

Down load the SQL DUMP of this student table

Number of User Comments : 4




i want to display the all record from table, in which if column contain duplicate value then it will show duplicate value at once


You have to use distinct SQL command. Read here on how to use Distinct to get unique records.


very nice tutorial it really helps me a lot :)


i want to display a column into row.

Post Comment This is for short comments only. Use the forum for more discussions.

Subscribe to our mailing list

* indicates required
Subscribe to plus2net

HTML . MySQL. PHP. JavaScript. ASP. Photoshop. Articles. FORUM Contact us
©2000-2016 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer