Back to course

Sorting Results with ORDER BY

Database Fundamentals: From Zero to Hero

Lesson 19: Sorting Results with ORDER BY

By default, SQL retrieves data in an arbitrary order (often based on physical storage). The ORDER BY clause allows you to sort your result set logically.

Basic Syntax

The ORDER BY clause always comes last in a basic SELECT statement.

sql SELECT [columns] FROM [table] WHERE [condition] ORDER BY [column_name] [ASC | DESC];

Sorting Direction

  1. ASC (Ascending): Sorts from smallest to largest (A to Z, 1 to 10, oldest date to newest date). This is the default if no direction is specified.
  2. DESC (Descending): Sorts from largest to smallest (Z to A, 10 to 1, newest date to oldest date).

Example 1: Sorting by Price (Low to High)

sql SELECT Name, Price FROM Products ORDER BY Price ASC;

Example 2: Sorting by Date (Newest First)

sql SELECT OrderID, OrderDate FROM Orders ORDER BY OrderDate DESC;

Sorting by Multiple Columns

You can specify multiple columns for sorting. The order of columns determines the sorting hierarchy.

Example: Sort by Department (primary) then by Salary (secondary)

sql SELECT Name, Department, Salary FROM Employees ORDER BY Department ASC, Salary DESC;

In this example, all employees in 'HR' will be listed together, sorted from highest salary to lowest salary within that group.