How do you get the 5 most expensive products?
Options
- SELECT * FROM products ORDER BY price LIMIT 5;
- SELECT * FROM products ORDER BY price DESC LIMIT 5; (Correct option)
- SELECT TOP price FROM products;
- SELECT * FROM products WHERE price = MAX;
Answer
SELECT * FROM products ORDER BY price DESC LIMIT 5;
Why
ORDER BY price sorts from smallest to largest by default (ASC). Adding DESC sorts from largest to smallest.
LIMIT 5 keeps only the first 5 rows of that sorted result.
Without DESC you would get the 5 CHEAPEST products.
Remember
ORDER BY ... DESC LIMIT n = top n.