1

I have the following sort in Postgresql:

ORDER BY verified_at NULLS FIRST, name ASC

What I want is having all records with verified_at NULLS first, but only if the field verified_at is not null, then order by name. I don't want the verified_at to have the priority on name if verified_at IS NOT NULL.

With this code, verified_at has the priority on name, after the NULLs are displayed. In fact, is-it possible to have records order by name except for the ones that have verified_at NULL ?

Example of what I want:

verified_at:     name:
NULL             Alex
NULL             Bernard
NULL             Toto
2018             Albert
2012             Boris
2015             Michel
2001             Lena

2 Answers 2

1

You could add a first sorting criteria that checks if the data is null, then order by name:

order by (verified_at is not null)::int, name

Actually using the boolean directly should also work:

order by verified_at is not null, name
Sign up to request clarification or add additional context in comments.

Comments

0

You could order by a CASE expression:

ORDER BY
    CASE WHEN verified_at IS NULL THEN 0 ELSE 1 END,
    name

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.