Sort Results Part 1
Part of the Fundamentals section of Coddy's SQL journey — lesson 13 of 72.
When querying a database, organizing your results in a meaningful order can make data analysis much more efficient. To sort the result we use the ORDER BY keyword and after that, we should specify by which field we are ordering by. By default, it sorts by ascending order.
For example consider the following <strong>competition</strong> table:
| runner_id | age | avg_speed |
|---|---|---|
| 1 | 47 | 3.65 |
| 2 | 62 | 3.07 |
| 3 | 57 | 6.82 |
| 4 | 56 | 4.34 |
| 5 | 25 | 4.93 |
| 6 | 40 | 3.94 |
| 7 | 23 | 6.58 |
| 8 | 40 | 3.43 |
SELECT *
FROM competition
WHERE age > 50
ORDER BY avg_speedThis is the result
| runner_id | age | avg_speed |
|---|---|---|
| 2 | 62 | 3.07 |
| 4 | 56 | 4.34 |
| 3 | 57 | 6.82 |
To specify how to sort that data we can add DESC or ASC keywords after the name of the column.
ORDER BY avg_speed ASCChallenge
EasyAvailable tables and columns:
<strong>feathers</strong>:<strong>id</strong>,<strong>weight</strong>
Return all of the ids after ordering them by the weight in descending order
Cheat sheet
Use ORDER BY to sort query results. By default, it sorts in ascending order:
SELECT *
FROM table_name
ORDER BY column_nameTo specify sort direction, add ASC (ascending) or DESC (descending):
ORDER BY column_name DESC
ORDER BY column_name ASCTry it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4More Keywords
The IN keywordThe BETWEEN keywordThe LIKE keywordThe AS keywordRecap - Cellphone Models2Conditions
Conditions BasicsThe AND keywordThe OR keywordThe NOT keywordMultiple Conditions CombinedParenthesisBooleans5Arithmetic Operations
Mathematical OperatorsMathematical ColumnsThe Modulo OperationThe ROUND() Function3Specific Return Format
Null valuesSort Results Part 1Sort Results Part 2Recap - Cyber Security FirmLimit number of recordsRecap - Vehicle Factory6Intro Challenges
Recap - Parliamentary ElectionRecap - Police Criminal ArrestRecap - Bar Beverage ContainerRecap - Engineer new columns