The ORDER BY clause determines how the rows will be ordered when they are returned. If no order is given, the results will be displayed in an undefined order.

The order fields are comma-separated expressions. Ordering will happen across the fields from left to right (ordering by the first expression, then using the second to resolve ties, and so on). Each expression may optionally have ASC or DESC appended to it to control whether ordering is in ascending or descending order. (Ascending is the default if no direction is specified).

For example:

ORDER BY SUM(tickets.total_user_waiting) DESC

would order a list of users or organizations by their total waiting time, with the highest waiting time at the top.

The ORDER BY clause can access aliases that were specified in the SELECT or GROUP BY clauses using the syntax @'alias' (for example: @'Total Tickets'). Referencing an alias causes the results to be ordered as if you had written the aliased expression in the ORDER BY clause.

For example, suppose you want to make a table showing how many tickets each agent has, sorted in descending order:

SELECT COUNT() AS 'Tickets'
FROM tickets
GROUP BY tickets.agent
ORDER BY @'Tickets' DESC

../_images/reports-order-desc.png

Published: 23/03/2018

Last updated: 22/05/2018