Google Sheets QUERY: Sort Data
ORDER BY
It is possible to sort the data returned by the QUERY function by specifying the column(s) to consider and the sort order (ascending or descending).
Sort based on one column
To sort the data based on one column, add ORDER BY at the end of the query, followed by the column and the keyword ASC (for ascending sort) or DESC (for descending sort).
For example, to retrieve all data sorted by the number of messages (E) and in descending order, enter:
=QUERY(DB!A1:G15,"SELECT * ORDER BY E DESC")

Sort based on several columns
To sort the data based on several columns, add the columns in sequence separated by commas, specifying the sort order for each column.
For example, to sort by rank (D) descending, then by number of messages (E) descending, then by username (C) ascending, enter:
=QUERY(DB!A1:G15,"SELECT * ORDER BY D DESC, E DESC, C ASC")

Sort grouped data
The following query (seen on the previous page) allows obtaining the sum of messages (E) for each group:
=QUERY(DB!A1:G15,"SELECT D, SUM(E) GROUP BY D")

To sort the data based on the sum of the messages, enter:
=QUERY(DB!A1:G15,"SELECT D, SUM(E) GROUP BY D ORDER BY SUM(E) DESC")
