Practical 10 - Order By Clause - CSU357P - Shoolini U

Practical 10: Order By Clause

10. ORDER BY Clause

The ORDER BY clause is an optional SQL clause that allows you to display the results of your query in a sorted order (either ascending or descending) based on the columns you specify.

10.1. Syntax

SELECT column1, SUM(column2)
FROM "list-of-tables"
ORDER BY "column-list" [ASC | DESC];

Here, [ ] denotes optional elements.

This statement will select the employee_id, dept, name, age, and salary from the employee_info table where the dept equals 'Sales' and will list the results in ascending (default) order based on their salary.

10.2. Ordering Options

  • ASC: Ascending Order - default
  • DESC: Descending Order
SELECT employee_id, dept, name, age, salary
FROM employee_info
WHERE dept = 'Sales'
ORDER BY salary;

To order by multiple columns, separate the columns with commas.

SELECT employee_id, dept, name, age, salary
FROM employee_info
WHERE dept = 'Sales'
ORDER BY salary, age DESC;

10.3. Example Tables for Exercises

Use these tables for the exercises:

  • items_ordered
  • customers

10.4. Review Exercises

  1. Select the lastname, firstname, and city for all customers in the customers table. Display the results in ascending order based on the lastname.
  2. Repeat exercise #1, but display the results in descending order.
  3. Select the item and price for all items in the items_ordered table where the price is greater than 10.00. Display the results in ascending order based on the price.

10.5. ORDER BY Exercise Answers

10.5.1. Exercise #1
SELECT lastname, firstname, city
FROM customers
ORDER BY lastname;
10.6.1. Exercise #2
SELECT lastname, firstname, city
FROM customers
ORDER BY lastname DESC;
10.7.1. Exercise #3
SELECT item, price
FROM items_ordered
WHERE price > 10.00
ORDER BY price ASC;