Multiple levels of ordering query results

Often you need to order results on more than one column or property. For example, you query addresses and want them ordered by city. Within a city, you want them ordered by postal code. Within a postal code, you want them ordered by street. In this example, you want three levels of ordering: city, postal code, and street.

The following SQL statement specifies three levels of ordering for addresses.

SELECT * FROM addresses
  ORDER BY city, postal_code, address_line1;

The following Gosu code constructs and executes a query that is functionally equivalent to the preceding SQL example.

uses gw.api.database.Query 
uses gw.api.database.QuerySelectColumns
uses gw.api.path.Paths

var queryAddresses = Query.make(Address) // Query for addresses. 
var resultAddresses = queryAddresses.select()

// Sort results by city.
resultAddresses.orderBy(QuerySelectColumns.path(Paths.make(Address#City)))
// Within a city, sort results by postal code.
resultAddresses.thenBy(QuerySelectColumns.path(Paths.make(Address#PostalCode)))
// Within a postal code, sort results by street.
resultAddresses.thenBy(QuerySelectColumns.path(Paths.make(Address#AddressLine1)))

You can call the ordering methods thenBy and thenByDescending as many times as you need.