Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails/Hibernate: how to order by isnull(property) to get NULLs last?

Normally when ordering ascending by a field, you get the NULL values first, and then the more interesting values. Often, you want NULL values last. In MySQL, you can do this with:

SELECT * FROM people ORDER BY ISNULL(name), name;

However, I'm using Grails with Hibernate criteria, and I have absolutely no idea how to do this there. Is this even supported in any way? Is there some way to order by a custom SQL expression? I'd hate to rewrite all my criteria to plain SQL just to get it to sort correctly.

like image 384
mcv Avatar asked Apr 26 '11 08:04

mcv


People also ask

How do I sort by nulls last in SQL?

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.

Is order by name asc displays nulls last?

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 you use nulls last?

If the null ordering is not specified then the handling of the null values is: - NULLS LAST if the sort is ASC - NULLS FIRST if the sort is DESC - If neither ascending nor descending order is specified, and the null ordering is also not specified, then both defaults are used and thus the order will be ascending with ...


3 Answers

if you want to order and HibernateCriteriaBuilder to set NullPrecedence in GORM the AbstractHibernateCriteriaBuilder provies you with the method order() that you can set a org.hibernate.criterion.Order like regular Hibernate

Example

     People.createCriteria().list (){
          order(org.hibernate.criterion.Order.asc('name')
                . nulls(org.hibernate.NullPrecedence.LAST)
           )
     }
like image 100
ladriangb Avatar answered Nov 05 '22 12:11

ladriangb


In hibernate you can try with this below code :

Criteria c = ...;

c.addOrder(Order.asc("name").nulls(NullPrecedence.LAST));

like image 36
Uvaise Avatar answered Nov 05 '22 11:11

Uvaise


I'm afraid it's not even in Hibernate yet: there's an open bug for this.

Though, one could use NativeSQLOrder from that bug comments and try to inject a proper function into HibernateCriteriaBuilder. You only need to add a sqlOrder method to HibernateCriteriaBuilder class, doing approximately same as HibernateCriteriaBuilder.order().

like image 28
Victor Sergienko Avatar answered Nov 05 '22 11:11

Victor Sergienko