Sorting results with ORDER BY #
So far, the rows we get back from a query come out in whatever order the database happens to store them in. The ORDER BY clause lets us control that order.
SELECT
column_name
FROM
table
ORDER BY
column_name;
ORDER BY column_name: Sorts the result by the given column, from smallest to largest (ascending) by default.
You can also sort by a column you are not even selecting, and you can sort by multiple columns by separating them with a comma:
SELECT
first_name,
last_name
FROM
customers
ORDER BY
last_name,
first_name;
This sorts the rows by last_name first, and for rows that share the same last_name, sorts them by first_name.
Exercise #
Write a command that retrieves all columns from the customers table, sorted by age from youngest to oldest.
Tests #
- The result has an
agecolumn. - The rows are sorted by
agefrom smallest to largest.
Solution
SELECT
*
FROM
customers
ORDER BY
age;
Basic Data Retrieval
Filtering Data
Aggregating Data
Joining Tables
Creating and Managing Tables
Transactions and Data Integrity