Sorting, limiting and DISTINCT
Put rows in order, take the top few, and list each value only once.
15 min
A table has no built-in order. Without ORDER BY, the database may return rows in any order, and that order can change. If order matters, ask for it.
SELECT title, price FROM books ORDER BY price DESC;ASC (smallest first) is the default; DESC is largest first. Sort by more than one column to break ties:
ORDER BY genre, price DESCThat sorts by genre A to Z, and within each genre by price from highest to lowest.
LIMIT n returns at most n rows. With ORDER BY it answers "the top 3":
SELECT title, price FROM books ORDER BY price DESC LIMIT 3;LIMIT 3 OFFSET 3 skips the first three rows and returns the next three, which is how pages of results work.
SELECT genre FROM books lists a genre once per book. SELECT DISTINCT genre FROM books lists each genre once.
You must write them in this order: SELECT, FROM, WHERE, ORDER BY, LIMIT. SQL runs them in a different order from how it reads: first FROM, then WHERE, then SELECT, then ORDER BY, then LIMIT. That is why you can sort by a column alias but not filter by one.
How the database actually works through a query.
Show the title and price of the three most expensive books, most expensive first.
Tables you can query
- books (id, title, author, genre, price, year, stock)
SELECT title, price FROM booksList each author once, in alphabetical order (A to Z).
Tables you can query
- books (id, title, author, genre, price, year, stock)
SELECTShow the title and genre of books that are in stock (stock above 0), sorted by genre A to Z, and within each genre by title A to Z.
Tables you can query
- books (id, title, author, genre, price, year, stock)
SELECT title, genre FROM booksReading order of a query
- Without
ORDER BYthe row order is not guaranteed. DESCreverses a sort; list several columns to break ties.LIMITkeeps the first rows, so pair it withORDER BY.DISTINCTremoves duplicate rows from the result.
Sorting checks.
Which returns the 5 cheapest books?
- A`ORDER BY price DESC LIMIT 5`
- B`ORDER BY price LIMIT 5`
- C`LIMIT 5 ORDER BY price`
- D`WHERE price < 5`
Put the clauses in the order you must write them.
- AFROM
- BORDER BY
- CSELECT
- DWHERE
- ELIMIT
What does SELECT DISTINCT genre FROM books return for our data?
- A10 rows
- B4 rows
- C1 row
- D2 rows
ORDER BY genre, price DESC sorts...
- Aby price, then genre
- Bby genre A-Z, then price high to low within genre
- Conly by genre
- Drandomly
LIMIT 3 OFFSET 3 skips how many rows?
Practise this lesson, not just read it
In BiliMind the questions above are marked when you answer, the flashcards come back on a schedule, and the rest of SQL for Beginners is planned around your week. Free.