rownum和order by

今天刚好在网上看到一篇关于rownum和order by的文章

英文的,大概意思就是说

SELECT firstname
FROM   employee
WHERE  ROWNUM < 5
ORDER BY empid

 

empid如果是主键,这个语句可以返回期望的结果,按empid排序且rownum也是升序排列

 

如果order by的字段不是主键,返回的结果按empid排序但rownum的顺序是乱的,和插入DB的时间有关

 

 

 

原文及出处

http://www.devx.com/tips/Tip/14251

Using ROWNUM Pseudocolumn in Oracle
When querying in Oracle, use ROWNUM pseudocolumn to limit the number of returned rows. Pseudocolumns behave like table columns but are not actually stored in tables. (Other pseudocolumns are RowId, Level, etc.).

In Sybase, the equivalent way to restrict returned rows in T-SQL is the following:

 Set Rowcount n

Where 'n' stands for number of rows returned by query
Consider following this example, which would restrict the resulting number of rows to 9:
 SELECT firstname
FROM   employee
WHERE  ROWNUM < 10 ;
Here are the results:
 FIRSTNAME
------------
John
Tim
Julie
Stacy
Rahul
Leena
Amy
Bill
Teri
However, one should be careful when using the Order By clause along with Rownum. When Order By is used with Rownum to restrict query results, it works only if Ordered By is the primary key of the table. For example, empid is the primary key in this employee table:
 SELECT firstname
FROM   employee
WHERE  ROWNUM < 5 
ORDER BY empid;
Here are the results:
 FIRSTNAME
------------
John
Julie
Stacy
Tim
Now consider the following query, ordered by a non-PK column. The order of its results would be unpredictable. It would depend on how the rows were inserted in table.
 SELECT firstname
FROM   employee
WHERE  ROWNUM< 5 
ORDER BY firstname;
Here are the results:
 FIRSTNAME
------------
Teri
Julie
Stacy
Bill
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值