Skip to content

Order By Function Akin To MySQL #3310

@shadyanwar

Description

@shadyanwar

Suggestion

When querying data, most filters are customizable and flexible enough to get the desired results except for the order filter which is very limited to 'propertyName <ASC|DESC>'. Powerful functions in MySQL or statements cannot be used.

Use Cases

  • Using if statements in ordering like ORDER BY IF (`arg1` IS NULL, `arg2`, `arg1`)
  • Using functions like ORDER BY ROUND(`arg`) or ORDER BY GREATEST(`arg1`, `arg2`)
  • Getting on-the-fly values or applying arithmetic operations to the arguments like ORDER BY `quantityOrdered` * `priceEach` or ORDER BY `arg`*2

Not being able to do any of this means having to loop through the results after fetching then doing some processing on them one by one.

Examples

One example is ordering results by more than one property. By default, when the first property is null, it comes up at the top when ordering ascendingly since NULL values are considered lower than any non-NULL values. Here are a few takes on Stackoverflow on the topic. This lingering issue also came up a few years ago in a Gitter discussion inside loopback community.

Here is an example where some products have prices for both local and abroad users while others have a price for only one of them:

MySQL: SELECT ... ORDER BY `feesLocal` ASC, `feesAbroad` ASC gives:

+----+------------+-------------+
| id | feesLocal  | feesAbroad |
+----+------------+-------------+
|  1 |  NULL      |   30       |
|  2 |  10        |   20       |
|  3 |  65        |   NULL     |
+----+------------+-------------+

Which is obviously different from the desired result. But the following:

MySQL: SELECT ... ORDER BY IF (`feesLocal` IS NULL, `feesAbroad`, `feesLocal`)

gives:

+----+------------+-------------+
| id | feesLocal  | feesAbroad |
+----+------------+-------------+
|  1 |  10        |   20       |
|  2 |  NULL      |   30       |
|  3 |  65        |   NULL     |
+----+------------+-------------+

Acceptance criteria

TBD - will be filled by the team.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions