In a multiple-column sort, the columns are processed from left to right in the order they appear after the ORDER BY clause.
Here is how the logic works:
- Primary Sort: SQL sorts the data based on the first column specified.
- Secondary Sort: Only if there are rows with the exact same value in the first column does SQL look at the second column to determine their relative order.
- Subsequent Sorts: This pattern continues for any additional columns listed.
Example Analysis
Based on your command history:
ORDER BY genre ASC, price DESC;
- Step 1: SQL first groups all "Mystery" books together and all "Technical" books together (Alphabetical order).
- Step 2: Within the "Mystery" group, it looks at the
price. Since you specifiedDESC, it puts the most expensive Mystery book first. - Step 3: It does the same for the "Technical" group, sorting those specific rows by price descending.
Key Rule: Each column can have its own direction (ASC or DESC). If you don't specify one, it defaults to ASC (ascending).