go top


  • Colection of 65 PHP scripts for $4.29 each


Limited offer!

Get a huge collection of PHP scripts in a special bundle!

Mega Sale Price
Whenever you are retrieving information in MySQL, you will probably want to adjust the way it is ordered or grouped. If you plan to output a group of users, you might want the records to be listed in alphabetical order by their name. Other times, you might want to summarize the information like counting the number of people in a particular zip code that are on your mailing list. MySQL makes all of this very easy with two keywords: ORDER BY and GROUP BY. We will first start with creating a tiny generic users table that gives us the name and zip code of our users.

Fields: user_id, name, zip_code
Type: int, varchar(100), int
Extra: auto_increment

Now that we have that set up, let's take a look at MySQL's ORDER BY in action:

FROM table_users

At a first glance, it looks like a very simple MySQL query. We are simply selecting all of the users' information in the table. However, we see the ORDER BY command that has "name" following it. Essentially, this will order how MySQL outputs the users. In this example, MySQL will output alphabetically because MySQL sees the "name" column as a varchar and defaults to alphabetically order. If our column had been an integer, MySQL would have defaulted to numerical order.

What if we wanted to get the users' names by reverse alphabetical order? All you would have to do is add "DESC" right after the column name like this:

FROM table_users

Sometimes we just need to summarize the data in groups. Maybe we want to count the number of people in a zip code, or count the number of users with the same name. Let's take a look at how to use the MySQL GROUP BY keyword:

SELECT zip_code, count(name)
FROM table_users
GROUP BY zip_code

This query would return the number of users in each zip code. As you can see, the MYSQL GROUP BY keyword retrieves summarized information from the database. This is how you can group and order your records using MySQL. Now go forth and apply them to your queries to get the results you want.

Special Offer!

Get all 65 PHP scripts in a bundle for $4.29 each only!

Mega Sale Offer

1 Comments to "MySQL ORDER BY and GROUP BY"

Add your comment

    • Free Scripts

      Add great new functionalities to your website with our Free Scripts collection.

      Free scripts
    • PHP Scripts

      Check our extensive collection of top-notch PHP Scripts that will enhance your website!

      Commercial PHP scripts