The SQL ORDER BY Clause is used in the SELECT statement to sort results in ascending or descending order. By default, Oracle sorts query results in ascending order.
Syntax of the ORDER BY Clause in SQL to sort data
SELECT column-list
FROM table_name [WHERE condition]
[ORDER BY column1 [, column2, .. columnN] [DESC]];
An example of the ORDER BY clause in SQL
Below is the employee data table:
To sort the employee list by salary, the SQL ORDER BY command is written as follows:
SELECT name, salary FROM employee ORDER BY salary;
The output appears as follows:
The first query sorts the results by name and displays them.
Furthermore, you can use multiple columns in the ORDER BY clause in SQL.
To sort the employee table by name and salary, the SQL ORDER BY query is:
SELECT name, salary FROM employee ORDER BY name, salary;
The output appears as follows:
Note on the ORDER BY clause in SQL
Columns specified in the ORDER BY clause are among those selected in the SELECT column list.
You can specify the position of a column in the SELECT list to represent columns in the ORDER BY clause, instead of writing column names.
These queries can also be written as follows:
SELECT name, salary FROM employee ORDER BY 1, 2;
By default, the ORDER BY clause in SQL will sort data in ascending order. If you want to sort in descending order, you must specify it explicitly as in the query below:
SELECT name, salary
FROM employee
ORDER BY name, salary DESC;
The SQL ORDER BY query above sorts the salary column in descending order and the name column in ascending order.
To sort employees by name and salary in descending order, the SQL ORDER BY query is written as follows:
SELECT name, salary
FROM employee
ORDER BY name DESC, salary DESC
Using expressions in the ORDER BY clause in SQL
Expressions in the ORDER BY clause in SQL are used within the SELECT statement.
For example: If you want to display all employee names, current salaries, and only increase the salaries by 20% for employees with salaries above 30000 in descending order, the SELECT statement would be written as follows:
SELECT name, salary, salary*1.2 AS new_salary
FROM employee
WHERE salary*1.2 > 30000
ORDER BY new_salary DESC;
The output of the above query is as follows:
Above, Mytour has just introduced you to the ORDER BY clause in SQL. In the next article, Mytour will further introduce you to VIEW, GRANT, ... in SQL, and especially the CREATE statement in SQL. Stay tuned.
Furthermore, you can explore more articles related to SQL, SQL Server such as how to create, check, and modify an Identity column on Microsoft SQL Server to gain additional knowledge about this language and data management environment. Wishing you all success!
