Question

My understanding is that nulls last is not possible with QoQ. How do I trick coldfusion into sorting null values last whether i'm sorting the row ascending or descending?

I've tried using case in the SELECT and ORDER part of query, but looks like CF is not liking it (running on railo)

Was it helpful?

Solution

There may be better options, but one simple trick is to add a column representing sort priority. Assign records with non-null values a higher priority than null values. Then simply sort by the priority value first, then any other columns you want. Since the null values have a lower priority number, they will always sort last.

    <!--- 1 - non-null values 2 - null values --->
    SELECT 1 AS SortOrder, SomeColumn
    FROM   theQuery
    WHERE  SomeColumn IS NOT NULL
    UNION ALL
    SELECT 2 AS SortOrder, SomeColumn
    FROM   theQuery
    WHERE  SomeColumn IS NULL
    ORDER BY SortOrder, SomeColumn ASC

(It is worth noting you could probably do something similar in your database query using order by instead of union.)

OTHER TIPS

QoQ on both ColdFusion and Railo have a very limited SQL vocab, and there's nothing that deals with how to collate nulls. So as @Leigh has suggested, add another column - without any nulls - which represent the sorting you want.

Or, better, if possible deal with all this in the DB. Obviously this is not always possible (as the record set you're querying might not have come from a DB in the first place ;-)

...there was one more way, but it relies on values being NULL and not empty ''. I'm going from memory here, but this is essentially it, using || only works if the value is non-null, so using the null values descending sort first, I get the values at the end.

 <cfquery>
    SELECT *, '1' || #sortCol# as isNull
    FROM table
    ORDER BY isNull desc, #sortCol#
 </cfquery>

Note I'm not actually advocating the use of this and I'm not sure if CF would handle it the same way

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top