Notes

`ORDER BY` Clause in DBMS (MySQL) [ English ]

< Prev Next >

Introduction

When retrieving data from a table using the SELECT statement, the results may not appear in any particular order. In many situations, users need the data to be arranged in a specific order such as ascending or descending.

The ORDER BY clause is used to sort the result of a query based on one or more columns. This helps in organizing data for easier reading and analysis.

Definition

The ORDER BY clause is used in SQL to sort the records retrieved from a table in ascending or descending order based on one or more columns.

Syntax

SELECT column1, column2, ...
FROM table_name
ORDER BY column_name [ASC | DESC];

Where:

Example Table

Suppose we have a table named students.

id name age course
1 Rahul 20 BCA
2 Anita 21 BBA
3 Rohit 19 BCA
4 Priya 22 BCom

Example 1: Sorting in Ascending Order

SELECT * FROM students
ORDER BY age ASC;

Output

id name age course
3 Rohit 19 BCA
1 Rahul 20 BCA
2 Anita 21 BBA
4 Priya 22 BCom

The records are arranged from lowest age to highest age.

Example 2: Sorting in Descending Order

SELECT * FROM students
ORDER BY age DESC;

Output

id name age course
4 Priya 22 BCom
2 Anita 21 BBA
1 Rahul 20 BCA
3 Rohit 19 BCA

The records are arranged from highest age to lowest age.

Sorting by Multiple Columns

It is also possible to sort records using more than one column.

SELECT * FROM students
ORDER BY course ASC, age DESC;

In this example:

Important Notes

Example:

SELECT * FROM students
WHERE course = 'BCA'
ORDER BY age;

Key Points

Summary

The ORDER BY clause is used to arrange the results of a SQL query in a specific order. By sorting data based on one or more columns, users can easily analyze and interpret information stored in a database.

< Prev Next >