SQL is the Structured Query Language that is used to communicate commands to a database server. It is used by databases like MySQL, PostgreSQL, SQL Server, etc. SQL can be used to insert, delete, update, and search database records. This article will discuss the ORDER BY keyword in SQL.
Order By Keyword in SQL
The ORDER BY keyword in SQL is used to sort the result in ascending or descending order.
Note: By default, the results are sorted in ascending order.
SELECT column1, column2, ...
ORDER BY column1, column2, ... ASC|DESC
For our learning purpose, we will be using the given below data to understand the ORDER BY keyword.
Order By ASC
The following SQL statement selects all the customers from the customer table and sorts them in the ascending order of the first name alphabetically:
As you can see, your data is now sorted in ascending order by “first_name”.
Order By DESC
The following SQL statement selects all the customers from the customer table and sorts them in descending order:
The data is now sorted in descending order by “first_name”.
Order By Several Columns
The following SQL statement selects all customers from the "Customers" table, sorted ascending by the "first_name" and descending by the "city" column. This means that it orders by “first_name”, but if some rows have the same first name, it orders them by city:
Gain expertise in the latest Business analytics tools and techniques with the Post Graduate Program in Business Analysis. Enroll now!
This article discussed the ORDER BY keyword in SQL and how it is used to sort the results. If you wish to learn more about SQL, then check out our SQL certification course.
This SQL certification course gives you all of the information you need to successfully start working with SQL databases and make use of the database in your applications. Learn how to correctly structure your database, author efficient SQL statements, and clauses, and manage your SQL database for scalable growth.