orderBy
Reports, top-10 lists and "latest first" views all need sorted data. orderBy sorts by one or more columns, each up or down, with missing values where you choose. This lesson also shows why sorting a whole big table is expensive, and the cheaper options when you only need part of it.
Step 1 · PySpark functions · Bronze · Read and select, lesson 5 of 5
On this page
Show code in
Every code block on the page follows this.
Read first: select (skip if you know it)
In plain words first
Sorting exam papers by score is easy on one desk. Now imagine the papers are spread over a hundred desks in different rooms: to put all of them in one order, someone has to gather them and compare across rooms. That is why a full sort is one of the most expensive things Spark does, and why sorting only the top 10 is cheap.
What it does
Sorts rows by one or more columns. Each column can be ascending or descending, and you can choose whether nullsnull: A missing or unknown value. Any comparison with null gives null, so filters treat it as false. Learn more → come first or last.
Step by step
Input
| name | dept | salary |
|---|---|---|
| Ben | Sales | 48000 |
| Farid | null | 39000 |
| Asha | Engineering | 72000 |
| Esha | Sales | 50000 |
Output
| name | dept | salary |
|---|---|---|
| Asha | Engineering | 72000 |
| Esha | Sales | 50000 |
| Ben | Sales | 48000 |
| Farid | null | 39000 |
Sorted by dept ascending with nulls last, then salary descending within each department.
Run the example
Input: employees
| id | name | dept | salary | manager_id |
|---|---|---|---|---|
| 1 | Asha | Engineering | 72000 | null |
| 2 | Ben | Sales | 48000 | 1 |
| 3 | Chitra | Engineering | 95000 | 1 |
| 4 | Dev | HR | 51000 | 1 |
| 5 | Esha | Sales | 50000 | 2 |
| 6 | Farid | null | 39000 | 2 |
from pyspark.sql import functions as F result = employees.orderBy( F.col("dept").asc_nulls_last(), F.col("salary").desc(), )
SELECT * FROM employees ORDER BY dept ASC NULLS LAST, salary DESC
Where nulls go
| Direction | Default | Override |
|---|---|---|
| Ascending | Nulls first | asc_nulls_last() / ASC NULLS LAST |
| Descending | Nulls last | desc_nulls_first() / DESC NULLS FIRST |
Other databases differ: PostgreSQL treats nulls as larger than any value, so its default is the opposite. Say it explicitly when results must match another system.
What a global sort costs Optional deep dive
To sort the whole DataFrameDataFrame: A table of rows and named columns that Spark processes in parallel. It never changes: every operation returns a new one. Learn more →, Spark first samples the data to pick range boundaries, then shufflesshuffle: Moving rows between machines so that all rows with the same key end up together. Needed by joins, groupBy and sorting, and usually the most expensive step of a job. Learn more → every row into the partitionpartition: A chunk of a DataFrame's rows. Spark processes each partition as one task, so partitions decide how much work runs in parallel. Learn more → for its range, then sorts each partition. That is a full shuffle plus a sort, and extra sampling jobs you will see in the Spark UI.
orderBy / sort
sortWithinPartitions
orderBy(...).limit(10) is cheap: Spark plans it as TakeOrderedAndProject, keeping only the top 10 per partition before merging, instead of sorting everything.Ties and stability
Rows that tie on every sort key can come back in any order, and the order can change between runs. If a result must be deterministic, for example for pagination or tests, add a unique column as the last sort key.
Common mistakes
- Sorting before a groupBy or join — The next shuffle destroys the order. Sort last.
- Assuming the sort survives a write — Files written from a sorted DataFrame are not read back in a guaranteed order. Sort in the query that needs it.
- Leaving ties unresolved — Add a unique tiebreaker when order must be stable.
Key takeaways
orderBysorts globally; ascending puts nulls first by default.- Use
asc_nulls_last/NULLS LASTto control null placement. - A global sort shuffles everything;
sortWithinPartitionsdoes not. - Sort plus limit runs as a cheap top-K.
Interview prep
THE QUESTION
"How would you get the top 10 customers by revenue from a 2 TB table?"
orderBy(desc).limit(10). Explain that Spark turns sort plus limit into a top-K per partition (TakeOrderedAndProject), so it never globally sorts the data. If they ask for top 10 per region, switch to a window with row_number.Avoid: "orderBy the whole table and take 10". Say that Spark rewrites sort plus limit into a per-partition top-K, so no full sort happens.
Follow-ups · answer out loud, then open
Follow-up"Where do nulls go in an ascending sort, and how do you change it?"
F.col("x").asc_nulls_last() or desc_nulls_first(), or NULLS LAST in SQL.Scenario"You need files sorted by customer_id inside each output file, not a globally sorted table."
sortWithinPartitions("customer_id"), which sorts each partition locally with no shuffle. Optionally repartition or repartitionByRange first to control which keys share a file.Trap"After orderBy, writing the result keeps the order when I read it back."
Check yourself
3 questionsWith default settings, where do nulls go in orderBy(F.col("x").desc())?
Show the answer
Last. Spark puts nulls first for ascending order and last for descending order by default.
Which needs a shuffle?
Show the answer
orderBy. A global orderBy range-partitions the data. sortWithinPartitions sorts each partition where it is.
Two rows tie on every sort key. What is guaranteed about their order?
Show the answer
Nothing. Spark makes no guarantee for ties. Add a unique tiebreaker for deterministic output.
Practise this
Problems that use orderBy, graded on hidden tests
- Sort Delivery OptionsFiltering & Selection Easy
- Filter High EarnersFiltering & Selection Easy
- Running Total by RegionWindow Functions Medium
Keep going
Up next · new module: Clean and type · 5 min readcast and schemas
Change column types safely, read a schema, and avoid the silent nulls bad casts produce.
Related lessons
row_number / rankSpark internals · 6 min read
Narrow vs wide transformationsData lake & lakehouse · 5 min read
Compaction, OPTIMIZE and Z-order
Previous: withColumn
Primary sources: DataFrame.orderBy · ORDER BY clause