Sikau

Databases and SQL · Day 3 · about 25 min

Sorting and shaping results

ORDER BY, LIMIT, DISTINCT, aliases and expressions.

Top 3, newest first

Most screens show sorted, limited, tidied data: the 5 newest orders, the cheapest dishes, prices with tax. SQL can do all of that before the data ever reaches your app.

ORDER BY, LIMIT, AS, DISTINCT

SELECT name, price FROM dishes ORDER BY price DESC LIMIT 3;

SELECT name, price, round(price * 1.13) AS price_with_tax FROM dishes ORDER BY name;

SELECT DISTINCT city FROM customers ORDER BY city;

SELECT name, joined FROM customers ORDER BY joined DESC LIMIT 2 OFFSET 1;
  • Without ORDER BY, the database may return rows in any order — never rely on it.
  • Sort by several columns: ORDER BY category, price DESC.

The rest of this lesson

  • Pages of resultsexplain
  • Expressions and aliasesexplain
  • Which dish?predict
  • Which clause?match
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 17 lessons of Databases and SQL