Practical 10: Order By Clause
2024, May 8
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.
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.
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;
Use these tables for the exercises:
customers
table. Display the results in ascending order based on the lastname.items_ordered
table where the price is greater than 10.00. Display the results in ascending order based on the price.SELECT lastname, firstname, city
FROM customers
ORDER BY lastname;
SELECT lastname, firstname, city
FROM customers
ORDER BY lastname DESC;
SELECT item, price
FROM items_ordered
WHERE price > 10.00
ORDER BY price ASC;