rownum belongs to pseudoColumns in oracle. There are some details in the usage, so pull it out separately.
Article Directory
test you
The t_user table has 20 records. How many records will be returned by executing the following statement?
The statement is:
select * from t_user where rownum > 10 ;
Main content
rownum> 1 does not return any results
select * from t_user where rownum > 5;
The statement does not return any results. why?
Description:
rownum starts from 1.
Take out the records one by one and allocate rownum, and then judge the rownum condition.
Process:
First take out one, assign rownum=1, and judge whether it meets rownum>1.
If it doesn't meet, discard it.
Take out another one. Because the previous one was discarded, this rownum is still 1, which
does not meet the conditions, so continue to discard it.
By analogy, the follow-up will not be consistent. So no records are returned.
rownum is greater than the use of conditions
Some scenes really need to use the condition that rownum is greater than n, how to use it?
It's actually very simple, just add a column alias to rownum. The sql is as follows:
select
*
from
(
select
product_name,price,rownum as rn
from t_product where rownum < 10
) a
where a.rn >5
Set a column of the table to 1-n serial number
Some tables do not have a serial number column. After adding a column, you can use the following statement to set the serial number value:
UPDATE t_user SET sequence = ROWNUM;
In this way, the sequence column is the serial number of 1-n.
Oracle's paging example
Where rownum in Oracle can only be written in uppercase or lowercase. So you need to pack 2 layers. For example in mybatis:
select
*
from
(
select
b1.*,
rownum rn
(
select
*
from
t_user
where username like '%a%'
) b1
where rownum <= (#{pageSize,jdbcType=VARCHAR}*#{page,jdbcType=VARCHAR}) --第一层设置右边界
) b2
where rn >= ((#{page,jdbcType=VARCHAR}-1)*#{pageSize,jdbcType=VARCHAR} +1) -- 第二层,设置左边界
Answer part
Answer to Question 1
The t_user table has 20 records. How many records will be returned by executing the following statement?
Is it 10? Of course not. No data is actually returned.
The reason is in this document.
other
references
oracle official website rownum document:
https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/RO WNUM-Pseudocolumn.html#GUID-2E40EC12-3FCF-4A4F-B5F2-6BC669021726
oracle official website help center (document)
https://docs.oracle.com/en/
Enter search content to retrieve, for example, search rownum.