The ORDER BY clause in SQL Server

The ORDER BY clause is used to filter records in the result set.

The ORDER BY clause is used to filter records in SQL Server's returned result set. This clause can only be used in the SELECT statement.

ORDER BY clause syntax

 SELE CT 'biểu thức' 
FROM 'bảng'
[WHERE 'điều kiện']
ORDER BY 'bi knowledgeable' [ASC | DESC];

Variable names and variable values

Expression - column or calculation value you want to retrieve.

Table - the table you want to use to retrieve the record. Must have at least 1 table in the FROM clause.

WHERE 'condition' - optional. Conditions must be met, the new record is selected.

ASC - optional. Filter results in ascending order of expressions (default if not specified).

DESC - optional. Filter the results in descending order of expressions.

Note:

If ASC or DESC is not selected in the ORDER BY clause, the result will be sorted by ascending order by default, equivalent to ORDER BY 'ASC expression'.

For example - filtering without using the ASC / DESC attribute

 SELECT cough 
FROM nhanvien
WHERE nhanvien_id > 1000
ORDER BY ho ;

The returned result will be the records filtered by the employee's surname field, in ascending order, equivalent to the following clause.

 SELECT cough 
FROM nhanvien
WHERE nhanvien_id > 1000
ORDER BY ho ASC;

Most developers remove the ASC attribute if they want to sort in ascending order.

For example - sort in descending order

 SELECT cough 
FROM nhanvien
WHERE ten = 'Sarah'
ORDER BY ho DES C;

As a result, records filter by employee's surname in descending order.

For example - filtering by relative position

You can use the ORDER BY clause in SQL Server to filter by relative position in the result set, where the first field is set to 1, followed by 2 and so on .

 SELECT ho 
FROM nhanvien
WHERE ho = 'Anderson'
ORDER BY 1 DESC;

In this example, the returned result is the record of the employee's last name field in descending order. Since the employee surname is at the 1st position in the result set, the above result is the same as in the ORDER BY clause below.

 SELECT cough 
FROM nhanvien
WHERE ho = 'Anderson'
ORDER BY ho DESC ;

For example - use both ASC and DESC attributes

 SELECT h o, ten 
FROM nhanvien
WHERE ho = 'Johnson'
ORDER BY ho D ESC, ten ASC;

In the above example, the return record will be the employee surname arranged in descending order and the employee name in ascending order.

Previous article: WHERE clause in SQL Server

Next lesson: AND condition in SQL Server

Update 25 May 2019
Category

System

Mac OS X

Hardware

Game

Tech info

Technology

Science

Life

Application

Electric

Program

Mobile