SQL ORDER BY, explained

Without ORDER BY a database may return rows in any order. ORDER BY sorts the result by one or more columns, smallest first unless you add DESC.

LIMIT keeps only the first few rows, and OFFSET skips some rows first, which is how "top 10" lists and pagination work.

Examples

1. Most expensive first

SELECT name, price
FROM products
ORDER BY price DESC;

DESC sorts from highest to lowest.

2. Top 3 most recent

SELECT id, order_date
FROM orders
ORDER BY order_date DESC
LIMIT 3;

Sort newest first, then keep only three rows.

Practice ORDER BY

4 questions, easiest first. Your progress is saved on this device.

  • โ—‹Most expensive firsteasy
  • ๐Ÿ”’Sort by two columnsmedium
  • ๐Ÿ”’Top 3easy
  • ๐Ÿ”’Page twomedium
Practice ORDER BY