row num is not displaying any rows when using between keyword [duplicate]

[亡魂溺海] 提交于 2019-11-29 16:38:11

Oracle rownum starts at 1, so you will never get the first rownum if you say between 2 and N.

It takes a row to "initiate" the rownum pseudocolumn sequence, so by eliminating rownum 1 in your criteria, you eliminate all rownums (or every row essentially has rownum 0).

Look at it like this. You don't get a ROWNUM until the database returns a row to you. The first row of any criteria will always be ROWNUM 1.

Now, the trick you can use is to use a subquery. Each subquery will have its own rownum, and if you alias it to another column name, you can preserve it into outer queries, and treat it however you like. So if you are looking to implement paging of a result set, you would normally alias rownum from inner results as rownum_ to an outer subquery to limit with BETWEEN.

select * from 
  (select t.*, rownum as rownum_ from t)
where rownum_ between 2 and 6

But note, that the outer result set will have its own rownum, so you could do:

select t2.*, rownum from 
  (select a, b, rownum as rownum_ from t) t2
where rownum_ between 2 and 6

You will see rownum on the final result still starts at 1, but your inner result will have rownum_ starting at 2.

select * from cus where rownum between 2 and 6;

That is completely wrong. Because, ROWNUM is a pseudo-column which increments to 2 only when it started at ROW one(random, of course). In your query, the predicate ROWNUM BETWEEN 2 AND 6 is meaningless, since ROWNUM has not yet been assigned.

Let's understand this step-by-step :

  1. Understand how a SQL statement is interpreted. After the query is parsed, the filter is applied.

  2. In your query, the filter ROWNUM BETWEEN 2 AND 6 is meaningless, since, Oracle has not yet assigned ROWNUM 1 as the first row is not yet fetched.

  3. When the first row is fetched, then ROWNUM is assigned as a pseudo-number. But the filter in your query directly points to rows between 2 and 6, which is absurd. So, no rows are returned.

Mysql doesnt have rownum.

If you are looking for oracle maybe you can try something like this:

select * from (select cus.*, rownum as row_num from cus) where row_num between 2 and 6;

or

select * from (select cus.*, rownum as row_num from cus) where row_num >1 and row_num <=6;

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!