SQL Server returns data in a random order. A simple SELECT returns data in the order they were entered..
Although we can have our results returned in the order in which they were entered, but the only way to ensure the order is the use of ORDER BY clause. The following shows how to sort the result set on Name in descending order.
SELECT Name, Age, Salary FROM Employee
Although we can have our results returned in the order in which they were entered, but the only way to ensure the order is the use of ORDER BYclause. The following shows how to sort the result set on Name in descending order.
SELECT Name, Age, Salary FROM Employee ORDER BY Name DESC
Instead of following the above step all the time for each sorting, we can have a better approach. We can use Case statements and have sorting as per our wish and reqiurement. But there is something known as dynamic Order by clause.
DECLARE @SortingOrder tinyint SET @SortingOrder = 2 SELECT Name, Age, Salary FROM Employee ORDER BY CASE WHEN @SortingOrder = 1 THEN Name WHEN @SortingOrder = 2 THEN Salary ELSE Age END DESC/ASC
Here we can sort items order by Name or Salary or Age. This is somewhat more easy
and crispy and less time taking