Methods for sorting SQL query result sets according to specified criteria

Source: Internet
Author: User

Oracle considers NULL to be the largest.

In ascending order, by default, the null value is sorted back.

The descending sort, by default, is preceded by a null value.

There are several ways to change this situation:

(1) Convert NULL to a specific value using the NVL function or the Decode function

(2) Use case syntax to convert NULL to a specific value (Oracle9i later version support. Similar to SQL Server):
1. When a value is specified, specify the position of the sort
SELECT * FROM (
Select 1 T from dual
UNION ALL
Select 2 T from dual
UNION ALL
Select 3 T from dual
UNION ALL
Select 4 T from dual
) A order by case when a.t=2 then 1 else 0 end
2. When the value is the time of the order, always in the last
SELECT * FROM (
Select 1 T from dual
UNION ALL
Select 2 T from dual
UNION ALL
Select 3 T from dual
UNION ALL
Select 4 T from dual
) A order by case when a.t=2 and null else 0 end ASC Nulls last

Results:

(3) Use Nulls first or nulls last syntax.

This is the syntax that Oracle specifically uses to sort null values.

Nulls first: null is the top of the line. Example: SELECT * from MYTB ORDER by MyCol nulls first

NULL Last: The null is queued at the bottom. Example: SELECT * from MYTB ORDER by MyCol nulls last

If you want the columns that contain null to be sorted as you wish, you can do so.

Methods for sorting SQL query result sets according to specified criteria

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.