Sorting in Spark Dataframe

Updated On February 11, 2021 | By Mahesh Mogal

In this blog, we are going to write code to sort the spark dataframe. We can sort our data based on one or more columns just like we do it in SQL. Spark provides two function to sort data, "sort" & "orderBy".

Both of these functions work in the same way. We will mostly be using "orderBy" as it is more close to SQL like syntax.

Sorting Dataframe based on Column Value

Consider our flight data, we want to sort our dataframe using number of flights.

We can similarly output using "orderBy". As you can see, data is sorted in ascending order by default.

Sorting Rows Using Orderby
Sorting Rows Using Orderby

We can also use column expression or column functions with our sorting functions.

Sorting data in Descending order

If we want to change default sorting order for Spark dataframe, we have to use desc function.

Sorting Data in Descending Order
Sorting Data in Descending Order

As seen in output, we can sort data in desending order using sparks inbult desc function.

I hope you found this useful. See you in next blog.

Mahesh Mogal

I am passionate about Cloud, Data Analytics, Machine Learning, and Artificial Intelligence. I like to learn and try out new things. I have started blogging about my experience while learning these exciting technologies.

Stay Updated with Latest Blogs

Get latest blogs delivered to your mail directly.

Recent Posts

Spark Join Types With Examples

In this blog, we are going to learn different spark join types. We will also write code and validate data output for each join type to better understand them.

Read More
Integrate Spark with Jupyter Notebook and Visual Studio Code

In this blog, we are going to integrate spark with jupyter notebook and visual studio code to create easy-to-use development environment.

Read More
Reading Data From SQL Tables in Spark

In this blog, we are going to learn about reading data from SQL tables in Spark. We will create Spark data frames from tables and query results as well.

Read More

Leave a Reply

Your email address will not be published. Required fields are marked *

linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram