Shanghai Tengke Education Dameng database training dry goods sharing the use of ROWNUM in Dameng database

ROWNUM is a false column that represents the row number of the query from the table, or the number of rows in the result set of the join query. It will be allocated as 1, 2, 3, 4,...N, where N is the number of rows. By using ROWNUM, we can limit the number of rows returned by the query.

 

Let's take the EMPLOYEE table in the RESOURCES mode in the BOOKSHOP instance library as an example

The complete data of the table is as follows:

 

 

If we only want to see the first 5 rows of data, we can write

SELECT * FROM RESOURCES.EMPLOYEE WHERE rownum < 6;

 

 

It should be noted that a ROWNUM value is not permanently assigned to a row. There is no label for a row in the table. You cannot query the row whose ROWNUM value is 5. The ROWNUM value will only increase when it is allocated, and the initial value is 1. That is, only after one row is satisfied, the ROWNUM value will increase by 1, otherwise it will only maintain the original value. Therefore, the following statement cannot return data at any time.

 

SELECT * FROM RESOURCES.EMPLOYEE WHERE ROWNUM > 6;

SELECT * FROM RESOURCES.EMPLOYEE WHERE ROWNUM = 6;

 

 

An important function of ROWNUM is to control the size of the returned result set, which can prevent queries from being sorted on disk. Because the ROWNUM value is assigned after the predicate of the query is parsed and before any sorting and aggregation. Therefore, we need to pay attention to the use of ROWNUM in sorting and aggregation. Unexpected results may be obtained. For example, if we want to get the five oldest employees

SELECT * FROM RESOURCES.EMPLOYEE WHERE ROWNUM < 6ORDER BY BIRTHDATE;

 

 

The above statement will only output the first 5 rows of the EMPLOYEE table in BIRTHDATE sorting, not all the data in the table will be sorted by BIRTHDATE and output the first 5 rows. To achieve the latter, you need to use the following statement:

SELECT * FROM (SELECT * FROM RESOURCES.EMPLOYEE ORDER BY BIRTHDATE)WHERE ROWNUM < 6;

或者SELECT TOP 5 * FROM RESOURCES.EMPLOYEE ORDER BY BIRTHDATE;

The results are as follows:

 

 

Regarding the use of ROWNUM, the following restrictions should be noted:

1. In the query, ROWNUM can be compared and operated with any numeric expression, but it cannot appear in a Boolean expression containing OR, otherwise an error will be reported;

 

2. ROWNUM can only appear in non-correlated sub-queries, and cannot be used in related sub-queries, otherwise an error will be reported;

 

3. In non-correlated sub-queries, ROWNUM can only achieve the same function as TOP, so sub-queries cannot contain ORDER BY and GROUP BY;

 

4. The sub-predicate where ROWNUM is located can only have the following form: ROWNUM op exp, the type of exp can only be immediate numbers, parameters and variable values, op ∈ {<, <=, >, >=, =,<>}.

Guess you like

Origin blog.csdn.net/qq_42726883/article/details/108463668