Skip to the content

ORDER BY

SQL · Unit 3: Sorting and limiting

Up to now the catalog has always looked the same, with the Keyboard on top and the Speaker at the bottom. That's how someone entered them, and it's no use to any customer.

What's the cheapest thing in the store, and what comes next? ORDER BY goes at the end of the query, after the WHERE if there is one, and says which column the rows are sorted by. They go from lowest to highest.

SELECT name, price
FROM products
ORDER BY price;

Returns

nameprice
Cable5.25
Mouse19.9
Keyboard45.5
Headphones59.9
Speaker74
Monitor189
Tablet320
Laptop899

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    Someone wants to spend between 40 and 200, and see the cheapest first. What does this query return?

  2. 2. Multiple choice

    The weekly orders report has no ORDER BY, and for months it has listed them from the oldest order to the newest. What guarantees it looks the same on Monday?

  3. 3. Complete the code

    Someone is looking for a gift under 100 and wants to see the most expensive first, so the gift doesn't look cheap. Fill in the blanks.

  4. 4. Predict the output

    The store is inviting its customers under 30 to a workshop. Whoever is at the door wants the list in alphabetical order, to find each name fast. What does this query return?

  5. 5. Find the bug

    The history for Luke, customer 2, should start with his most recent order. The query runs without an error, but the history comes out backward. Which line has the problem?

  6. 6. Put the lines in order

    The store is giving its Denver customers a free course and forming the groups by age. Put in order the query that shows each one's name and age, from youngest to oldest. One line doesn't belong.

  7. 7. Complete the code

    The printed catalog ends with an index of what's in stock, to look up each product by name, from A to Z. Fill in the blank.

  8. 8. Predict the output

    Here the sort is on a column the SELECT doesn't show. In Accessories, the Keyboard costs 45.5, the Mouse 19.9, and the Cable 5.25. What does this query return?

  9. 9. Put the lines in order

    The keyboards and the mice, products 1 and 2, went out with a defect. Someone has to call the people who ordered them, starting with the most recent order. Put the query in order. One line doesn't belong.

  10. 10. Write the code

    The store is launching a discount for its customers over 30 that grows with age, and wants whoever gets the most at the top of the list. Write a query that shows the name and the age of those customers, in that order, starting with the oldest.

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →