How to Use the ORDER BY Clause in SQL
How to Use the ORDER BY Clause in SQL: Video
This video lesson, titled “The ORDER BY Clause,” shows how to use the ORDER BY clause in SQL. This video is from our introductory SQL tutorial, titled “Mastering Introductory SQL Made Easy.”
Overview of the ORDER BY Clause in SQL
This blog post shows you how to use the ORDER BY clause in SQL to sort the result set of a query. When viewing the result set of a SELECT statement in SQL, the records appear in the order that they were selected from the table.
This means that, by default, they do not appear in any particular order within the result set. You use the ORDER BY clause of the SELECT statement in SQL to sort the records selected within the result set.
General Syntax of the ORDER BY Clause in SQL
The core SQL of a SELECT statement using the ORDER BY clause appears below. Note that the “table_name” parameter is the name of the table from which to select the records, the “field_name” parameter is the name of a field, and “criteria” is a value to find within the specified field. ASC stands for “ascending” and DESC stands for “descending. The braces denote an area where you must make a choice, and the pipe symbol separates the available choices. You do not actually type the braces or pipe symbol.
SELECT {* | field_name, field_name1, etc.}
FROM table_name
WHERE field_name = criteria
ORDER BY field_name {ASC | DESC}, field_name1 {ASC | DESC}, etc.
You often do not need to specify “ASC” for each field by which to sort the result set, as the field is sorted in ascending order (1-9, A-Z) by default. However, to sort the records by the values within the field in descending order (9-1, Z-A), you must specify the DESC keyword after each named field to sort in descending order.
How to Use the ORDER BY Clause in SQL
The following hyperlinks show how to use the ORDER BY clause in SQL SELECT statements for SQL implementations of MySQL 8.0, SQL Server or Microsoft Azure (T-SQL), and Access 2019.
MySQL 8.0:
https://dev.mysql.com/doc/refman/8.0/en/select.html
ORDER BY Optimization in MySQL 8.2:
https://dev.mysql.com/doc/refman/8.0/en/order-by-optimization.html
SQL Server or Microsoft Azure (T-SQL):
https://docs.microsoft.com/en-us/sql/t-sql/queries/select-order-by-clause-transact-sql
Access 2019:
https://support.microsoft.com/en-us/office/order-by-clause-e8ea47f7-5388-460a-bec8-dcc81792d762