Ordering results

By default, SQL Select statements and the query builder APIs return results from the database in no specific order. Results in this apparently random order might not be useful. SQL and the query builder APIs support specifying the order of items in the results.

With SQL, the ORDER BY clause specifies how the database sorts fetched data. The following SQL statement sorts the result set on the postal codes of the addresses.

SELECT * FROM addresses
  WHERE city = "Chicago"
  ORDER BY postal_code;

The following Gosu code uses the orderBy ordering method to sort addresses in the same way as 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 in Chicago. 
queryAddresses.compare(Address#City, Equals, "Chicago")
var selectAddresses = queryAddresses.select()

// Sort the result by postal code.
selectAddresses.orderBy(QuerySelectColumns.path(Paths.make(Address#PostalCode))) 

var resultAddresses = selectAddresses.iterator() // Execute the query and iterate the ordered results.

The query builder APIs use the object path expressions that you pass to ordering methods to generate the ORDER BY clause for the SQL query. Gosu does not submit the query to the database until you begin to iterate a result object. The database fetches the items that match the query predicates, sorts the fetched items according to the ordering methods, and returns the result items in that order.