Introduction

Hello again! As we continue our journey through the world of SQL, let's take a quick moment to remember how far we've come. We've worked our way through the basics of SQL, practiced with queries, understood how to select data from tables, and even learned how to filter our data using the WHERE clause and logical operators.

Now, let's explore a new key SQL keyword — ORDER BY — and discover how we can use this to organize and sort our data.

Understanding `ORDER BY` Clause

In SQL, the ORDER BY keyword is used to sort the result set in ascending or descending order. It's an invaluable tool when seeking insights from data and one that you will use frequently. The ORDER BY keyword sorts the records in ascending order by default, but descending order can be applied by using DESC after the column name.

To illustrate how this works, let's say we have a Matches table with columns: match_id, date, and result. If we would like to sort our list of matches by year in descending order, we could use the ORDER BY clause like this:

Linking SELECT with ORDER BY

Remember our dear friend, the SELECT statement? Well, it's back again. This time, however, we're going to pair it up with the ORDER BY clause. The general syntax looks like this:

To better understand, let's look at a code that you will know how to write by the end of this lesson:

This code retrieves match IDs, their corresponding match dates, and results from the Matches table and organizes them in ascending order of their year.

Interpreting Results

Let's break down our SQL query and the output:

  • SELECT match_id, date, result: This part of the command specifies the columns that we want to retrieve from the Matches table.
  • FROM Matches: Here we are specifying the table that we want to retrieve data from.
  • ORDER BY YEAR(date) ASC: The ORDER BY clause sorts the records based on the year. The ASC part specifies that we want the sorting to be in ascending order. The ORDER BY keyword sorts the records in ascending order by default, so the ASC keyword is optional here.

If we run the query, we would see the matches listed in reverse order.

Summary and Preparation for Practice

Great job! Today, you've learned how to sort data in SQL using the ORDER BY clause. Understanding how to arrange your data using ORDER BY is a critical skill as you delve into more complex data analysis.

Prepare for the upcoming practice sections where you will get to flex your SQL muscles by using the ORDER BY clause to sort different aspects of Messi's dataset. Happy sorting!

Just remember, the goal here isn't just to know how to use the ORDER BY clause, but to understand why you use it and when to use it.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal