How to Sort in SQL Database: Standard SQL MySQL PostgreSQL Oracle MS SQL Server SQLite Operators: ORDER BY Table of Contents Problem: Example: Solution: Discussion: Problem: You would like to sort the result of an SQL query in ascending or descending order. Example: Our database has a table named salary_information with data in the columns id, first_name, last_name, and monthly_earnings. We want to sort the employees by their monthly_earnings in descending order. idfirst_namelast_namemonthly_earnings 1CalvinRios3500 2AlanPaterson4000 3KurtEvans2300 4AlexWatkins5500 Solution: We will use an ORDER BY clause. Here is the query: SELECT first_name, last_name, monthly_earnings FROM salary_information ORDER BY monthly_earnings DESC; Here is the result of the query: first_namelast_namemonthly_earnings AlexWatkins5500 AlanPaterson4000 CalvinRios3500 KurtEvans2300 Now, we can see that Alex Watkins is first on the list, which means he earns the most money. Discussion: Use an ORDER BY clause if you want to sort the dataset in either ascending or descending order. The syntax for an ORDER BY clause is as follows: SELECT col1, col2, … FROM table ORDER BY col1, col2, … ASC|DESC; In the above, ASC|DESC means that you should choose either the keyword ASC (ascending) or DESC (descending) to order the dataset the way you want. Besides sorting by numeric columns, you can also sort by text columns. An ORDER BY clause will sort text columns in alphabetical order. Instead of the column name, you can also use the position of the column counting from the left. So, in our example, instead of writing: ORDER BY monthly_earnings DESC you can also write: ORDER BY 3 DESC If you want to sort the table from the example by the first_name column in alphabetical (ascending) order, you can use the following query: SELECT first_name, last_name, monthly_earnings FROM salary_information ORDER BY first_name ASC; It is also worth noting that you can sort by multiple columns. This is helpful when some values in a given column are repeated and you need additional sorting. In this case, separate the column names with commas in the ORDER BY clause. You can even sort in ascending order by one column and in descending order by another. The following illustrates the syntax of this combination: ORDER BY Col1 ASC, Col2 DESC; If you omit the ASC or DESC keyword, an ascending sort is performed by default. Recommended courses: SQL Basics SQL Practice Set Recommended articles: SQL Basics Cheat Sheet What Does ORDER BY Do? How ORDER BY and NULL Work Together in SQL How to Sort Records with the ORDER BY Clause See also: How to Order Alphabetically in SQL How to Order by Count in SQL? How to Order By Two Columns in SQL? How to Order Rows by Group Sum in SQL Subscribe to our newsletter Join our monthly newsletter to be notified about the latest posts. Email address How Do You Write a SELECT Statement in SQL? What Is a Foreign Key in SQL? Enumerate and Explain All the Basic Elements of an SQL Query