Multiple level ordering
To sort on multiple levels use the ORDER BY
clause, establishing preferences by defining the column sequence:
List columns sequentially in the ORDER BY
clause, prioritizing the first column for primary sort, followed by secondary sort using the second column, and so forth. Apply ASC
for ascending order or DESC
for descending.
Take for example, sorting employees by department and then by descending order of salary:
The resulting output will list employees organized by department, and within each department, salaries will be listed from highest to lowest.
Complex ordering with LIMIT
At times, you may need to limit results before applying additional sorting criteria. In SQLite, complex multi-level ordering can be implemented using nested SQL commands:
The above query does the following:
- The inner query (or is it the dream within a dream?) sorts employees by their rating scores in descending order and limits the output to the top 20 entries.
- The outer query then organizes these shortlisted 20 records further by arranging them in ascending order of names.
This strategy achieves a two-tier sorting effect and ensures you get a highly tailored and specific subset of data.
Compound ordering in multi-table situations
When working with complex datasets encompassing multiple joined tables or when multiple attributes need to be considered for sorting, nested SQL commands or Common Table Expressions (CTEs) can provide a reliable solution for sophisticated multi-level ordering:
Useful techniques featured in this scenario:
- CTEs: for a cleaner and more organized approach to multi-tiered sorting.
ROW_NUMBER()
: to assign ranks to employees within their respective departments based on descending order of salaries.PARTITION BY
: to apply the sorting rules individually to each department subgroup.- The
WHERE
clause is used further to filter out only the top 5 earners from each department.
Dynamic ordering with CASE statement
In SQL, the CASE
statement offers dynamic sorting capabilities when certain conditions need to be accounted for in the sorting process:
The CASE
statement here determines the sort ordering based on whether a specific condition is met: entries that satisfy the condition are prioritized and arranged before others. Sorting by col2
only comes into play after this.
Handling TIMESTAMPs in sorting
When working with TIMESTAMP
data, especially those sans time zones, you may need to sort by date alone ignoring the time component:
Here, entries are sorted based on date extracted from a timestamp, leaving out the time. This is a neat trick to know for handling timestamps!
Was this article helpful?