Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I order by NULL in DQL?

I'm building an app using Symfony2 framework and using Doctrine ORM. I have a table with airlines for which some IATA codes are missing. I'm outputting a list, ordered by this IATA code, but I'm getting the undesirable result that the records with null IATA codes are sorted at the top.

In MySQL this is simple enough to do, with ORDER BY ISNULL(code_iata), code_iata but I'm clueless as to what the equivalent would be for DQL. I tried

$er->createQueryBuilder('airline')->orderBy('ISNULL(airline.codeIata), airline.codeIata', 'ASC')

but this gives me a syntax error.

The Doctrine docs give me no answer either. Is there a way?

like image 692
indorock Avatar asked Sep 29 '12 10:09

indorock


People also ask

How do you order NULL values?

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.

What is ORDER BY select NULL?

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.

Can we use ORDER BY without select?

Yes, you can order by a field(s)even if it is not your in your select statement but exists in your table.


2 Answers

You can use the following trick in DQL to order NULL values last

$em->createQuery("SELECT c, -c.weight AS HIDDEN inverseWeight FROM Entity\Car c ORDER BY inverseWeight DESC");

The HIDDEN keyword (available since Doctrine 2.2) will result in omitting the inverseWeight field from the result set and thus preventing undesirable mixed results.

(The sort fields value is inverted therefore the order has to be inverted too, that's why the query uses DESC order, not ASC.)

Credits belong to this answer.

like image 189
Petr Sobotka Avatar answered Sep 22 '22 05:09

Petr Sobotka


The most unobtrusive generic solution would be to use the CASE expression in combination with the HIDDEN keyword.

   SELECT e,
     CASE WHEN e.field IS NULL THEN 1 ELSE 0 END HIDDEN _isFieldNull
     FROM FooBundle:Entity e
 ORDER BY _isFieldNull ASC

Works with both numeric as well as other field types and doesn't require extending Doctrine.

like image 40
kgilden Avatar answered Sep 21 '22 05:09

kgilden