SQL Order By
Use ORDER BY to sort the results of a query by a given column or columns.
Using a SQL SELECT statement can retreive many hundreds or even thousands of records. In some cases you might find it useful to sort the records by a given column. For example, when selecting records from the Individual table, you might like to sort them by the LastName column.
SQL statement
SELECT * FROM Individual
ORDER BY LastName;
Source Table
IndividualIdFirstNameLastNameUserName1FredFlinstonefreddo2HomerSimpsonhomey3HomerBrownnotsofamous4OzzyOzzbournesabbath5HomerGainnoplacelike
Result
IndividualIdFirstNameLastNameUserName3HomerBrownnotsofamous1FredFlinstonefreddo5HomerGainnoplacelike4OzzyOzzbournesabbath2HomerSimpsonhomey
Descending Order
By default, ORDER BY sorts the column in ascending order — that is, from lowest values to highest values. You could also explicitly state this using the ASC keyword, but it's not necessary.
If you want highest values to appear first, you can use the DESC keyword.
SQL statement
SELECT * FROM Individual
ORDER BY LastName DESC;
Result
IndividualIdFirstNameLastNameUserName2HomerSimpsonhomey4OzzyOzzbournesabbath5HomerGainnoplacelike1FredFlinstonefreddo3HomerBrownnotsofamous
Sorting By Multiple Columns
You can sort by multiple columns by stating each column in the ORDER BY clause, separating each column name with a comma. SQL will first order the results by the first column, then the second, and so on for as many columns that are included in the ORDER BY clause.
SQL statement
SELECT * FROM Individual
ORDER BY FirstName, LastName;
Result
IndividualIdFirstNameLastNameUserName1FredFlinstonefreddo3HomerBrownnotsofamous5HomerGainnoplacelike2HomerSimpsonhomey4OzzyOzzbournesabbath