When retrieving data from a table using the SELECT statement, the results may not appear in any particular order. In many situations, users need the data to be arranged in a specific order such as ascending or descending.
The ORDER BY clause is used to sort the result of a query based on one or more columns. This helps in organizing data for easier reading and analysis.
The ORDER BY clause is used in SQL to sort the records retrieved from a table in ascending or descending order based on one or more columns.
SELECT column1, column2, ...
FROM table_name
ORDER BY column_name [ASC | DESC];
Where:
Suppose we have a table named students.
| id | name | age | course |
|---|---|---|---|
| 1 | Rahul | 20 | BCA |
| 2 | Anita | 21 | BBA |
| 3 | Rohit | 19 | BCA |
| 4 | Priya | 22 | BCom |
SELECT * FROM students
ORDER BY age ASC;
| id | name | age | course |
|---|---|---|---|
| 3 | Rohit | 19 | BCA |
| 1 | Rahul | 20 | BCA |
| 2 | Anita | 21 | BBA |
| 4 | Priya | 22 | BCom |
The records are arranged from lowest age to highest age.
SELECT * FROM students
ORDER BY age DESC;
| id | name | age | course |
|---|---|---|---|
| 4 | Priya | 22 | BCom |
| 2 | Anita | 21 | BBA |
| 1 | Rahul | 20 | BCA |
| 3 | Rohit | 19 | BCA |
The records are arranged from highest age to lowest age.
It is also possible to sort records using more than one column.
SELECT * FROM students
ORDER BY course ASC, age DESC;
In this example:
ORDER BY clause is usually written after the WHERE clause.Example:
SELECT * FROM students
WHERE course = 'BCA'
ORDER BY age;
ORDER BY is used to sort query results.The ORDER BY clause is used to arrange the results of a SQL query in a specific order. By sorting data based on one or more columns, users can easily analyze and interpret information stored in a database.