Quackit Logo

FREE Hosting!

With every domain name you register with ZappyHost, you get FREE hosting.

$1.99 Domain Names

With every new non-domain purchase thru ZappyHost, you get a domain name for only $1.99.

SQL Order By

Print Version

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

Enjoy this website?

  1. Link to this page (copy/paste into your own website or blog):
  2. Add this page to your favorite social bookmarks sites:
               
  3. Add this page to your Favorites

Oh, and thank you for supporting Quackit!