ORDER BY Clause ORDER BY ASC
The ORDER BY clause is used to sort the result of a SELECT statement in ascending or descending order as per the requirement. When a query returns a result set with multiple records, the ORDER BY clause is used to order the records based on one or more columns.
Syntax
The basic syntax of the ORDER BY clause with ASC in MySQL is as follows:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 ASC;
- column1, column2, ...: Name of the columns which we want to fetch from the table.
- table_name: The name of the table from which we want to fetch the data.
- column1: The column based on which we want to sort the data. We can add more columns if we want to sort on more columns.
- ASC: The keyword to sort in ascending order.
Example
For example, let's consider a "students" table that contains the following data:
SELECT * FROM students;
Output:
| id | name | marks |
|----|--------|-------|
| 1 | John | 75 |
| 2 | Alice | 85 |
| 3 | Peter | 90 |
| 4 | Rachel | 80 |
Now, if we want to fetch student details by their name in ascending order, we can use the following query:
SELECT * FROM students
ORDER BY name ASC;
Output:
| id | name | marks |
|----|--------|-------|
| 2 | Alice | 85 |
| 1 | John | 75 |
| 4 | Rachel | 80 |
| 3 | Peter | 90 |
In the above query, we are selecting all the columns from the "students" table and ordering them by their name in ascending order using the ASC keyword.
Explanation
The ORDER BY clause is used to sort the result set in either ascending or descending order based on the specified column name.
In the above example, we have sorted the result set in ascending order based on the "name" column. If we want to sort it in descending order, we can replace "ASC" with "DESC" keyword.
Use
The ORDER BY clause is used to sort the result set of a SELECT statement based on one or more columns in ascending or descending order as per the requirement.
Important Points
- The ORDER BY clause is used to sort the result set based on one or more columns.
- The default order is ascending. Hence, if we don't specify any order, it is sorted in ascending order.
- We can specify the order as either ASC (for ascending) or DESC (for descending).
Summary
In conclusion, the ORDER BY clause with ASC is used to sort the data in ascending order based on one or more columns. It is an essential clause in SQL for sorting the result set in specific orders based on the requirements.