Can you sort by multiple columns?

QuestionsQuestions8 SkillsProDec, 12 2025
0106

Yes, absolutely! You can definitely sort by multiple columns using the ORDER BY clause. This is incredibly useful when your first sorting column might have duplicate values and you need a secondary (or tertiary, etc.) sorting criteria to further organize the results.

The syntax for sorting by multiple columns is to list them, separated by commas, after ORDER BY. You can also specify ASC or DESC for each column independently.

Here's an example based on the current step:

-- Sort by genre (ascending) and then by price (descending) within each genre
SELECT title, genre, price
FROM books
ORDER BY genre ASC, price DESC;

In this query:

  1. The database will first sort all the books by their genre in alphabetical (ascending) order.
  2. Then, for any books that have the same genre, it will further sort those specific books by their price in descending order (from most expensive to least expensive).

This allows for very precise control over how your data is presented. Give it a try!

0 Comments

no data
Be the first to share your comment!