562 attributed reviews in the last 3 years
Refreshingly small course sizes
Outstandingly good courseware
Whizzy online classrooms
Wise Owls only (no freelancers)
Almost no cancellations
We have genuine integrity
We invoice after training
Review 30+ years of Wise Owl
View our top 100 clients
Using ORDER BY to Sort in SQL Server Queries
Part one of a two-part series of blogs
If your SQL queries return lots of records you'll probably want to sort the results in some kind of order. This blog teaches you how to use the ORDER BY clause to do exactly that!
This blog teaches you how to sort the results of basic queries in Microsoft SQL Server.
You can sort the results of a query by adding the ORDER BY clause to a SELECT statement. If you've read our blog on basic SQL queries you'll remember that ORDER BY is the last of the six main keywords in a SQL query. If you haven't read the previous blog, here's a quick reminder of the order of keywords:
To sort the results of a query you can simply add a column name to the ORDER BY clause:
Adding the FilmName field to the ORDER BY clause sorts the query results in ascending order of film title.
By default, a column will be sorted in ascending order. You can add the ASC keyword to make this more obvious:
The ASC keyword is optional but makes the query more readable.
You can sort a column in descending order by adding the DESC keyword after the column name:
Adding the DESC keyword sorts a column in descending order.
You can sort your query on multiple columns by listing extra column names separated with commas:
Here the films are sorted in descending order of release date. Where multiple films share a release date they are sorted in ascending order of name.
You don't have to include a column in the SELECT list in order to use it in the ORDER BY clause:
The results of this query are sorted so that the most successful Oscar winners appear at the top, even though that field isn't shown in the query.
If you've used aliases to replace long column names in the SELECT list you can also use them in the ORDER BY clause:
Here we've used the alias to sort the films in descending order of duration.
Using an alias is also a useful way to sort on a calculated column.
Now that you've seen the basics of changing the order of query results it's time to see how to return a given number of items from a table using the TOP keyword. Read the next part of this series to find out how.
|Parts of this blog|
25 Aytoun Street