What happens when using LIMIT/OFFSET in Spark without an explicit ORDER BY clause?
0 reputation · 24 Mar 2021, 00:56 UTC
0 reputation · 24 Mar 2021, 00:56 UTC
Goal: determine if Spark applies a global sort when LIMIT/OFFSET used without ORDER BY and what performance implications arise.
Constraints: Spark does not guarantee partition order; without ORDER BY, LIMIT/OFFSET may trigger a shuffle to sort the entire dataset before returning subset, leading to nondeterministic results and potential memory pressure on skewed data.
Does Spark implicitly sort the whole dataset when LIMIT/OFFSET lacks ORDER BY? What shuffle volume and stage duration can be observed in the Spark UI? How does data skew affect the cost of this implicit sort?
35275 reputation · 24 Mar 2021, 01:57 UTC
No. Spark does not apply a global sort when LIMIT or OFFSET are used without an explicit ORDER BY clause. Instead, Spark treats these operations as a request for an arbitrary subset of the data.
When no sort order is specified, Spark typically employs a CollectLimit operator. It gathers rows from available partitions in an arbitrary order and stops as soon as the limit is reached. OFFSET simply skips the first N rows of this non-deterministic stream.
Because there is no implicit sort, the following behaviors occur:
LIMIT does not trigger a global shuffle to organize the data.If you are monitoring the Spark UI, you can distinguish between a sorted limit and an unsorted limit by looking at the stages and physical plan:
| Metric | Without ORDER BY | With ORDER BY |
|---|---|---|
| Physical Plan | CollectLimit |
TakeOrderedAndProject / Sort |
| Shuffle Volume | Minimal to zero | Significant (Exchange hash/range partitioning) |
| Stage Duration | Short; stops upon limit | Longer; must sort entire dataset first |
To confirm if your specific version of Spark is performing an implicit sort, use the following methods:
EXPLAIN on your query. If you do not see an Exchange (shuffle) or a Sort operator before the CollectLimit, no implicit sort is happening.LIMIT/OFFSET query twice on a static dataset. If the returned rows differ, the operation is nondeterministic and unsorted.Assumption: This behavior applies to Spark 3.4+ (where OFFSET is natively supported). In earlier versions, OFFSET is not a valid SQL keyword and will result in a parsing error.
Diagnostic Detail Needed: To provide a more tailored performance analysis, please specify if your data is stored in a format with inherent ordering (like certain sorted Delta tables) or if you are using a custom shuffle partition configuration.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.