Learning Goals
By the end of this section you will:
know how to sort a queryβs results
know how to sort using mulitple fields
ORDER BY ClauseΒΆ
The SQL ORDER BY keyword is used to sort the result set of a query by one or more columns, either in ascending (ASC) or descending (DESC) order.
Summary
Sorting in Ascending and Descending Order:
The
ORDER BYkeyword is used to sort the results of a query.By default, it sorts the data in ascending order (ASC).
To sort in descending order, you must use the
DESCkeyword.
Sorting Different Data Types:
Numerical Data: When applied to numerical columns like βPrice,β the clause sorts the values from smallest to largest (ascending) or largest to smallest (descending).
Text Data: For text-based columns such as βProductName,β
ORDER BYwill sort the data alphabetically.
Sorting by Multiple Columns:
You can sort by more than one column to create a more refined, hierarchical sorting of your data.
The data will be sorted based on the first column specified, and then the second column will be used to sort any rows that have the same value in the first column.
Mixing Sort Orders:
It is possible to sort one column in ascending order and another in descending order within the same query. To do this, you specify
ASCorDESCafter each column name in theORDER BYclause.
The video also encourages viewers to visit w3schools.com to practice what theyβve learned
Go to the W3schools Tutorial on the ORDER BY Keyword and complete their exercises.
ORDER BY Activities
Using the Movies database
List all the movies names in ascedning alphabetical order
What is the 5 newest movies in stock?
Display the movies in chronological order, and then alphabetical order within each year.
Using the School Database
List the name of the grade 6 students in alphabetical order
What is the top three results in percentage
List all the boysβ birthdays in order, then all the girlsβ birthdays in order, with their names