We use cookies to enhance your experience on the site
CodeWorlds

Sorting by multiple columns

One field is sometimes not enough. When many scrolls share the same value - for instance several books published in the same year - you need a second criterion to break the tie.

Two fields separated by a comma

In

ORDER BY
you can give several fields, separating them with a comma:

1SELECT tytul, rok_wydania
2FROM ksiazki
3ORDER BY rok_wydania DESC, tytul ASC;

The Library sorts first by the first field (

rok_wydania
descending). Only when several books came out in the same year does it reach for the second field (
tytul
ascending) and line them up alphabetically.

Each field has its own direction

Each column may have its own

ASC
or
DESC
:

1SELECT imie, nazwisko, kraj
2FROM autorzy
3ORDER BY kraj ASC, nazwisko ASC;

First we group the authors by country (alphabetically), and within each country we arrange them ascending by surname.

Why break ties?

  • The result becomes predictable - the same set of data always lines up the same way.
  • Reports are clearer - the data has a distinct, two-level order.

Remember, @name: the first field rules, and the next ones step in only on a tie. That is how a scribe tidies even the most crowded shelf.

Go to CodeWorlds