SQL - Select Order By
The ORDER BY clause in SQL is used to sort the result set of a query based on one or more columns. It allows you to specify the order in which the rows should be displayed in the query result. By default, the ORDER BY clause sorts the result set in ascending order, but you can also specify descending order for individual columns. The ORDER BY clause is commonly used to organize and present query results in a meaningful way.
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
Example:
Let's assume we have a "Students" table with the following columns:
StudentID (unique identifier for each student)
FirstName (first name of the student)
LastName (last name of the student)
Age (age of the student)
Grade (grade level of the student)
To retrieve a list of students sorted by their last name in ascending order, we can use the ORDER BY clause:
SELECT FirstName, LastName, Age, Grade
FROM Students
ORDER BY LastName;
Explanation:
The SELECT statement specifies the columns we want to retrieve from the table. In this case, we select FirstName, LastName, Age, and Grade columns.
The FROM clause indicates the table from which we want to retrieve data. In this example, it's the "Students" table.
The ORDER BY clause is used to specify the sorting order for the result set. In this case, we sort the rows based on the LastName column.
By executing this query, you will retrieve the student records sorted by their last name in ascending order.
Sorting in Descending Order:
If you want to sort the result set in descending order, you can use the DESC keyword after the column name within the ORDER BY clause. For example, to sort the students by their last name in descending order, you can modify the query as follows:
SELECT FirstName, LastName, Age, Grade
FROM Students
ORDER BY LastName DESC;
This query will retrieve the student records sorted by their last name in descending order.