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.
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:
SQL1SELECT match_id, date, result 2FROM Matches 3ORDER BY YEAR(date) DESC;
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:
SQL1SELECT column_name
2FROM table_name
3ORDER BY column_name ASC|DESC;
To better understand, let's look at a code that you will know how to write by the end of this lesson:
SQL1SELECT match_id, date, result 2FROM Matches 3ORDER BY YEAR(date) ASC;
This code retrieves match IDs, their corresponding match dates, and results from the Matches
table and organizes them in ascending order of their year.
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.
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.