TECHNOLOGIESTieInn Technologies

Sorting with ORDER BY

SQL · 16 questions

Short notes

Key idea

ORDER BY sorts the result. It runs near the end, after SELECT, so it can use column aliases. Combined with LIMIT it answers "top N" questions.

Syntax

SELECT name, city, total
FROM customers
ORDER BY city ASC, total DESC
LIMIT 3;
  • ASC (the default) is smallest first; DESC is largest first.
  • Each column has its own direction.
  • NULLS FIRST / NULLS LAST control where missing values go.

Example

The five most expensive products:

SELECT product_name, price
FROM products
ORDER BY price DESC
LIMIT 5;

Traps

  • DESC applies only to the column just before it. ORDER BY city, total DESC sorts city ascending.
  • Ties: if two rows share the 5th price, LIMIT 5 picks one of them arbitrarily. Add a second sort column to make it stable.
  • Text sorts as text: '100' comes before '20' if the column is a string.
  • Databases disagree on NULLs: DuckDB puts them last both ways; PostgreSQL puts them first when sorting descending. Say NULLS LAST when it matters.

Want the full lesson with step-by-step examples, a project and a certificate? SQL course, ₹120 →

Questions

Open in Code Lab5 free questions
5 questions

    Sorting with ORDER BY

  1. Question 1easy

    What is the default sort direction of ORDER BY price?

  2. Sorting with ORDER BY

  3. Question 2medium

    In ORDER BY category, price DESC, how is category sorted?

  4. Sorting with ORDER BY

  5. Question 3medium

    A query has no ORDER BY. Which statement is true?

  6. Sorting with ORDER BY

  7. Question 4medium

    What does this return?

    SELECT price
    FROM (SELECT price FROM products ORDER BY price DESC LIMIT 3)
    ORDER BY price
    LIMIT 1;
  8. Sorting with ORDER BY

  9. Question 5medium

    SELECT order_id FROM orders ORDER BY order_date DESC LIMIT 1; sometimes returns order 53 and sometimes order 54. Both were placed on the same day. What's the best fix?

11 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.