The ORDER BY clause within SQL controls the
order of the records that are output. Ordering within a view is
controlled by the value of the key. However, the key also
controls and supports the querying mechanism.
In SELECT statements where there is no
explicit WHERE clause, the emitted key can
entirely support the sorting you want. For example, to sort by
the city and salesman name, the following
map() will achieve the required sorting:
function(doc, meta) { emit([doc.city, doc.name], null) }
If you need to query on a value, and that query specification is part of the order sequence then you can use the format above. For example, if the query basis is city, then you can extract all the records for 'London' using the above view and a suitable range query:
?endkey=["London\u0fff"]&startkey=["London"]
However, if you want to query the view by the salesman name, you
need to reverse the field order in the
emit() statement:
function(doc, meta) { emit([doc.name,doc.city],null) }
Now you can search for a name while still getting the information in city order.
The order the output can be reversed (equivalent to
ORDER BY field DESC) by using the
descending query parameter. For more
information, see
Section 9.8.5, “Ordering”.