Taking just the top of the list
Real tables have millions of rows. You almost never want all of them. LIMIT n cuts the result off after n rows, and it combines beautifully with ORDER BY:
SELECT title, rating FROM movies ORDER BY rating DESC LIMIT 3;
Sort best-first, keep three: that is a top-3 query. Add OFFSET m to skip the first m rows before counting, which is how apps build page 2 of results: LIMIT 10 OFFSET 10 shows results 11 through 20.
An important habit: LIMIT without ORDER BY gives you some n rows, not the top n. Always sort before you cut.
Code exercise · sql
Run it. Top 3 movies by rating.
Removing duplicates with DISTINCT
Ask for just the genre column and you get one value per row, duplicates included: scifi prints three times. SELECT DISTINCT collapses identical result rows into one:
SELECT DISTINCT genre FROM movies ORDER BY genre;
The next block runs the plain version first, then a divider, then the DISTINCT version so you can see the difference in one output.
Code exercise · sql
Run it. Five genre values before the divider (with repeats), three unique genres after it.
Quiz
A leaderboard query ends with LIMIT 10 but has no ORDER BY. What do you get?
Code exercise · sql
Your turn. Print the title and year of the 2 most recent movies, newest first.
Problem
Your app shows 10 search results per page. A user clicks to page 3. What OFFSET value does the query need (with LIMIT 10)? Answer with a number.