Master sorting results with ORDER BY, limiting the number of rows with LIMIT and removing duplicates with DISTINCT.
Open this lesson in KodokonBy default, the order of the rows returned by a SELECT is not guaranteed: the database returns them however it finds convenient. To impose an order, add ORDER BY followed by a column. Sorting is ascending by default (you can make it explicit with ASC); add DESC for a descending sort.
SELECT title, price FROM books ORDER BY price;
SELECT title, price FROM books ORDER BY price DESC;You can sort on several columns: ORDER BY genre, price DESC sorts first by genre, then, within the same genre, from most expensive to cheapest. The LIMIT clause keeps only the first N rows of the result: combined with ORDER BY, it gives you a "top N". LIMIT 3 OFFSET 2 would additionally skip the first 2 rows.
SELECT title, price FROM books
ORDER BY price DESC
LIMIT 3;One last tool: DISTINCT, placed right after SELECT, removes duplicates from the result. Our table contains 7 books but only 3 different genres: without DISTINCT, the query below would display 7 rows with repetitions.
SELECT DISTINCT genre FROM books;
SELECT DISTINCT author FROM books;