Overview
The ORDER BY clause is utilized in a SELECT statement to sort the results based on one or more columns in ascending or descending order. It is the last clause in a SELECT statement and can be combined with the WHERE, GROUP BY, and HAVING clauses. The ORDER BY clause can be utlized to sort the results by one or more columns in either ascending (ASC) or descending (DESC) order.
ORDER BY Syntax
Akash was a database administrator with a small company. He had been tasked with creating an application allowing the company to query its database and retrieve certain information. Akash needed help to come up with the best way to sort the query results. He knew he wanted to sort the results in a particular order but needed to figure out how. He had heard about the ORDER BY clause in SQL but needed to figure out how to use it. After some research, Akash discovered that the ORDER BY clause was exactly what he needed. Let's help him with it.
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC;
This syntax is utilized to sort the results of a query in ascending or descending order based on the values in the specified columns. The SELECT statement is used to specify the columns in the result set, and the FROM clause is used to specify the table in which to search for the data. The ORDER BY clause is utilised to specify which column(s) to use for sorting and whether the sorting should be in ascending (ASC) or descending (DESC) order.
ORDER BY Example
SELECT *
FROM customers
ORDER BY customer_name ASC;
This query selects all columns from the customer's table and orders the results alphabetically by the customer_name column in ascending order (A-Z).
ORDER BY DESC Example
First_Name | Last_Name | Age |
---|---|---|
John | Smith | 55 |
Alice | Johnson | 45 |
Bob | Williams | 40 |
Steve | Miller | 35 |
SELECT
first_name, last_name, age
FROM
employees
ORDER BY age DESC;
This query selects the first name, last name, and age columns from the employees table and orders them by age in descending order.
ORDER BY Several Columns Example
ID | NAME | AGE |
---|---|---|
1 | James | 18 |
2 | John | 25 |
3 | Jane | 20 |
4 | Smith | 22 |
SELECT id, name, age
FROM customers
ORDER BY name, age DESC;
This query will select the id, name, and age columns from the customers table and order the results by name in ascending order, followed by age in descending order.
Conclusion
With this clause, he could specify the exact order in which the results would be sorted. He was even able to specify multiple columns to sort by. Akash was so pleased with the results that he shared his story with other database administrators. Soon, ORDER BY clauses became a standard feature of SQL queries. Akash was proud to have played a role in popularizing this powerful tool.
Key takeaways
Quiz
Answer: A) SELECT * FROM table ORDER BY column;
Answer: b. Ascending
Answer: d. INDEX
Answer: d. RANDOM
Top Tutorials
Related Articles