Function: ORDER BY
The ORDER BY function in Wonderful Relations allows queries to sort results based on fields or custom conditions. This ensures that data is displayed in a structured and meaningful order.
Sorting can be applied to existing query fields or custom conditions, including calculations and transformations.
Note: ORDER BY does not affect queries used by DataTables, because DataTables has its own ORDER BY column schema.
Parameters
Field
Defines a query field to be used for ordering. This is optional, as ordering can also be based on a condition.
Condition
Allows sorting based on a custom expression instead of a direct field. Useful for sorting by computed values or special logic.
Order
Defines the sorting direction:
ASC
– Ascending orderDESC
– Descending order
Field Order
Specifies the priority of multiple ORDER BY clauses when more than one sorting rule is applied.
Example
Ordering with a CASE Statement Sorting data dynamically based on a condition:
ORDER BY CASE WHEN field = 'A' THEN 1 ELSE 0 END, title ASC
This ensures that all rows with field = 'A'
appear at the top, followed by others ordered alphabetically by title.
Conclusion:
The ORDER BY function provides flexibility and control over query results, allowing both simple and complex sorting logic.