title: Doctrine2 - Specific NULL sorting
body: <p>When you sort on column <code>a</code> descending, it will put all records having <code>a</code> <code>NULL</code> at the bottom, which makes sense. What I want is the following ordering when I'm sorting on attribute <code>a</code> descending:</p>
  
  <pre><code>a
  ----
  NULL
  NULL
  5
  4
  3
  2
  1
  </code></pre>
  
  <p>I know Oracle has <code>NULLS_FIRST</code> and in MySQL you could use <code>ORDER BY ISNULL(a)</code>, but I'm wondering whether there is an elegant way to deal with this using Doctrine2 functionality only? So not using native queries, etc.</p>
  
  <hr>
  
  <p>Answer with the help of S0pa: I fixed it using the following new function node for Doctrine2:</p>
  
  <pre><code>&lt;?php
  namespace MyBundle\General;
  
  use \Doctrine\ORM\Query\Lexer;
  
  class IsnullFunctionNode extends \Doctrine\ORM\Query\AST\Functions\FunctionNode
  {
      private $isnull;
  
      public function parse(\Doctrine\ORM\Query\Parser $parser)
      {
          $parser-&gt;match(Lexer::T_IDENTIFIER);
          $parser-&gt;match(Lexer::T_OPEN_PARENTHESIS);
          $this-&gt;isnull = $parser-&gt;ArithmeticPrimary();
          $parser-&gt;match(Lexer::T_CLOSE_PARENTHESIS);
      }
      public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
      {
          return 'ISNULL('.$this-&gt;isnull-&gt;dispatch($sqlWalker).')';
      }
  }
  </code></pre>
  
  <p>And connected it in Symfony2 to Doctrine2 like this (app.yml):</p>
  
  <pre><code>doctrine:
    orm:
      entity_managers:
        default:
          ...
          dql:
            numeric_functions:
              isnull: Diagenda\CommonBundle\General\IsnullFunctionNode
  </code></pre>
  
  <p>I can't use these functions in my <code>ORDER BY</code> clause, but by doing a <code>SELECT ISNULL(a) AS n_a</code> I can order on the <code>n_a</code> attribute.</p>