-
Notifications
You must be signed in to change notification settings - Fork 841
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
Bind query Order By with params? #830
Comments
Order By
with either a string
or []string
?Order By
?
What you want is a bit tricky, CREATE TABLE authors (
id BIGSERIAL PRIMARY KEY,
name text NOT NULL,
bio text
);
-- name: ListAuthors :many
SELECT *
FROM authors
ORDER BY CASE
WHEN @order_by::text = 'name' THEN name
WHEN @order_by::text = 'id' THEN id
END; We can go further and change the sort order dynamically but it gets ugly: CREATE TABLE authors (
id BIGSERIAL PRIMARY KEY,
name text NOT NULL,
bio text
);
-- name: ListAuthors :many
SELECT *
FROM authors
ORDER BY CASE
WHEN NOT @reverse::boolean AND @order_by::text = 'name' THEN name
WHEN NOT @reverse::boolean AND @order_by::text = 'id' THEN id
END ASC, CASE
WHEN @reverse::boolean AND @order_by::text = 'name' THEN name
WHEN @reverse::boolean AND @order_by::text = 'id' THEN id
END DESC; Depending on the value of |
@aitva : Using this solution, I got error ERROR: CASE types text and timestamp with time zone cannot be matched (SQLSTATE 42804) or ERROR: CASE types text and integer cannot be matched (SQLSTATE 42804) because my columns are not the same type
|
You can add more CASE statement pairs, one for each type. |
Maybe this exists and I couldn't find anything in the docs: Is it possible to control the sorting on a
:many
query using the input params?When I run the following query, I don't see the ability to pass
OrderBy
in thegetStuffParams
:Since the order by value is a $variable it we be nice if
getStruffParams
would generate something like this, instead:In the case where
order by
is hard-coded in the query, then there wouldn't be a need to add "OrderBy" to the params.It should be possible to mix both:
order by x desc, $1
ororder by $1, x desc
.This pattern would also enable dynamically generating
HAVING
andGROUP BY
clauses.The text was updated successfully, but these errors were encountered: