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,......, '', ''
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:
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.
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.
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.
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With