Order by的用法和注意问题

来源:互联网 发布:淘宝客服工资多少2016 编辑:程序博客网 时间:2024/06/05 20:26

1、ORDER BY 中关于NULL的处理

缺省处理,Oracle在Order by 时认为null是最大值,所以如果是ASC升序则排在最后,DESC降序则排在最前。

当然,你也可以使用nulls first 或者nulls last 语法来控制NULL的位置。
Nulls first和nulls last是Oracle Order by支持的语法
如果Order by 中指定了表达式Nulls first则表示null值的记录将排在最前(不管是asc 还是 desc)
如果Order by 中指定了表达式Nulls last则表示null值的记录将排在最后 (不管是asc 还是 desc)
使用语法如下:
--将nulls始终放在最前
select * from zl_cbqc order by cb_ld nulls first
--将nulls始终放在最后
select * from zl_cbqc order by cb_ld desc nulls last

2、几种排序的写法
单列升序:select<column_name> from <table_name> order by <column_name>; (默认升序,即使不写ASC)

单列降序:select <column_name> from <table_name> order by <column_name> desc;
多列升序:select <column_one>, <column_two> from <table_name> order by <column_one>, <column_two>;
多列降序:select <column_one>, <column_two> from <table_name> order by <column_one> desc, <column_two> desc;
多列混合排序:select <column_one>, <column_two> from <table_name> order by <column_one> desc, <column_two> asc;

3、今天看到的新写法

SQL> select * from tb;

    BLOGID BLOGCLASS
---------- ------------------------------
        1 人生
        2 学习
        3 工作
        5 朋友

SQL> select * from tb order by decode(blogid,3,1,2), blogid;

    BLOGID BLOGCLASS
---------- ------------------------------
        3 工作
        1 人生
        2 学习
        5 朋友

我所说的就是上面红色的那句话。实现的功能就是不管怎样,BLOGID为3的值必须排在第一位,其他的记录按照BLOGID升序排序。

 

4、Order By 语句不能与Sequence.nextval同时使用

     select seq.nextval, id from db order by id 是不合法的

原创粉丝点击