ORDER BY: How to sort data in SQL using ORDER BY clause

  • by

This tutorial helps you to understand, how to sort the result set of an SQL query by one or more columns using ORDER BY clause.

You should be already aware of SELECT FROM SQL statement. The SELECT FROM is used to get the records from a table. To sort the output of this query, we simply add the ORDER BY keyword to the SELECT query. Here’s the example:

SELECT *
FROM actor
ORDER BY last_update ASC
Try this query in dbHarbor for free

This query prints out records from the actor table sorted by last_update column in the ascending order (oldest first).

How to sort data using ORDER BY in dbHarbor

Also, we can get records in the descending order using DESC keyword (newest first):

SELECT *
FROM purchases
ORDER BY purchase_date DESC
Try this query in dbHarbor for free

Multiple orders in one query

Suppose you want to get all purchases sorted by the price and additionally you want to see the latest purchases first. It can be done by applying multiple columns to the ORDER BY clause. Here is an example:

SELECT *
FROM purchases
ORDER BY price DESC, purchase_date DESC
Try this query in dbHarbor for free

This query will select all records from the purchases table and sort them first by the price in the descending order (like 99.99, 89.99,...). So you will get many records for each price. In other words, the records will be grouped by the price. When SQL performs ORDER BY for the second column(purchase_date), it will sort all records by purchase_date field within each group in the descending order.


Download dbHarbor for free and try out these queries ⚓️  dbHarbor is a native macOS tool with intuitive UI to manage SQLite databases.


Don’t miss the latest news about our development journey and SQL tutorials. Signup for our newsletter. Promise not to SPAM😎

Leave a Reply

Your email address will not be published. Required fields are marked *