Sorting data using SQL
Using the ORDER BY clause in SQL, it is easy and quick to sort data from a database. The ORDER BY clause in SQL can be used to sort data in either ascending or descending order depending on one or more columns.
The syntax for using the ORDER BY clause is as follows:
SELECT column1, column2, ... FROM table_name ORDER BY column1 ASC/DESC, column2 ASC/DESC, ...;
In this syntax, the FROM statement defines the table name, and the SELECT statement specifies the columns to obtain from the table. The column(s) to sort by and whether to sort in ascending (ASC) or descending (DESC) order are specified in the ORDER BY statement.
Sorting by a Single Column
Suppose there is a table called employees
with columns employee_id
, first_name
, last_name
, hire_date
and salary
.
Sort this table by the last_name
column in ascending order using the following SQL query:
SELECT * FROM employees ORDER BY last_name ASC;
This query returns all the columns from theemployees
table sorted in ascending order by thelast_name
column.
Sorting by Multiple Columns
Sorting by multiple columns is useful when you need to sort data by more than one criterion.
For example, suppose sorting the employees
table by last_name
and then by hire_date
.
See the following SQL query:
SELECT * FROM employees ORDER BY last_name ASC, hire_date ASC;
This query returns all the columns from theemployees
table sorted in ascending order by thelast_name
column and then by thehire_date
column.
Sorting in Descending Order
By default, SQL sorts data in ascending order and for descending order use DESC keyword.
For example, suppose sorting the employees
table by salary
in descending order.
Use the following SQL query:
SELECT * FROM employees ORDER BY salary DESC;
This query returns all the columns from theemployees
table sorted in descending order by thesalary
column.
Comments
Post a Comment