How to Use SQL ‘Order By’ Clause – Programming, Pseudocode Example, C# Programming Example

How to Use SQL ‘Order By’ Clause

In this tutorial, we’ll learn How to use order by clause in SQL.

Order by clause is used to sort the fetched data either in ascending or descending order. When we execute our select statement we get unsorted results as our output. In order to arrange them in a sorted way – order by comes in picture.

  • Order by Clause is an optional expression in an sql query. If we don’t write, the query sorts according to the primary key column.
  • Orderby clause is used to sort table according to the specified column or the columns.
  • For ascending sort, we write “asc” or nothing after column name.
  • For Descending sort, we write “desc” after column name.
  • For Random sort, we write newid() function after order by clause
  • Instead of column names, sequence number of column names would be wriiten.

Syntax of Order by clause

If we have conditions at the same time then:

By Default Order by sorts the column in ascending order. If you want to sort your column in descending order then you have to explicitly use the keyword “DESC”.

Sql Order By Examples on Northwind Database (Products)

Example 1: List all products sorted by name:

Example 2: List all products sorted by Category ID (descending), then by UnitPrice:

Example 3: List the products where CategoryID in between 4 and 6 sorted by ProductName:

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: