SQL Order By: Learn With Simple Examples

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.

In this article, we will discuss - 

  • Order by a keyword in SQL
  • Order by ASC
  • Order by DESC
  • Order by several columns

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. 

Syntax: 

SELECT column1, column2, ...

FROM table_name

ORDER BY column1, column2, ... ASC|DESC

For our learning purpose, we will be using the given below data to understand the ORDER BY keyword.

sample-data

Business Analyst Master's Program

Gain expertise in Business analytics toolsExplore Program
Business Analyst Master's Program

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:

orderby-in-SQL-asc

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:

orderby-desc

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:

orderbyseveral

Gain expertise in the latest Business analytics tools and techniques with the Post Graduate Program in Business Analysis. Enroll now!

Conclusion

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.

About the Author

Aryan GuptaAryan Gupta

Aryan is a tech enthusiast who likes to stay updated about trending technologies of today. He is passionate about all things technology, a keen researcher, and writes to inspire. Aside from technology, he is an active football player and a keen enthusiast of the game.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.