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

Postgres order by with nulls last #1652

Open
Zhe-Shen opened this issue Jun 23, 2021 · 4 comments
Open

Postgres order by with nulls last #1652

Zhe-Shen opened this issue Jun 23, 2021 · 4 comments

Comments

@Zhe-Shen
Copy link

I'm using Ent with Postgres. When I try to order by a time field with desc order, the null values cause unexpected result with nulls come first, refer to sort-by-column-asc-but-null-values-first. Does Ent support postgres syntax like "order by time desc nulls last" so that nulls come last?

@a8m
Copy link
Member

a8m commented Jun 23, 2021

Hey @Zhe-Shen and thanks for raising this issue.

The index API doesn't support this, but it's going to be added in the upcoming release as we're rewriting the migration framework atm (should be released in a few weeks from now). If you're blocked on this, please ping me on our Slack chanhel and I'll try to help. Thanks 🙏

@a8m a8m added the migration label Jul 11, 2021
@mikebuss
Copy link

mikebuss commented Nov 3, 2021

@a8m was support for this added? Thank you!

@Liooo
Copy link
Contributor

Liooo commented Dec 14, 2022

@a8m

I see nullFirst/Last code in atlas, but seems like this isn't available from ent.
Is there any workaround? Or could you please add the feature? 🙏 We need this one 🥹

@crossworth
Copy link
Contributor

crossworth commented Dec 28, 2022

Import: "entgo.io/ent/dialect/sql"

Define a helper functions:

func NullsLast(column string) string {
	b := &sql.Builder{}
	b.Ident(column).WriteString(" NULLS LAST")
	return b.String()
}

func NullsFirst(column string) string {
	b := &sql.Builder{}
	b.Ident(column).WriteString(" NULLS FIRST")
	return b.String()
}

Usage:

users := client.User.Query().Order(func(s *sql.Selector) {
	s.OrderBy(NullsFirst(sql.Asc(user.FieldName)))
}).IDsX(ctx)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

5 participants