SQL ORDER BY Keyword
In SQL, the ORDER BY clause is used to
sort the result set of a SELECT statement in either ascending or
descending order.
The syntax of ORDER BY clause is as follows:
SELECT column_1, column_2, ...
FROM tablename
ORDER BY column_1 [ASC|DESC], column_2 [ASC|DESC], ...;
A. Here, column1, column2, etc. are the names of the columns that you want to retrieve data from.
B. table_name is the name of the table containing those columns.
C. ASC|DESC]
is the optional sorting order of the columns in either ascending (ASC)
or descending (DESC) order. By default, it sorts the data in ascending
order.
For example, if you have a table employees with columns name, department, and salary, and you want to retrieve the names and salaries of employees in descending order of their salaries, you can use the following query:
SELECT EmpName, salary
FROM employees
ORDER BY
salary DESC;
For example, to retrieve a list of all employees in the mployees table sorted by last name in ascending order, you can use the following SQL statement:
SELECT *
FROM employees
ORDER BY
lastName ASC;
This will return the names and salaries of employees sorted in descending order of their salaries.
You can also sort by multiple columns by including them in the ORDER BY clause separated by commas. For example, the following query retrieves the names, departments, and salaries of employees sorted first by department in ascending order and then by salary in descending order:
SELECT EmpName, Empdepartment, salary
FROM employees
ORDER BY
Empdepartment ASC, salary DESC;
This will return the names, departments, and salaries of employees sorted first by department in ascending order and then by salary in descending order.
To sort the data by multiple columns, you can imply add additional columns to the ORDER BY clause:
SELECT *
FROM employees
ORDER BY
LastName ASC, FirstName ASC;
This statement will sort the data by last name first, and then by first name in ascending order.
0 Comments