Limiting results with LIMIT #
Sometimes a table has far more rows than you need. The LIMIT clause caps the number of rows a query returns:
SELECT
column_name
FROM
table
LIMIT
number;
number: The maximum number of rows to return.
LIMIT is commonly combined with ORDER BY to answer questions like "who are the 3 oldest customers?":
SELECT
first_name,
last_name
FROM
customers
ORDER BY
age DESC
LIMIT
3;
Without ORDER BY, LIMIT just returns however many rows the database happens to return first, which is not guaranteed to mean anything.
Exercise #
Write a command that retrieves the first_name and age columns from customers, sorted by age from oldest to youngest, and returns only the oldest 3 customers.
Tests #
- The result has an
agecolumn. - The result contains exactly 3 rows.
- The rows contain the 3 oldest customers, sorted from oldest to youngest.
Solution
SELECT
first_name,
age
FROM
customers
ORDER BY
age DESC
LIMIT
3;
Basic Data Retrieval
Filtering Data
Aggregating Data
Joining Tables
Creating and Managing Tables
Transactions and Data Integrity