Search This Blog

SQL ORDER BY Clause

 

SQL: ORDER BY Clause

This SQL tutorial explains how to use the SQL ORDER BY clause with syntax and examples.

Description

The SQL ORDER BY clause is used to sort the records in the result set for a SELECT statement.

Syntax

The syntax for the ORDER BY clause in SQL is:

SELECT expressions
FROM tables
[WHERE conditions]
ORDER BY expression [ ASC | DESC ];

Parameters or Arguments

expressions
The columns or calculations that you wish to retrieve.
tables
The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.
WHERE conditions
Optional. Conditions that must be met for the records to be selected.
ASC
Optional. ASC sorts the result set in ascending order by expression. This is the default behavior, if no modifier is provider.
DESC
Optional. DESC sorts the result set in descending order by expression.

Note

  • If the ASC or DESC modifier is not provided in the ORDER BY clause, the results will be sorted by expression in ascending order. This is equivalent to ORDER BY expression ASC.

DDL/DML for Examples

If you want to follow along with this tutorial, get the DDL to create the tables and the DML to populate the data. Then try the examples in your own database!

Get DDL/DML

Example - Sorting Results in Ascending Order

To sort your results in ascending order, you can specify the ASC attribute. If no value (ASC or DESC) is provided after a field in the ORDER BY clause, the sort order will default to ascending order. Let's explore this further.

In this example, we have a table called customers with the following data:

customer_idlast_namefirst_namefavorite_website
4000JacksonJoegoogle.com
5000SmithJanedigminecraft.com
6000FergusonSamanthabigactivities.com
7000ReynoldsAllencheckyourmath.com
8000AndersonPaigeNULL
9000JohnsonDerekgoogle.com

Enter the following SQL statement:


SELECT *
FROM customers
ORDER BY last_name;

There will be 6 records selected. These are the results that you should see:

customer_idlast_namefirst_namefavorite_website
8000AndersonPaigeNULL
6000FergusonSamanthabigactivities.com
4000JacksonJoetechonthenet.com
9000JohnsonDerektechonthenet.com
7000ReynoldsAllencheckyourmath.com
5000SmithJanedigminecraft.com

This example would return all records from the customers sorted by the last_name field in ascending order and would be equivalent to the following SQL ORDER BY clause:


SELECT *
FROM customers
ORDER BY last_name ASC;

Most programmers omit the ASC attribute if sorting in ascending order.

Example - Sorting Results in descending order

When sorting your result set in descending order, you use the DESC attribute in your ORDER BY clause. Let's take a closer look.

In this example, we have a table called suppliers with the following data:

supplier_idsupplier_namecitystate
100MicrosoftRedmondWashington
200GoogleMountain ViewCalifornia
300OracleRedwood CityCalifornia
400Kimberly-ClarkIrvingTexas
500Tyson FoodsSpringdaleArkansas
600SC JohnsonRacineWisconsin
700Dole Food CompanyWestlake VillageCalifornia
800Flowers FoodsThomasvilleGeorgia
900Electronic ArtsRedwood CityCalifornia

Enter the following SQL statement:


SELECT *
FROM suppliers
WHERE supplier_id > 400
ORDER BY supplier_id DESC;

There will be 5 records selected. These are the results that you should see:

supplier_idsupplier_namecitystate
900Electronic ArtsRedwood CityCalifornia
800Flowers FoodsThomasvilleGeorgia
700Dole Food CompanyWestlake VillageCalifornia
600SC JohnsonRacineWisconsin
500Tyson FoodsSpringdaleArkansas

This example would sort the result set by the supplier_id field in descending order.

Example - Sorting Results by relative position

You can also use the SQL ORDER BY clause to sort by relative position in the result set, where the first field in the result set is 1, the second field is 2, the third field is 3, and so on.

In this example, we have a table called products with the following data:

product_idproduct_namecategory_id
1Pear50
2Banana50
3Orange50
4Apple50
5Bread75
6Sliced Ham25
7KleenexNULL

Now enter the following SQL statement:


SELECT product_id, product_name
FROM products
WHERE product_name <> 'Bread'
ORDER BY 1 DESC;

There will be 6 records selected. These are the results that you should see:

product_idproduct_name
7Kleenex
6Sliced Ham
4Apple
3Orange
2Banana
1Pear

This example would sort the results by the product_id field in descending order, since the product_id field is in position #1 in the result set and would be equivalent to the following SQL ORDER BY clause:


SELECT product_id, product_name
FROM products
WHERE product_name <> 'Bread'
ORDER BY product_id DESC;

Example - Using both ASC and DESC attributes

When sorting your result set using the SQL ORDER BY clause, you can use the ASC and DESC attributes in a single SELECT statement.

In this example, let's use the same products table as the previous example:

product_idproduct_namecategory_id
1Pear50
2Banana50
3Orange50
4Apple50
5Bread75
6Sliced Ham25
7KleenexNULL

Now enter the following SQL statement:


SELECT *
FROM products
WHERE product_id <> 7
ORDER BY category_id DESC, product_name ASC;

There will be 6 records selected. These are the results that you should see:

product_idproduct_namecategory_id
5Bread75
4Apple50
2Banana50
3Orange50
1Pear50
6Sliced Ham25

This example would return the records sorted by the category_id field in descending order, with a secondary sort by product_name in ascending order.

No comments:

Post a Comment

Using SQL*Plus to Unlock Accounts and Reset Passwords

  Using SQL*Plus to Unlock Accounts and Reset Passwords Use this SQL*Plus procedure to unlock and reset user account passwords. Log in as th...