21

I need to write a sql statement to select all users ordered by lastname, firstname. This is the part I know how to do :) What I don't know how to do is to order by non-null values first. Right now I get this:

null, null
null, null
p1Last, p1First
p2Last, p2First

etc

I need to get:

p1Last, p1First
p2Last, p2First
null, null
null, null

Any thoughts?

0

3 Answers 3

36

See Sort Values Ascending But NULLS Last

basically

SELECT *
    FROM @Temp
    ORDER BY CASE WHEN LastName IS NULL THEN 1 ELSE 0 END, LastName
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

Nowadays the
IIF ( boolean_expression, true_value, false_value )

will suit too.

ORDER BY IIF(name IS NULL, 1, 0), 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.