SQL Order By

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

IndividualId FirstName LastName UserName
1 Fred Flinstone freddo
2 Homer Simpson homey
3 Homer Brown notsofamous
4 Ozzy Ozzbourne sabbath
5 Homer Gain noplacelike

Result

IndividualId FirstName LastName UserName
3 Homer Brown notsofamous
1 Fred Flinstone freddo
5 Homer Gain noplacelike
4 Ozzy Ozzbourne sabbath
2 Homer Simpson homey
 

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

IndividualId FirstName LastName UserName
2 Homer Simpson homey
4 Ozzy Ozzbourne sabbath
5 Homer Gain noplacelike
1 Fred Flinstone freddo
3 Homer Brown notsofamous
 

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

IndividualId FirstName LastName UserName
1 Fred Flinstone freddo
3 Homer Brown notsofamous
5 Homer Gain noplacelike
2 Homer Simpson homey
4 Ozzy Ozzbourne sabbath
%d bloggers like this: