Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine 2 Order By ASC and Null values in last

I am trying to fetch result which and I need to sort in ascending order. But some values would be null/empty, I need the to be in last while sorting starts from 0 1 2 and then null value.

I tried SortableNullsWalker but it did not help. The value I am sorting is not column, its a multiplication of two values which is being sorted, thats why I think SortableNullsWalker did not work. Any help please

$dql = 'SELECT (column1 * column2) as distance FROM table)

                ORDER BY distance ASC ';

        $dq = $this->getEntityManager()->createQuery($dql);

The result comes as '', '', 0, 1, 2.334, ....

But I am trying to get it like : 0, 1, 2.334,......, '', ''

like image 846
Deepanshu Goyal Avatar asked May 02 '14 04:05

Deepanshu Goyal


People also ask

How to sort null last whilst ordering non-NULL values in ascending order?

The COALESCE function can also be used, which returns the first non-NULL value in a specified list of arguments (or NULL if there are no non-NULL values). Therefore, to sort NULL last whilst ordering non-NULL values in ascending order, we could simply supply a highest possible value as a fallback (or substitue) for NULL values. For example:

What is order by ASC with detailed example?

In this topic, we described about the ORDER BY ASC with detailed example. ORDER BY ASC statement is used to sort the data from table in result-set in ascending order. ORDER BY ASC is used in SELECT statement. column1, column2, …, columnN - Specifies the column names from table. table_name – Specifies the name of the table.

What does ASC NULLS LAST mean in MySQL?

In an ascending sort, ASC NULLS LAST specifies that rows with a NULL value in the sort key column follow non-NULL rows in the sorted result set.

What does NULLS LAST mean for the ORDER BY clause?

The NULLS LAST option for the ORDER BY clause has been an ANSI standard for a long time. Obviously, it does not mean that all database vendors have implemented it. Oh, no. Nothing like that.


2 Answers

This is similar solution, which works with non numerical colums/expressions:

/* @var $datasource QueryBuilder */  
$datasource->addSelect('CASE WHEN xxx.yyy IS NULL THEN 1 ELSE 0 END as HIDDEN yyy_is_null');
$datasource->orderBy('yyy_is_null', 'ASC'); // always ASC
$datasource->addOrderBy('xxx.yyy','DESC'); //DESC or ASC
like image 146
Petr Avatar answered Sep 22 '22 07:09

Petr


SOLUTION:

I had to use a hidden variable with same value as of distance and add minus(-) before it and Order the result by new hidden variable in DESC order

$dql = 'SELECT (column1 * column2) as distance,
        -(column1 * column2) as HIDDEN distance1 
        FROM table
        ORDER BY distance1 DESC';

        $dq = $this->getEntityManager()->createQuery($dql);
like image 32
Deepanshu Goyal Avatar answered Sep 22 '22 07:09

Deepanshu Goyal