Skip to content
Advertisement

there is a way to order empty element like null element?

I need to order a column and there are a lot of elements null or empty.The problem is null element are ordered differente from null element

SELECT s.name         
                   FROM Employee s
                 ORDER BY s.name desc

The result about is that employees with name==null are the first position, after there are the elements with name!=null (are a real name) and at the end there are the elements with name empty.

I want that the name=null and name=empty are treated in the same way and put all in the first result? Anyone can help me?

Advertisement

Answer

You can use the nulls first or nulls last clause to determine where null values sort, i.e.

order by s.name desc nulls last

if you want null values to sort last rather than first or

order by s.name desc nulls first

if you want them so sort first

In Oracle, there is no such thing as an empty string that is separate from null so it isn’t obvious what you mean when you say “empty”. My guess is that you mean a string that contains one or more spaces and nothing else. If you want to eliminate spaces from the string before ordering so that a name of 1 space or 10 spaces is treated the same as null, you can trim the name

order by trim(s.name) desc nulls first

Note that this may affect performance if Oracle is using an index on name to do the sorting (unlikely in this particular case with no where clause but that may be important in the real query). You may need a function-based index on trim(name) to support the ordering.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement