Skip to content
Bronze 4 min read · Selection 3 practice problems ↓

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

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

namedeptsalary
BenSales48000
Faridnull39000
AshaEngineering72000
EshaSales50000

Output

namedeptsalary
AshaEngineering72000
EshaSales50000
BenSales48000
Faridnull39000

Sorted by dept ascending with nulls last, then salary descending within each department.

Run the example

PySparkSpark SQL

Input: employees

idnamedeptsalarymanager_id
1AshaEngineering72000null
2BenSales480001
3ChitraEngineering950001
4DevHR510001
5EshaSales500002
6Faridnull390002
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

DirectionDefaultOverride
AscendingNulls firstasc_nulls_last() / ASC NULLS LAST
DescendingNulls lastdesc_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

Total order across all partitions. Needs a range-partitioning shuffle.

sortWithinPartitions

Sorts each partition independently. No shuffle. Enough before writing files, so each file is sorted for better min/max skipping.
Tip: 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

  • orderBy sorts globally; ascending puts nulls first by default.
  • Use asc_nulls_last / NULLS LAST to control null placement.
  • A global sort shuffles everything; sortWithinPartitions does 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?"

Aggregate revenue per customer first, then 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?"
Ascending puts nulls first, descending puts them last. Use 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."
Use 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."
Files are written in order, but a later read with several partitions, or any shuffle afterwards, gives no guaranteed order. If a consumer needs order, it must sort.

Check yourself

3 questions

With 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

See all 29 problems →

Keep going

Up next · new module: Clean and type · 5 min read
cast and schemas
Change column types safely, read a schema, and avoid the silent nulls bad casts produce.

Related lessons

Previous: withColumn

Primary sources: DataFrame.orderBy · ORDER BY clause