SQL ORDER BY and LIMIT
Sort the rows by name and take only the first five.
All lessons · SQL lessons: read, sort, count
ORDER BY: sort
ORDER BY sorts the rows by one column. DESC after the name reverses the order, from large to small.
SELECT name FROM users ORDER BY name;
LIMIT: take a few
LIMIT says how many rows come back. Sort with ORDER BY first, then keep the first five with LIMIT 5. A query without a limit can be heavy on a large table.
SELECT name FROM users ORDER BY name LIMIT 5;
Questions
What is the order without ORDER BY? The database’s own order. Do not rely on it.
What does LIMIT 5 bring? Only five of the matching rows.
Do you write LIMIT first and ORDER BY after? No. Sort first, then cut. ORDER BY comes before LIMIT.
What is DESC? Descending order. For example so the newest date stays on top.