Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle order by descending with NULL last

Tags:

sql

oracle

my objective is, to print the result of the query in "DESCENDING" order. but the problem is, the rows with NULL values went on top of the list.. how to put the null rows at the bottom, if the order by is descending?

select mysubcat.subcat
       , mysubcat.subcatid as subcat_id
       , (select SUM(myad.PAGEVIEW) 
           from myad 
            where MYAD.CREATEDDATE between  '01-JUL-13 02.00.49.000000000 PM' and '13-JUL-13 02.00.49.000000000 PM'
            AND MYAD.status = 1 
            and  MYAD.mobileapp IS NULL
            and myad.subcatid = mysubcat.subcatid )as web_views 
from mysubcat 
order by web_views desc;

the sample result goes like this

                             SUBCAT_ID    WEB_VIEWS
Swimming Lessons                56        (null)    
Medical Services                17        (null)
Mobile Phones & Tablets         39        6519
Home Furnishing & Renovation   109        4519

the order is in the descending order, I just want to put the rows with null values at the bottom of the printed result, so how?

like image 413
sasori Avatar asked Jul 14 '13 13:07

sasori


People also ask

How do I ORDER BY NULL last?

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.

How does Oracle sort NULL values?

Oracle treats NULLs the same way as PostgreSQL. Specifically, Oracle's documentation states that “if the null ordering is not specified, then the handling of the null values is NULLS LAST if the sort is ASC, NULLS FIRST if the sort is DESC.” In effect, Oracle considers NULL values larger than any non-NULL values.

When data is sorted in ascending order NULL values appear first in the list?

SQL treats NULL values to be less than 0 so while sorting in ascending order, NULL values always appear to be at first.

What does ORDER BY NULL mean?

using ORDER BY NULL is a workaround that satifies the syntax requirement but does not actually change the order of the data. In effect it is an instruction to not order at all. N.B.: some (myself included) prefer to use SELECT 1 instead of SELECT NULL but there is no difference in effect.


2 Answers

You can use DESC NULLS LAST to achieve that.

Here is the official documentation from Oracle.

NULLS LAST

Specifies that NULL values should be returned after non-NULL values.

like image 137
AllTooSir Avatar answered Oct 18 '22 13:10

AllTooSir


Use a case

order by case when web_views is not null 
              then 1 
              else 2 
         end asc, 
         web_views desc;
like image 38
juergen d Avatar answered Oct 18 '22 13:10

juergen d