Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order by column with null values last in entity framework

Does anyone know how to return an ordered list of strings with null values last? I have something like this:

using(var context = new DomainEntities()) {     var result = context.Users.OrderBy(u => u.LastName).ThenBy(u => u.FirstName); } 

My problem though is that this query returns null values before non-null values.

Any thoughts?

like image 257
devlife Avatar asked May 11 '10 21:05

devlife


People also ask

How do you sort null last?

If you specify the ORDER BY clause, NULL values by default are ordered as less than values that are not NULL. Using the ASC order, a NULL value comes before any non-NULL value; using DESC order, the NULL comes last.

How is NULL treated in order by?

If you sort a column with NULL values in ascending order, the NULLs will come first. Alternatively, if you add a DESC keyword to get a descending order, NULLs will appear last.

How do I sort the last null in SQL Server?

SQL ORDER BY Clause Handling NULLS This means that if you specify a column in the ORDER BY clause that has null values in ascending order the NULL values will appear first in the result set. Conversely, if you specify descending order, they will appear last in the result set.

How do columns with null values behave?

Some columns cannot have a meaningful value in every row. Db2 uses a special value indicator, the null value , to stand for an unknown or missing value. A null value is a special value that Db2 interprets to mean that no data is present. If you do not specify otherwise,Db2 allows any column to contain null values.


2 Answers

I would do:

using(var context = new DomainEntities()) {     var result = context.Users.OrderBy(u => u.LastName == null)                               .ThenBy(u => u.LastName)                               .ThenBy(u => u.FirstName == null)                               .ThenBy(u => u.FirstName); } 

...which should produce reasonable SQL.

EDIT: explanation (taken from Craig's comment):

Because false sorts before true.

like image 118
Craig Stuntz Avatar answered Oct 07 '22 08:10

Craig Stuntz


var result = context.Users.OrderBy(x => x.FirstName ?? x.LastName); 
like image 30
Alex Zaitsev Avatar answered Oct 07 '22 09:10

Alex Zaitsev