The Final Touch: Ordering Your Results
The Friday Finale
It was the end of my first week. My final task was to present the "Top 10 most expensive products" to the board. I had the `SELECT`, I had the `FROM`, and I had the `WHERE`.
But the list was a mess. The expensive items were scattered among the cheap ones. It didn't look like a "Top 10" list; it looked like a spreadsheet.
The Quest: Sorting the Chaos
Data is only useful if it’s organized. In SQL, we use the `ORDER BY` clause to sort our results. Whether it's sorting by Price, Date, or Alphabetical name, this is how you make your data "Presentable."
The Implementation: Climbing the Ladder
To sort, you tell SQL which column to use and which direction to go:
-- Sorting by price, highest first
SELECT
product_name,
price
FROM
products
ORDER BY
price DESC;
Multiple Sorters
You can even sort by many things at once. For example, sort by `category` (A-Z) and then `price` (High to Low).
SELECT *
FROM products
ORDER BY category ASC, price DESC;
The "Oops" Moment
I once forgot to specify `DESC` when looking for the latest orders. I ended up looking at the very first order from 2012 instead of the one from five minutes ago.
**Pro Tip**: SQL defaults to `ASC`. If you want the most recent or the most expensive, always remember to add `DESC`.
The Victory
The board saw a perfectly sorted list. They didn't have to scroll or search; the most important information was right at the top. I realized that a good analyst doesn't just "find" answers—they "arrange" them.
Your Task for Today
Take your query from Day 2 and add an `ORDER BY` clause to a numerical column. Try it both with `ASC` and `DESC` to see how the "Top" of your data changes.
*Day 6: Limiting the Scope—LIMIT and OFFSET.*