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

IndividualIdFirstNameLastNameUserName
1FredFlinstonefreddo
2HomerSimpsonhomey
3HomerBrownnotsofamous
4OzzyOzzbournesabbath
5HomerGainnoplacelike

Result

IndividualIdFirstNameLastNameUserName
3HomerBrownnotsofamous
1FredFlinstonefreddo
5HomerGainnoplacelike
4OzzyOzzbournesabbath
2HomerSimpsonhomey

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

IndividualIdFirstNameLastNameUserName
2HomerSimpsonhomey
4OzzyOzzbournesabbath
5HomerGainnoplacelike
1FredFlinstonefreddo
3HomerBrownnotsofamous

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

IndividualIdFirstNameLastNameUserName
1FredFlinstonefreddo
3HomerBrownnotsofamous
5HomerGainnoplacelike
2HomerSimpsonhomey
4OzzyOzzbournesabbath