Sorting Records

Contact Us or call 1-877-932-8228
Sorting Records

Sorting Records

The ORDER BY clause of the SELECT statement is used to sort records.

Sorting By a Single Column

To sort by a single column, simply name that column in the ORDER BY clause.

Syntax

SELECT column, column
FROM table
ORDER BY column;

Note that columns in the ORDER BY clause do not have to appear in the SELECT clause.

Code Sample:

SimpleSelects/Demos/OrderBy1.sql
/*
	Select the FirstName and LastName columns from the Employees table. 
	Sort by LastName.
*/

SELECT FirstName, LastName
FROM Employees
ORDER BY LastName;

The above SELECT statement will return the following results:

Sorting By Multiple Columns

To sort by multiple columns, comma-delimit the column names in the ORDER BY clause.

Syntax

SELECT column, column
FROM table
ORDER BY column, column;

Code Sample:

SimpleSelects/Demos/OrderBy2.sql
/*
Select the Title, FirstName and LastName columns from the Employees table.
Sort first by Title and then by LastName.
*/

SELECT Title, FirstName, LastName
FROM Employees
ORDER BY Title, LastName;

The above SELECT statement will return the following results:

Sorting By Column Position

It is also possible to sort tables by the position of a column in the SELECT list. To do so, specify the column numbers in the ORDER BY clause.

Syntax

SELECT column, column
FROM table
ORDER BY column_position, column_position;

Code Sample:

SimpleSelects/Demos/OrderBy3.sql
/*
Select the Title, FirstName and LastName columns from the Employees table.
Sort first by Title (position 1) and then by LastName (position 3).
*/

SELECT Title, FirstName, LastName
FROM Employees
ORDER BY 1,3;

The above SELECT statement will return the same results as the previous query:

Ascending and Descending Sorts

By default, when an ORDER BY clause is used, records are sorted in ascending order. This can be explicitly specified with the ASC keyword. To sort records in descending order, use the DESC keyword.

Syntax

SELECT column, column
FROM table
ORDER BY column_position DESC, column_position ASC;

Code Sample:

SimpleSelects/Demos/OrderBy4.sql
/*
	Select the Title, FirstName and LastName columns from the Employees table.
	Sort first by Title in ascending order and then by LastName 
	in descending order.
*/

SELECT Title, FirstName, LastName
FROM Employees
ORDER BY Title ASC, LastName DESC;

The above SELECT statement will return the following results:

Next