Explain ORDER BY in Sql
In SQL, the ORDER BY
clause is used to sort the result set of a query by one or more columns. You can specify whether to sort in ascending (ASC
) or descending (DESC
) order. By default, the ORDER BY
clause sorts in ascending order.
Basic Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
Example
Assume we have a table named Employees
with the following data:
EmployeeID | FirstName | LastName | Age | Salary |
---|---|---|---|---|
1 | John | Doe | 30 | 50000 |
2 | Jane | Smith | 25 | 60000 |
3 | Alice | Johnson | 30 | 55000 |
4 | Bob | Brown | 28 | 45000 |
Query to Sort by Age (Ascending)
SELECT * FROM Employees
ORDER BY Age;
Output:
EmployeeID | FirstName | LastName | Age | Salary |
---|---|---|---|---|
4 | Bob | Brown | 28 | 45000 |
2 | Jane | Smith | 25 | 60000 |
3 | Alice | Johnson | 30 | 55000 |
1 | John | Doe | 30 | 50000 |
Query to Sort by Age (Descending)
SELECT * FROM Employees
ORDER BY Age DESC;
Output:
EmployeeID | FirstName | LastName | Age | Salary |
---|---|---|---|---|
3 | Alice | Johnson | 30 | 55000 |
1 | John | Doe | 30 | 50000 |
4 | Bob | Brown | 28 | 45000 |
2 | Jane | Smith | 25 | 60000 |
Query to Sort by Multiple Columns
SELECT * FROM Employees
ORDER BY Age ASC, Salary DESC;
Output:
EmployeeID | FirstName | LastName | Age | Salary |
---|---|---|---|---|
4 | Bob | Brown | 28 | 45000 |
2 | Jane | Smith | 25 | 60000 |
3 | Alice | Johnson | 30 | 55000 |
1 | John | Doe | 30 | 50000 |
Here, the result set is first sorted by Age
in ascending order. If there are ties in the Age
, it further sorts by Salary
in descending order.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.