Networking, Programming and Graphics - Tutorials
ONLINEHOWTO.net Tutorials Category

Using MySql Group By Function

Type: Code Networking, Programming and Graphics - Tutorials
Networking, Programming and Graphics - Tutorials
Level: Beginner Networking, Programming and Graphics - Tutorials 
Networking, Programming and Graphics - Tutorials
Date: 2010-Feb-02
Networking, Programming and Graphics - Tutorials
Visited: 344 times
Networking, Programming and Graphics - Tutorials
Rating: Networking, Programming and Graphics - Tutorials
Networking, Programming and Graphics - Tutorials
Published: Ivory Morhuld

In this tutorial I will show you how to use Group By Function in MySql.

Group by is very powerful function which can help you to get an result from MySql database in very specific view, format and order. Later resulted data in this format, can be parsed for some other operations or manipulations.

In our example we will use freeware and web based PhpMyAdmin for database administration and manipulation.
Using MySql Group By Function
In this tutorial we will use table with "IP-to-Country" data. This is a list with IP range zones of most countries, with their respective names and TLD suffixes.

In other words the tables looks in this way:
Using MySql Group By Function
Now you will prepare some select using Group By function. Let say we want to get all data from `tld` column, but only one time for each country - without repeated rows.

Our select query have to look like this:
select `tld` from `table` group by `tld`
And the query will return this result to us:
Using MySql Group By Function
But this result is displayed with no any order and we can improve our query to use Order by function to display data from `tld` column sorted alphabetically like this:
select `tld` from `table` group by `tld` order by `tld` asc
The result from the above select will be like this:
Using MySql Group By Function
But if you use most popular select:

select * from `table` group by `tld` order by `tld` asc

Let see what happen with data from other columns with this query:
Using MySql Group By Function
Like you can see, from the first select result in this tutorial, there is more than one row for UNITED STATES country with `tld`=US. But when we use Group by function we take only one row, and in this row exist only one value for `ip_from` and `ip_to`.

For this, you have to note, that when use Group by function you can not be sure which row will be returned sorting with Order by function.
Rate this tutorial:                    
Post Comment

Need a specific tutorial? Do not hesitate and submit a request!
Your e-mail: