Is there a way to compose the following ORDER BY clause?
select ... order by 1
Above, 1 is the number of a column. This approached is used in Postgres within the union operator:
select ... union select ... order by 1 (the first column)
I've been trying {:order-by 1}, {:order-by [:raw "1"]} , etc, but none of these gave me the right result.ha, it was simple:
(honey.sql/format {:select [:foo] :order-by [:1]})
["SELECT foo ORDER BY 1 ASC"]
yet took some time to figure outI'd use [:inline 1].
it won't work:
(honey.sql/format {:select [:foo] :order-by [:inline 1]})
["SELECT foo ORDER BY inline ASC, ? ASC" 1]Just as with other functions and specials (so, also true for :raw), you gotta wrap it:
(sql/format {:select :x
:from :t
:order-by [[[:raw "1"]]]})
=> ["SELECT x FROM t ORDER BY 1 ASC"]right, and I didn't try 3-level expression.
I've been trying only [] and [[]]
... - an item.
[...] - a collection with one item.
[[...]] - a collection with one item with some space for parameters (aliases for :select, direction for :order).
[[[...]]] - the innermost collection is the item, with no parameters.
yeah I use them in select and from, but never with order-by. Thanks!
And how would you treat the order by in this case? SELECT * FROM items ORDER BY embedding <=> '[...]' This is from PostgresSQL using the extension pgvector
<=> is not known by HoneySQL as an infix operator, so you gotta register it first:
(sql/register-op! :<=>)
=> nil
(sql/format {:select :*
:from :items
:order-by [[[:<=> :embedding [:inline "[...]"]]]]})
=> ["SELECT * FROM items ORDER BY embedding <=> '[...]' ASC"]Sorry I didn't get it. In your query, you use a custom expression which gets executed for each row, and then the database sorts the rows by the values.
But if you want to sort the result of UNION, you don't have the names of the columns but only their numbers. So, order by 1 will sort the whole union result by the first column, which is usually some kind of score/rank
IN your case, it will be something like that:
{:order-by [:<=> :some-field some-value]}It will fail, because of a single vector. :) See my example above.
ah, again 🙂