Order by in SQL Server

To sort the result set in ascending or descending order in SQL Server, you can use the ORDER BY clause. The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default.

To sort the records in descending order, use the DESC keyword.

Syntax: –

SELECT column1, column2, FROM table_name
ORDER BY column1, column2, … ASC|DESC;

To sort the result set in ascending or descending order in SQL Server, you can use the ORDER BY clause. The syntax for the ORDER BY clause is as follows:

SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;

Here, column1, column2, etc. are the columns you want to sort by. You can specify the sorting order for each column by using the optional ASC or DESC keyword. By default, the ORDER BY clause sorts the result set in ascending order.

For example, the following SQL statement selects all the columns from the “Customers” table, sorted by the “CustomerName” column in ascending order:

SELECT *
FROM Customers
ORDER BY CustomerName;

If you want to sort the records in descending order, you can use the DESC keyword. For example, the following SQL statement selects all the columns from the “Customers” table, sorted by the “CustomerName” column in descending order:

SELECT *
FROM Customers
ORDER BY CustomerName DESC;

For Example,

  1. The following SQL statement selects all customers from the \”Customers\” table, sorted by the \”Country\” column:

SELECT * FROM Customers
ORDER BY Country;

  • The following SQL statement selects all customers from the \”Customers\” table, sorted DESCENDING by the \”Country\” column:

SELECT * FROM Customers
ORDER BY Country DESC;

  • The following SQL statement selects all customers from the \”Customers\” table, sorted by the \”Country\” and the \”CustomerName\” column. This means that it orders by Country, but if some rows have the same Country, it orders them by CustomerName:

SELECT * FROM Customers
ORDER BY Country, CustomerName;

  • The following SQL statement selects all customers from the \”Customers\” table, sorted ascending by the \”Country\” and descending by the \”CustomerName\” column:

SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;