Day 18: ORDER BY Clause
Introduction:
The
ORDER BYclause is used to sort the result set of a query by one or more columns. It allows you to organize data in ascending or descending order.
Key Concepts:
Sorting Rows: Order rows by specified columns.
Ascending Order: Default sorting order (ASC).
Descending Order: Reverse sorting order (DESC).
SQL Commands and Examples:
Basic ORDER BY Clause:
Sort rows in ascending order by a specified column.
-- Sort students by age in ascending order
SELECT * FROM Students
ORDER BY Age;
Sorting in Descending Order:
Sort rows in descending order by a specified column.
-- Sort students by age in descending order
SELECT * FROM Students
ORDER BY Age DESC;
Sorting by Multiple Columns:
Sort rows by multiple columns.
-- Sort employees by department and then by salary in ascending order
SELECT * FROM Employees
ORDER BY Department, Salary;
Combining ORDER BY with WHERE Clause:
Filter and sort rows.
-- Select and sort courses with more than 3 credits by course name in descending order
SELECT * FROM Courses
WHERE Credits > 3
ORDER BY CourseName DESC;
Practice Exercise:
Use the Students table with columns
StudentID,FirstName,LastName,Age.Write a query to sort students by
FirstNamein ascending order.Write a query to sort students by
Agein descending order.Write a query to sort employees by
Departmentand then byLastNamein ascending order.Write a query to sort courses by
Creditsin descending order and then byCourseNamein ascending order.
-- Sort students by FirstName in ascending order
SELECT * FROM Students
ORDER BY FirstName;
-- Sort students by Age in descending order
SELECT * FROM Students
ORDER BY Age DESC;
-- Sort employees by Department and then by LastName in ascending order
SELECT * FROM Employees
ORDER BY Department, LastName;
-- Sort courses by Credits in descending order and then by CourseName in ascending order
SELECT * FROM Courses
ORDER BY Credits DESC, CourseName;
Using the ORDER BY clause allows you to present your data in an organized and readable manner.
0 Comments