ORDER BY — Complete Guide
ORDER BY — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of PostgreSQL Tutorial on Toolliyo Academy.
On this page
PostgreSQL Tutorial · Lesson 15 of 100
ORDER BY
SQL → Advanced
SQL · 1 — Queries · ~6 min · PostgreSQL — SQL & Queries
What is this?
ORDER BY sorts the final result set by one or more expressions, ascending (ASC) or descending (DESC). NULLS FIRST or NULLS LAST controls where nulls land.
Why should you care?
E-commerce search on PostgresVerse shows cheapest products first — ORDER BY price ASC — or newest reviews — ORDER BY created_at DESC.
See it live — copy this example
Run in pgAdmin or psql.
SELECT product_id, name, price, rating
FROM products
WHERE in_stock = true
ORDER BY rating DESC NULLS LAST, price ASC
LIMIT 20;
What happened?
- Primary sort is highest rating.
- Ties break by lower price.
- NULLS LAST keeps unrated items at the bottom.
- LIMIT returns top 20 after sorting.
Practice next
- Add in_stock boolean and rating numeric columns to products.
- Insert rows with mixed ratings including NULL.
- Run ORDER BY with and without NULLS LAST.
- ORDER BY random() LIMIT 5 for a “deals spotlight” prototype.
- Sort by expression: ORDER BY length(name) DESC for longest names.
Remember
ORDER BY is the last major sort step before LIMIT. Multi-column sorts use left-to-right tie-breaking. NULLS FIRST/LAST avoids surprise null placement.
PostgresVerse search ranking
App shows top-rated in-stock products under ₹500 using this sort pattern.
Outcome: Conversion improves because unrated junk sinks to page two.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!