Sorting in descending order #
By default, ORDER BY sorts from smallest to largest. To reverse the order, add the DESC keyword after the column name:
SELECT
column_name
FROM
table
ORDER BY
column_name DESC;
If you want to be explicit about the default ascending order, you can add ASC instead, although it is optional since it is the default:
SELECT
column_name
FROM
table
ORDER BY
column_name ASC;
You can even mix directions when sorting by multiple columns:
SELECT
first_name,
last_name
FROM
customers
ORDER BY
last_name DESC,
first_name ASC;
Exercise #
Write a command that retrieves all columns from the customers table, sorted by age from oldest to youngest.
Tests #
- The result has an
agecolumn. - The rows are sorted by
agefrom largest to smallest.
Solution
SELECT
*
FROM
customers
ORDER BY
age DESC;
Basic Data Retrieval
Filtering Data
Aggregating Data
Joining Tables
Creating and Managing Tables
Transactions and Data Integrity