Databases

Lesson 4 - ORDER BY, ASC/DESC and LIMIT

World populations

Lesson Overview

Explore a dataset of world populations produced by the World Bank, and learn how to sort and limit your query results using the ORDER BY and LIMIT clauses.

Sorting and Limiting Results

When working with large datasets, it's essential to sort and limit your results. The ORDER BY clause allows you to sort results in ascending (ASC) or descending (DESC) order, while the LIMIT clause restricts the number of rows returned.

Task: Sort Countries by Population

Try the following queries to explore world population data:

  1. Retrieve the top 5 most populous countries:
    SELECT country, population FROM countries ORDER BY population DESC LIMIT 5
    Top 5 populous countries
  2. Retrieve countries sorted alphabetically:
    SELECT country FROM countries ORDER BY country ASC
    Countries alphabetically
  3. Retrieve the bottom 10 countries by population:
    SELECT country, population FROM countries ORDER BY population ASC LIMIT 10
    Bottom 10 populous countries

Lesson Summary

In this lesson, we've learned how to use ORDER BY to sort query results and LIMIT to restrict the number of rows returned. These clauses are essential for working with large datasets and presenting data in a meaningful way.