asp.net.ph

Skip Navigation LinksHome > Data Access / ADO.NET > Structured Query Language (SQL) Basics > SQL Order By: Sorting Data in Query Results

SQL ORDER BY: Setting Sort Order In Query Results


In cases where data needs to be displayed in a sorted order, you can sort the query results based on the data in one or more columns.

SQL ORDER BY clause

The ORDER BY clause sets the order of a query’s result set based on a specified column or columns in ascending or descending order.

SELECT * FROM tableName WHERE filterCondition 
   GROUP BY groupColumn HAVING filterCondition 
   ORDER BY orderItem [ASC | DESC]

Each orderItem must correspond to a column in the query results and can be one of the following:

  • a column in a FROM table that is also a columnItem in the main SELECT clause
  • a numeric expression indicating the location of the column in the result table, starting from 1 (leftmost column).

ASC specifies an ascending order ( A to Z, 0 to 9 ) for query results, and is the default for ORDER BY, so can be omitted.

SELECT LastName, FirstName FROM Employees ORDER BY LastName ASC

is the same as

SELECT LastName, FirstName FROM Employees ORDER BY LastName
Run Sample | View Source

DESC specifies a descending order ( Z to A, 9 to 0 ) for query results. To sort in descending order, add the DESC keyword to the end of each column you want to sort in descending order.

SELECT LastName, Salary FROM Employees ORDER BY Salary DESC

You can include more than one column in the ORDER BY clause. Records are sorted first by the first column listed after ORDER BY. Records that have equal values in that column are then sorted by the value in the second column listed, and so on.

SELECT Design, Model, Description, PlanID ... ORDER BY Design, Model
SQL Order By Clause (Example 1)
Run Sample | View Source

Note that you cannot sort on Memo or OLE Object columns.

ORDER BY is usually the last item in an SQL statement. In general, query results appear unordered if ORDER BY is not specified.

See Also

Using SQL Aggregate Functions



© 2025 Reynald Nuñez and asp.net.ph. All rights reserved.

If you have any question, comment or suggestion
about this site, please send us a note