ORDER BY Clause of a SELECT Statement

This section provides tutorial examples on how to use the ORDER BY clause to sort rows of the base table according to the given order.

"ORDER BY clause" modifies the base table by sorting rows according the specified order. "ORDER BY clause" syntax is:

ORDER BY order_exp, order_exp, ...

where "order_exp" specify a single order expression. If multiple order expressions are specified, the order expression on the left has higher precedence than the one on the right. This means the order expression on the right will only be used to sort rows that are having the same for the order expression on the left.

If ORDER BY clause is used with GROUP BY clause, it must contain only group columns or group functions. For example, the following statement shows us which department has the oldest average age:

SELECT department, COUNT(name) AS numberOfEmployees, 
 min(age) AS minimumAge, max(age) AS maximumAge, 
 AVG(age) as averageAge
FROM employee WHERE status='Active' GROUP BY department
ORDER BY AVG(age) DESC

Last update: 2015.

Table of Contents

 About This Book

 Introduction of SQL

 MySQL Introduction and Installation

 Introduction of MySQL Programs

 Perl Programs and MySQL Servers

 PHP Programs and MySQL Servers

 Java Programs and MySQL Servers

 Datatypes and Data Literals

 Operations and Expressions

 Character Strings and Bit Strings

 Commonly Used Functions

 Table Column Types for Different Types of Values

 Using DDL to Create Tables and Indexes

 Using DML to Insert, Update and Delete Records

Using SELECT to Query Database

 SELECT Statements

 FROM Clause of a SELECT Statement

 JOIN -Operations to Join Two Tables

 JoinTable.sql - Example of Join Tables

 WHERE Clause of a SELECT Statement

 GROUP BY Clause of a SELECT Statement

ORDER BY Clause of a SELECT Statement

 Transaction Management and Isolation Levels

 Locks Used in MySQL

 Defining and Calling Stored Procedures

 Variables, Loops and Cursors Used in Stored Procedures

 Outdated Tutorials

 References

 PDF Printing Version