Learning of SQL Day 18

 

Day 18: ORDER BY Clause

Introduction:

  • The ORDER BY clause 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:

  1. Basic ORDER BY Clause:

    • Sort rows in ascending order by a specified column.

sql
-- Sort students by age in ascending order
SELECT * FROM Students
ORDER BY Age;
  1. Sorting in Descending Order:

    • Sort rows in descending order by a specified column.

sql
-- Sort students by age in descending order
SELECT * FROM Students
ORDER BY Age DESC;
  1. Sorting by Multiple Columns:

    • Sort rows by multiple columns.

sql
-- Sort employees by department and then by salary in ascending order
SELECT * FROM Employees
ORDER BY Department, Salary;
  1. Combining ORDER BY with WHERE Clause:

    • Filter and sort rows.

sql
-- 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:

  1. Use the Students table with columns StudentID, FirstName, LastName, Age.

  2. Write a query to sort students by FirstName in ascending order.

  3. Write a query to sort students by Age in descending order.

  4. Write a query to sort employees by Department and then by LastName in ascending order.

  5. Write a query to sort courses by Credits in descending order and then by CourseName in ascending order.

sql
-- 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. 

Post a Comment

0 Comments