With Order By Clause, you can sort the records returned as a result of the Select statement as ascending or descending according to the column you specify. Let’s make two examples that sort by numbers and letters.
Create a table to use in our examples and add a few records.
1 2 3 4 5 6 7 8 | USE [TestDB] GO CREATE TABLE [dbo].[MyTable]( [ID] [int] IDENTITY(1,1) NOT NULL, [Name] [varchar](50) NULL ) ON [PRIMARY] GO INSERT INTO [dbo].[MyTableTarget] VALUES ('Nurullah'),('Faruk'),('Hakan'),('Ogun') |
Example1: Sort numeric values with Order By Clause
The following command lists the records in the table from smaller to bigger according to the ID column.
1 | Select * FROM [dbo].[MyTable] Order By ID ASC |
The following command lists the records in the table from bigger to smaller according to the ID column.
1 | Select * FROM [dbo].[MyTable] Order By ID DESC |
Example2: Sorting Text Values with Order By Clause
With the following command, we sort the records in the table from A to Z according to the Name column.
1 | Select * FROM [dbo].[MyTable] Order By Name ASC |
With the following command, we sort the records in the table from Z to A according to the Name column.
1 | Select * FROM [dbo].[MyTable] Order By Name DESC |