Welcome back! Now that we've covered the basics of SQL, the SELECT
statement, and how to filter data using the WHERE
clause, it's time to learn how to sort data. Sorting data can be incredibly useful. For instance, whether you're ranking movies by their budgets or arranging them by their IMDb ratings, sorting helps you find and analyze your data more effectively.
The ORDER BY
clause in SQL is used to sort the records fetched by the SELECT
statement. Instead of getting results in an arbitrary order, you can specify how the data should be sorted. The ORDER BY
clause does this by allowing you to define one or more columns to sort by.
The syntax for the ORDER BY
clause is straightforward. Here’s what it looks like:
SELECT column1, column2
specifies the columns we want to retrieve.FROM table_name
specifies the table from which to retrieve the data.ORDER BY column1
specifies the column by which the results should be sorted.
By default, the ORDER BY
clause sorts data in ascending order (from lowest to highest). However, you can also sort data in descending order (from highest to lowest) by using the DESC
keyword. For clarity, it is recommended to also include the ASC
keyword even though ORDER BY
sorts in ascending order by default.
Let's sort our dataset by the budget_million_usd
column in ascending order.
ORDER BY budget_million_usd ASC
sorts the retrieved records by the budget_million_usd column in ascending order. This means the results will be arranged starting from the lowest budget to the highest budget. This can be seen in the output:
Here we sort the same dataset by the imdb_rating
column but in descending order by adding the DESC
keyword.
In the output, we can see the table lists the movies starting from the highest imdb_rating
of 8.4 down to 6.1.
The ORDER BY clause is not limited to sorting numerical values. It can also sort rows by alphabetical order. The default ordering is alphabetical order (ascending), but using DESC
, the output is in reverse alphabetical order. Let's take a look:
The output shows the movies starting from "Ant-Man" down to "Thor: The Dark World":
In this lesson, we've learned how to use the ORDER BY
clause to sort data, specifying both ascending and descending order. We also walked through a real-world example of sorting movie data by budget, IMDb rating, and name.
As you move forward, try practicing with different columns and combinations to refine your skills. Up next, you'll get the chance to practice these concepts through hands-on exercises.
Good luck, and happy querying!
