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 ASCTry 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).
Also, we can get records in the descending order using DESC keyword (newest first):
SELECT * FROM purchases ORDER BY purchase_date DESCTry 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 DESCTry 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.
Don’t miss the latest news about our development journey and SQL tutorials. Signup for our newsletter. Promise not to SPAM😎