How does the ORDER BY clause work? Also, give an example.
How does the ORDER BY clause work? Also, give an example.
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
Aryan Kumar
25-Sep-2023The 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 appear in the query result. The default order is ascending (ASC), but you can also specify descending (DESC) order for any column.
Here's how the ORDER BY clause works:
Syntax:
column1, column2, ...: The columns you want to retrieve from the table.
table_name: The name of the table from which you're selecting data.
condition (optional): Any conditions you want to apply to filter the rows.
ORDER BY column1 [ASC | DESC], column2 [ASC | DESC], ...: This clause specifies the columns by which you want to sort the result set. You can use one or more columns and specify the sorting order (ascending or descending) for each column. ASC is the default order, so it's optional.
Example:
Let's say you have a table called Employees with the following data:
Now, suppose you want to retrieve the employees sorted by their salary in descending order. You would use the ORDER BY clause like this:
The result of this query would be:
In this example, the ORDER BY clause sorted the rows based on the "Salary" column in descending order, so employees with higher salaries appear at the top of the result set.
You can use the ORDER BY clause to sort query results by one or more columns in ascending or descending order, making it a powerful tool for controlling the presentation of data in your SQL queries.