![]() |
![]() |
![]() |
The ORDER BY Clause is used to order the result set in ascending or descending order. By default, when ORDER BY clause is used the result set is ordered in the ascending order.
This is Part 4 of 40 Part SQL Server T-SQL Tutorial. Click here to read it from the beginning….
ORDER BY Clause Syntax
SELECT column1, column2
FROM schema.tablename
ORDER BY column1, column2 ASC|DESC
GO
ORDER BY ASC Example
Below query will fetch FirstName and LastName of all the records from Person’s table and order the results in ascending order. Even if you don’t specify the ASC still the result set will be retrieved in ascending order by default in SQL Server.
Use AdventureWorks2016
GO
SELECT
FirstName
, LastName
FROM Person.Person
Order by FirstName ASC
GO

ORDER BY DESC Example
Below query will fetch FirstName and LastName of all the records from Person’s table and order the results in descending order.
Use AdventureWorks2016
GO
SELECT
FirstName
, LastName
FROM Person.Person
Order by LastName DESC
GO

ORDER BY Multiple Column Example
The data is sorted in descending order and the data is sorted by FirstName and LastName. It means it is first ORDERED by FirstName and if some records has same FirstName then it is order by LastName.
You can see in the snippet below that rows 4 to 15 has same First Name which is Aaron and therefore the records from 4 to 15 are sorted by LastName in the descending order as specified in the query.
Use AdventureWorks2016
GO
SELECT
FirstName
, LastName
FROM Person.Person
Order by FirstName, LastName DESC
GO

Click Next Page button to continue reading the topics and click on the Previous Page button to revisit the previous topic.
Add comment