Top-N statements
This topic describes the ranking functions, syntax, examples, result writing, and state configuration of regular Top-N queries in Flink SQL.
Background information
A Top-N query sorts rows by the specified columns and returns the first or last N rows, such as the best-selling products in each category or the highest-rated stores in each region. When sort values are equal, use RANK() or DENSE_RANK() to keep tied ranks, so that a cutoff does not retain only part of the tied rows.
Streaming regular Top-N processes insert-only data and also ranks updated data continuously, such as aggregation results. Updates and deletes require the source connector to emit correct changelog records. For an upsert source, declare a valid primary key.
Limits
|
Scenario |
Supported ranking functions |
Description |
|
Streaming regular Top-N |
|
|
|
Batch regular Top-N |
|
|
|
Streaming window Top-N |
|
Tie-preserving ranking functions are not supported. |
-
Streaming
RANK()andDENSE_RANK()require a constant rank range with a finite upper bound, such asrk <= 3orrk >= 2 AND rk <= 3. Dynamic bounds such asrk <= limit_columnare not supported, and the upper bound cannot be omitted to rank the entire unbounded stream. -
Only the Top-N pattern of a ranking subquery plus an outer rank filter is supported. These functions are not available in arbitrary streaming
OVERqueries. -
Streaming window Top-N still uses
ROW_NUMBER(). You cannot replace it with a tie-preserving ranking function. -
Tie-preserving ranking does not use the Local-Global two-phase Top-N optimization available for
ROW_NUMBER(). Enabling mini-batch does not make the rank operator run in two phases. The execution plan, resource consumption, and throughput differ.
RANK() and DENSE_RANK() limit the rank value, not the number of rows. The result can contain more than N rows, and rank 1 alone can return multiple rows. Neither function deduplicates tied rows.
Choose a ranking function
|
Requirement |
Ranking function |
Tie handling |
Meaning of rk <= N |
|
Keep at most N rows per partition |
|
Assigns a unique, consecutive number to each row |
At most N rows |
|
Keep the top N ranks in competition ranking |
|
Tied rows share a rank, and subsequent ranks skip numbers |
All rows whose rank is N or less |
|
Keep the top N distinct sort-key values |
|
Tied rows share a rank, and subsequent ranks are consecutive |
All rows under the top N distinct sort keys |
For example, a category contains five products with sales of 100, 100, 90, 90, and 80. Ranking them by sales in descending order gives:
|
Product |
Sales |
ROW_NUMBER() |
RANK() |
DENSE_RANK() |
|
p1 |
100 |
1 |
1 |
1 |
|
p2 |
100 |
2 |
1 |
1 |
|
p3 |
90 |
3 |
3 |
2 |
|
p4 |
90 |
4 |
3 |
2 |
|
p5 |
80 |
5 |
5 |
3 |
In this table, ROW_NUMBER() breaks sales ties by product ID in ascending order, whereas RANK() and DENSE_RANK() rank by sales only. With the same filter rk <= 3, ROW_NUMBER() returns p1, p2, and p3; RANK() returns p1, p2, p3, and p4; DENSE_RANK() returns all five products.
Syntax
Compute the rank in a subquery and filter the rank range in the outer query:
SELECT column_list
FROM (
SELECT column_list,
DENSE_RANK() OVER (
PARTITION BY partition_columns
ORDER BY sort_column DESC
) AS rk
FROM source_table
) AS ranked
WHERE rk <= N;
-
You can replace the ranking function with
ROW_NUMBER()orRANK(). -
PARTITION BYdefines the partitions that are ranked independently. If you omit it, all input rows are ranked together. -
ORDER BYspecifies the sort keys. Multiple sort columns are supported, each with its own direction. UseDESCfor the largest values andASCfor the smallest. -
WHERE rk <= Nsets the upper bound of the rank. N must be a positive integer constant. -
Conditions added with
ANDin the outer query filter the ranking result. To restrict the rows that enter the ranking, put those conditions in the subquery that computes the rank.
How ties are determined: Rows belong to the same tie group only if they are in the same partition and have identical values for all ORDER BY columns. ORDER BY sales DESC treats equal sales as a tie. After you change it to ORDER BY sales DESC, product_id ASC, rows with different product IDs are no longer tied. Adding a unique column to RANK() or DENSE_RANK() changes the ranking semantics. For ROW_NUMBER(), the opposite applies: adding a stable sort column such as the product ID makes the choice among tied rows deterministic.
The ORDER BY clause in OVER computes ranks. It does not guarantee that query results or streaming messages are emitted in that order. The consumer must still sort the data before displaying a ranking.
Examples
The following examples use the same fixed dataset and require no external connector. In a production job, replace the view with an actual source table or query result. The results shown are the rankings after all the data is processed. During streaming execution, intermediate changes may occur.
CREATE TEMPORARY VIEW ShopSales AS
SELECT *
FROM (VALUES
('p1', 'books', 100),
('p2', 'books', 100),
('p3', 'books', 90),
('p4', 'books', 90),
('p5', 'books', 80)
) AS t(product_id, category, sales);
Example 1: Use RANK to keep tied products within the top 3 ranks
SELECT product_id, category, sales, rk
FROM (
SELECT product_id, category, sales,
RANK() OVER (
PARTITION BY category ORDER BY sales DESC
) AS rk
FROM ShopSales
) AS ranked
WHERE rk <= 3;
|
product_id |
category |
sales |
rk |
|
p1 |
books |
100 |
1 |
|
p2 |
books |
100 |
1 |
|
p3 |
books |
90 |
3 |
|
p4 |
books |
90 |
3 |
Two products tie for rank 1, and the next product is rank 3, so rank 2 does not appear. Use this for competition ranking, where gaps between ranks are allowed.
Example 2: Use DENSE_RANK to keep the top 3 sales values
SELECT product_id, category, sales, rk
FROM (
SELECT product_id, category, sales,
DENSE_RANK() OVER (
PARTITION BY category ORDER BY sales DESC
) AS rk
FROM ShopSales
) AS ranked
WHERE rk <= 3;
|
product_id |
category |
sales |
rk |
|
p1 |
books |
100 |
1 |
|
p2 |
books |
100 |
1 |
|
p3 |
books |
90 |
2 |
|
p4 |
books |
90 |
2 |
|
p5 |
books |
80 |
3 |
Ranks are consecutive, with no gaps. To keep only the second and third sales values, change the outer condition to WHERE rk >= 2 AND rk <= 3, which returns p3, p4, and p5. The filter selects a rank range, not two rows after skipping one row.
Example 3: Rank cumulative sales continuously
Assume that an Orders source table exists with the category, product_id, and numeric amount columns. Aggregate by category and product first, then keep the top three sales values in each category:
CREATE TEMPORARY VIEW ProductSales AS
SELECT category, product_id, SUM(amount) AS sales
FROM Orders
GROUP BY category, product_id;
SELECT category, product_id, sales, rk
FROM (
SELECT category, product_id, sales,
DENSE_RANK() OVER (
PARTITION BY category ORDER BY sales DESC
) AS rk
FROM ProductSales
) AS ranked
WHERE rk <= 3;
New orders update the cumulative sales. If the source table also emits order updates or deletions, the aggregation results change accordingly, and the ranking query adjusts ranks and which products enter or leave the top N. The query accumulates all retained historical data and does not reset by day or hour. To rank data within a time period, design a separate window query. Batch jobs can use the same aggregation and ranking query on bounded order data.
Write results to a sink table
-
The sink table must support changes: Streaming Top-N emits changes to the current ranking. Even if the source table only inserts records, an existing product can change rank or leave the top N. The sink connector must handle updates, retractions, or deletes, and cannot write the result as insert-only data. The preceding
SELECTexamples only produce query results. To write to external storage, create a sink table that matches the changelog semantics and submit anINSERT INTOstatement. -
Do not use a tied rank as a unique key: For
ROW_NUMBER(), the partition columns plus the rank column uniquely identify a ranking position. This does not hold forRANK()orDENSE_RANK(). Both p1 and p2 map to(category = 'books', rk = 1), so a primary key on(category, rk)causes key conflicts. Use a business unique key that exists and is retained in the query result, such as(category, product_id)in Example 3, and make sure it meets the primary key constraints of the sink connector. If no unique key is available, choose a write mode that handles a full retraction changelog stream. -
Output the rank only when needed: If downstream only needs to know which products are in the top N, omit
rkfrom the outerSELECTwhile keeping the inner rank computation and the outer rank filter. This reduces result updates that are caused only by changes to the rank column.
SELECT product_id, category, sales
FROM (
SELECT product_id, category, sales,
DENSE_RANK() OVER (
PARTITION BY category ORDER BY sales DESC
) AS rk
FROM ShopSales
) AS ranked
WHERE rk <= 3;
Even without the rank column, products entering or leaving the top N and changes to their own fields still generate changes. The sink table must still support the corresponding write semantics.
State and configuration
|
Parameter |
Default value |
Description |
|
|
|
In streaming |
|
|
|
The cache budget, in records, for each rank operator subtask. For |
|
|
|
By default, state is not cleared based on idle time. If you set a nonzero value, state that has not been updated for a long time may be cleared. |
Set the tie group limit before you run the ranking query:
SET 'table.exec.rank.max-rows-per-sort-key' = '100000';
-
The limit is a protective threshold for a single tie group, not a total state limit for a partition or the whole job. With
PARTITION BY category ORDER BY sales DESC, it constrains the number of rows retained for the same category and the same sales value. If the limit is exceeded, first check for duplicate input, the size of the tie group, and the sort keys, then adjust the limit based on available resources. Adding sort columns can split a tie group, but it changes the ranking semantics. -
The cache reduces state access. It is not a hard limit on the total memory of the job. With insert-only input, rows that exceed the budget are written back to state and evicted from the cache, and must be read again for later processing. The default cache of 10,000 rows is smaller than the 100,000-row limit for a single tie group, so a large number of tied rows can cause high state access overhead even if no error occurs. Updated input uses a different state maintenance path and is not governed by this cache parameter.
-
A query that handles updates or deletes retains data outside the top N so that ranks can be recomputed after a top-N row is retracted. Do not estimate the state size as N rows.
-
TTL is not a time window. Clearing historical state that still participates in later ranking or retraction can make results deviate from the ranking semantics over the full history. If a strict all-history ranking is required, do not control the state size by shortening the TTL.
Modify an existing job: Switching between ROW_NUMBER(), RANK(), and DENSE_RANK() changes not only the SQL result but also the meaning of the rank state. The state compatibility check treats a change of ranking type as incompatible. Before you make the change, assess historical data replay, rank state rebuilding, and how downstream results continue. Do not assume that the rank state in an existing checkpoint or savepoint can be reused directly. For more information about compatibility rules, see Top-N.
For the Top-N execution algorithms and tuning recommendations, see Optimize Flink SQL.
FAQ
-
RANK() <= 3returns fewer than three ranks. Why?RANK()skips rank numbers. If the first two rows tie for rank 1, the next row is rank 3. To get three consecutive sort-key values, useDENSE_RANK()instead. -
DENSE_RANK() <= 3returns many rows. Why?It returns all rows under the top three distinct sort keys, with no limit on the number of rows. To get at most three rows, use
ROW_NUMBER()and define how ties are broken. -
Why does the error
only supports constant rank range currentlyoccur?Streaming
RANK()orDENSE_RANK()uses a non-constant rank range. Change it to a fixed upper bound such asrk <= 3, or a fixed start and end range. -
Why does the job fail instead of returning partial data when a tie group exceeds the limit?
Truncating a tie group breaks the semantics of
RANK()andDENSE_RANK(). The limit therefore raises an error so that you can check the input data or adjust the capacity. Check for duplicate input, the size of the tie group, and the sort keys before you adjusttable.exec.rank.max-rows-per-sort-key. A restart does not resolve a limit violation caused by the same input.
The three ranking functions differ in result size and processing cost. After you replace ROW_NUMBER() with a tie-preserving function, also evaluate the state size, skewed partitions, and the change-processing capacity of downstream systems. For the function list, see Supported functions.