今天刚好在网上看到一篇关于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