PySpark orderBy() and sort(): order rows

PySpark `orderBy()` (alias `sort()`) returns a new DataFrame with rows sorted by one or more columns. By default sorting is ascending; use `col("x").desc()` or `.asc()` to control direction per column, and pass several columns to break ties.

Sort direction

df.orderBy(col("amount").desc()) sorts high-to-low. Mix directions across columns: orderBy(col("region").asc(), col("amount").desc()).

Nulls ordering

Use desc_nulls_last() / asc_nulls_first() when you need explicit control over where null values appear in the sort.

Example (PySpark)

from pyspark.sql import SparkSession
from pyspark.sql.functions import col

spark = SparkSession.builder.getOrCreate()
df = spark.createDataFrame([("North", 300), ("South", 500), ("North", 100)], ["region", "amount"])

df.orderBy(col("region").asc(), col("amount").desc()).show()

Sorts by region ascending, then amount descending within each region.

Run this example in the free online PySpark compiler

Frequently asked questions

What is the difference between sort() and orderBy() in PySpark?

They are aliases and behave the same; both return a globally sorted DataFrame.

How do I sort descending in PySpark?

Use col("column").desc() inside orderBy, e.g. df.orderBy(col("amount").desc()).

How do I sort by multiple columns in PySpark?

Pass several column expressions to orderBy; earlier columns take priority and later ones break ties.

Open the free PySpark compiler · Data Engineering challenges · Data Engineering jobs