SQL ORDER BY Clause – Sorting Results Tutorial

SQL Sorting Results – ORDER BY Clause

The ORDER BY clause in SQL is used to sort the result set of a query based on one or more columns. Sorting can be in ascending (ASC) or descending (DESC) order. By default, ORDER BY sorts in ascending order.


1. ORDER BY Ascending

Definition: Sorts data from lowest to highest (A-Z for text, smallest to largest for numbers).

Syntax:

SELECT column1, column2
FROM table_name
ORDER BY column1 ASC;

Example:

SELECT name, age
FROM Student
ORDER BY age ASC;

Displays students sorted by age in ascending order.


2. ORDER BY Descending

Definition: Sorts data from highest to lowest (Z-A for text, largest to smallest for numbers).

Syntax:

SELECT column1, column2
FROM table_name
ORDER BY column1 DESC;

Example:

SELECT name, salary
FROM Employee
ORDER BY salary DESC;

Displays employees sorted by salary in descending order.


3. ORDER BY Multiple Columns

Sort by more than one column. The first column is primary, second is secondary, etc.

SELECT name, dept_id, salary
FROM Employee
ORDER BY dept_id ASC, salary DESC;

Sorts employees by department ascending, and within each department by salary descending.


Lab Practice Tasks

  1. Sort students by name alphabetically using ORDER BY ASC.
  2. Sort employees by salary in descending order using ORDER BY DESC.
  3. Sort employees first by department, then by salary descending.

✔ Blogger-ready HTML | Inline CSS | SQL ORDER BY Tutorial

কোন মন্তব্য নেই:

একটি মন্তব্য পোস্ট করুন