Here, we have a country
table and we want to sort the data by LifeExpectancy
in ascending order and Population
in descending order.

Solution –
To sort data in ascending order we use the ASC keyword in SQL and DESC keyword to sort the data in descending order. If you want you can omit the ASC keyword as by default SQL sort the data in ascending order but writing it make it little bit more clear. And the order of the column names in the ORDER BY clause matters. Here we first want to sort the data by LifeExpectancy
, so we write it first then we want to sort by Population
so it goes after it.
SELECT
Name as country,
Continent,
Population,
LifeExpectancy
FROM
country
WHERE LifeExpectancy IS NOT NULL
ORDER BY
LifeExpectancy ASC,
Population DESC

One thought