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 aggregate 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

Another interesting function called FIELD() can also be used in the ORDER BY clause. FIELD(value, value_list) returns the position of a given value in a given value list. For example, if you want to return employees with first name of "Jean, Mary, John, Mike" and in this order, you can use the following SELECT statement:

SELECT name, department, age
  FROM employee WHERE name IN ('Jean', 'Mary', 'John', 'Mike')
  ORDER BY FIELD (name, 'Jean', 'Mary', 'John', 'Mike')

Table of Contents

 About This Book

 Introduction of SQL

 MySQL Introduction and Installation

 Introduction of MySQL Programs

 PHP Programs and MySQL Server

 Perl 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 - Operation to Join Two Tables

 JoinTable.sql - Example of Join Tables

 WHERE Clause of a SELECT Statement

ORDER BY Clause of a SELECT Statement

 GROUP BY Clause of a SELECT Statement

 Window Functions for Statistical Analysis

 Use Index for Better Performance

 Transaction Management and Isolation Levels

 Locks Used in MySQL

 Defining and Calling Stored Procedures

 Variables, Loops and Cursors Used in Stored Procedures

 System, User-Defined and Stored Procedure Variables

 MySQL Server Administration

 Storage Engines in MySQL Server

 InnoDB Storage Engine - Primary and Secondary Indexes

 Performance Tuning and Optimization

 Bulk Changes on Large Tables

 MySQL Server on macOS

 Installing MySQL Server on Linux

 Connection, Performance and Second Instance on Linux

 Archived Tutorials


 Full Version in PDF/EPUB