Oracle is a widely used database management system that fully supports the SQL language standard. In many scenarios, we need to display query results in pages to facilitate data management and viewing. Next, this article will introduce how Oracle performs paging operations.
1. Use ROWNUM for paging
Oracle provides a ROWNUM function, which can identify each row in the returned result set as a unique value, and the value is numbered starting from 1. self-increasing. This function has the following characteristics:
Then, we can use the ROWNUM function to perform data paging operations. The specific implementation steps are as follows:
For example:
SELECT FROM (SELECT A., ROWNUM RN FROM (SELECT * FROM user_data ORDER BY user_id) A WHERE ROWNUM <= 20) WHERE RN >= 1;
In the above SQL statement, a subquery statement is used to query all data from the user_data table and sort it according to the user_id field. Finally, use the ROWNUM function based on the query result set and limit the number of rows returned in the query result set to 20 rows. The result of using the above SQL statement is the data records from row 1 to row 20.
2. Use OFFSET...FETCH for paging
In view of the limitations of ROWNUM paging method, Oracle has provided a new paging method since version 12c, namely OFFSET FETCH interpolation syntax . Compared with the ROWNUM function, the characteristics of the OFFSET FETCH syntax are:
The specific usage method is as follows:
SELECT * FROM user_data ORDER BY user_id OFFSET 0 ROWS FETCH NEXT 20 ROWS ONLY;
In the above SQL statement, OFFSET 0 ROWS FETCH NEXT 20 ROWS ONLY syntax indicates that the specified offset is row 0 and 20 rows of data records are obtained.
Summary:
Oracle provides two paging data query methods: ROWNUM function and OFFSET FETCH syntax. The ROWNUM function is suitable for situations where the amount of data is small and the paging operation only needs to be performed once. The OFFSET FETCH syntax is suitable for situations where the amount of data is large and multiple paging needs to be queried continuously.
The above is the detailed content of How to paginate in oracle. For more information, please follow other related articles on the PHP Chinese website!