Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is it possible to use case expression in order-by? #414

Closed
vharmain opened this issue Jul 15, 2022 · 1 comment
Closed

Is it possible to use case expression in order-by? #414

vharmain opened this issue Jul 15, 2022 · 1 comment
Assignees
Labels
documentation I need to write something up!

Comments

@vharmain
Copy link

vharmain commented Jul 15, 2022

I would like to be able to sort by different fields based on a condition. This is supported at least in Postgresql.

SELECT *
FROM my_table
ORDER BY CASE WHEN field_x = 1 THEN field_y ELSE field_z END

I tried to express this in HoneySQL V2:

(sql2/format {:select [:*]
              :from :my-table
              :order-by [:case [:= :field_x 1] :field_y :else :field_z]})

..which yields weird results

=> ["SELECT * FROM my_table ORDER BY case ASC, = FIELD_X, field_y ASC, else ASC, field_z ASC"]

From the docs I can read that :order-by accepts a sequence of one or more ordering expressions. but apparently I want to use a "normal expression" instead of an "ordering expression" in this case.

Is there a workaround how this can be achieved without falling back to raw SQL?

@seancorfield
Copy link
Owner

It's like :select, you need extra nesting:

user=> (sql/format {:select [:*]
  #_=>              :from :my-table
  #_=>              :order-by [[[:case [:= :field_x 1] :field_y :else :field_z]]]})
["SELECT * FROM my_table ORDER BY CASE WHEN field_x = ? THEN field_y ELSE field_z END ASC" 1]
user=>

Because :order-by takes a sequence of order expressions, and an order expression can be:

  • a column name (implicitly :ascending)
  • a pair of column name and direction (:asc or :desc)
  • a pair of an expression and (optional) direction

I'll update the docs to make that clearer.

@seancorfield seancorfield added the documentation I need to write something up! label Jul 15, 2022
@seancorfield seancorfield self-assigned this Jul 15, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation I need to write something up!
Projects
None yet
Development

No branches or pull requests

2 participants