CSE Roadmap

Core tier · about 3 hours · 5 parts

Part 3 of 5 · 1 min read

Sorting with ORDER BY

Ascending and descending order, and sorting by more than one column.

Think of sorting a stack of forms first by last name, and within each matching name, by the date they were submitted.

In plain words: ORDER BY sorts a result by one or more columns. ASC means ascending, smallest or earliest first, and is the default if nothing is written. DESC means descending, largest or latest first. Listing more than one column sorts by the first column first. The next column only breaks ties within equal values of the first.

A worked example. Listing orders newest first, and for orders placed on the exact same day, breaking ties by the largest order ID first.

The key lines.

SELECT order_id, placed_on
FROM orders
ORDER BY placed_on DESC, order_id DESC;

ORDER BY, ascending, descending

ORDER BY sorts a query's result. Ascending order (ASC, the default) goes from smallest to largest. Descending order (DESC) goes from largest to smallest.

Example: ORDER BY placed_on DESC lists the most recent orders first.