Using ORDER BY to Sort Results

If you want to sort output using a field that is not the table's primary key, then specify an index. For example, if we want to query based on a Timestamp and sort the results in descending order by the timestamp:

sql-> SELECT id, firstname, lastname, lastLogin FROM Persons;
 +----+-----------+----------+--------------------------+
 | id | firstname | lastname |        lastLogin         |
 +----+-----------+----------+--------------------------+
 |  3 | John      | Morgan   | 2016-11-29T08:21:35.4971 |
 |  4 | Peter     | Smith    | 2016-10-19T09:18:05.5555 |
 |  2 | John      | Anderson | 2016-11-28T13:01:11.2088 |
 |  5 | Dana      | Scully   | 2016-11-08T09:16:46.3929 |
 |  1 | David     | Morrison | 2016-10-29T18:43:59.8319 |
 +----+-----------+----------+--------------------------+

5 rows returned
sql-> create index tsidx1 on Persons (lastLogin);
Statement completed successfully
sql-> SELECT id, firstname, lastname, lastLogin 
FROM Persons ORDER BY lastLogin DESC;
 +----+-----------+----------+--------------------------+
 | id | firstname | lastname |        lastLogin         |
 +----+-----------+----------+--------------------------+
 |  3 | John      | Morgan   | 2016-11-29T08:21:35.4971 |
 |  2 | John      | Anderson | 2016-11-28T13:01:11.2088 |
 |  5 | Dana      | Scully   | 2016-11-08T09:16:46.3929 |
 |  1 | David     | Morrison | 2016-10-29T18:43:59.8319 |
 |  4 | Peter     | Smith    | 2016-10-19T09:18:05.5555 |
 +----+-----------+----------+--------------------------+

5 rows returned 

SQL for Oracle NoSQL Database can also sort query results by the value of fields nested inside records, if again, an index on the nested field (or fields) exists. For example, to create an index and then order by state:

sql-> create index indx1 on Persons (address.state);
Statement completed successfully
sql-> SELECT id, $p.address.state FROM
Persons $p ORDER BY $p.address.state;
 +----+-------+
 | id | state |
 +----+-------+
 |  3 | FL    |
 |  4 | MA    |
 |  5 | NJ    |
 |  1 | TN    |
 |  2 | WI    |
 +----+-------+

5 rows returned 

To learn more about indexes see Working With Indexes.