Technical Implementation of Efficiently Retrieving Top 100 Latest Orders per Client in Oracle

Nov 11, 2025 · Programming · 12 views · 7.8

Keywords: Oracle Database | ROW_NUMBER Window Function | Top-N Queries | ROWNUM | FETCH FIRST

Abstract: This article provides an in-depth analysis of efficiently retrieving the latest order for each client and selecting the top 100 records in Oracle database. It examines the combination of ROW_NUMBER window function with ROWNUM and FETCH FIRST methods, compares traditional Oracle syntax with 12c new features, and offers complete code examples with performance optimization recommendations.

Problem Background and Requirements Analysis

In practical business scenarios, there is often a need to retrieve the latest order records for each client from an order table and further filter the top N records. This requirement is common in scenarios such as customer behavior analysis and order monitoring. The original query can correctly obtain the latest order for each client, but how to perform Top-N filtering on this basis becomes the key issue.

Core Solution Approaches

For the requirement of obtaining the top 100 latest orders per client, we provide two main implementation approaches:

Traditional ROWNUM Method

In versions prior to Oracle 12c, using ROWNUM combined with subqueries is the standard method for implementing Top-N queries. The specific implementation is as follows:

SELECT * FROM (
     SELECT * FROM (
        SELECT 
          id, 
          client_id, 
          create_time,
          ROW_NUMBER() OVER(PARTITION BY client_id ORDER BY create_time DESC) rn 
        FROM order
      ) 
      WHERE rn=1
      ORDER BY create_time desc
  ) WHERE rownum <= 100

The logic of this query is clearly layered: the innermost query uses the ROW_NUMBER window function to number orders for each client in descending order of creation time; the middle layer filters out the latest order for each client (rn=1) and sorts them in descending order of creation time; the outermost layer uses ROWNUM to limit the return to the first 100 records.

Oracle 12c FETCH FIRST Syntax

Starting from Oracle 12c, the more concise FETCH FIRST syntax was introduced, making Top-N queries more intuitive:

SELECT * FROM (
    SELECT 
      id, 
      client_id, 
      create_time,
      ROW_NUMBER() OVER(PARTITION BY client_id ORDER BY create_time DESC) rn 
    FROM order
  ) 
  WHERE rn = 1
  ORDER BY create_time desc
  FETCH FIRST 100 ROWS ONLY

The advantage of this method is that the syntax is more standard, similar to the LIMIT clause in other database systems, improving code readability and portability.

In-depth Technical Analysis

Working Principle of Window Functions

ROW_NUMBER() OVER(PARTITION BY client_id ORDER BY create_time DESC) is the core part of the query. PARTITION BY client_id groups the data by client, ORDER BY create_time DESC sorts within each group in descending order of creation time, and ROW_NUMBER() assigns a unique sequence number to records within each group. The execution efficiency of this window function is much higher than traditional self-join or correlated subquery methods.

Timing of Sorting and Limiting

In the traditional ROWNUM method, ORDER BY must be placed in the inner query before the ROWNUM restriction because ROWNUM is assigned during data retrieval. If ROWNUM is applied before ORDER BY, incorrect sorting results may be obtained. In the FETCH FIRST syntax, this restriction is more naturally integrated into the final stage of the query.

Performance Optimization Recommendations

For large order tables, it is recommended to create a composite index on the create_time and client_id columns to accelerate the calculation and sorting operations of the window function. Additionally, depending on actual business needs, consider regularly archiving historical order data to reduce the amount of data queried.

Comparison with Different Database Systems

Although this article mainly discusses Oracle implementation, understanding similar functions in other database systems aids cross-platform development: SQL Server uses the TOP keyword, MySQL uses the LIMIT clause, and PostgreSQL uses LIMIT or FETCH FIRST syntax. Oracle's FETCH FIRST syntax is closest to the SQL standard, facilitating code standardization.

Extended Practical Application Scenarios

Beyond obtaining the latest orders, similar techniques can be applied to: retrieving the top N products per category, the top N employees per department, the top N sales records per region, etc. The key is understanding the combined use of window function partitioning and sorting with Top-N restrictions.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.