Database Essentials using Postgres - Writing Basic SQL Queries - Sorting Data

In this article, we will delve into the concept of sorting data using SQL. We will explore how to sort data in ascending and descending order based on specific fields or expressions. Sorting is typically performed as the final step in a query and can be done using a single field or multiple fields, also known as composite sorting. We will walk through examples and code snippets to understand the sorting process clearly.

Key Concepts Explanation

Sorting Order

We can sort data in ascending order by default. The ORDER BY clause is used to perform sorting, and we can switch to descending order using DESC.

SELECT * FROM orders
ORDER BY order_customer_id DESC

Composite Sorting

Composite sorting involves sorting data in ascending order based on some fields and descending order on others.

SELECT * FROM orders
ORDER BY order_customer_id, order_date DESC

Hands-On Tasks

  1. Perform a simple sort of data in ascending order based on a specific field.
  2. Sort data in descending order based on multiple fields.


In this article, we covered the fundamental concepts of sorting data using SQL. Sorting is a crucial aspect of SQL querying, and understanding how to effectively sort data can enhance our querying capabilities. Practice these concepts with hands-on tasks and explore further to solidify your understanding of sorting in SQL. Happy learning!

Watch the video tutorial here