SQL - SPLessons

SQL Order By

Chapter 31

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

SQL Order By

SQL Order By

shape Description

To arrange data of a table either in ascending order or descending order based on single column use SQL Order By clause i.e., Select “*” from the table name will show all the rows from the table and order by clause is used to arrange the specific column in descending or ascending order.

shape Conceptual
figure

shape Syntax

Select * from <table_name> ORDER BY <column_name> ASC|DESC;

Table_name =>Any accurate table.

column_name =>The condition that one can perform on a column by using Order by clause.

shape Examples

By viewing the below example, the concept of Order by clause can be easily understood.

sql> select * from employee;
+--------+-------+-------+
| emp_id | ename | salary|
+--------+-------+-------+
|   1001 | mike  | 12000 |
|   1002 | rambo | 13000 |
|   1003 | David | 15000 |
+--------+-------+-------+
3 rows in set (0.00 sec)

sql> select * from employee order by salary desc;
+--------+-------+-------+
| emp_id | ename | salary|
+--------+-------+-------+
|   1003 | David | 15000 |
|   1002 | rambo | 13000 |
|   1001 | mike  | 12000 |
+--------+-------+-------+
3 rows in set (0.06 sec)

sql> select * from employee order by salary ;
+--------+-------+-------+
| emp_id | ename | salary|
+--------+-------+-------+
|   1001 | mike  | 12000 |
|   1002 | rambo | 13000 |
|   1003 | David | 15000 |
+--------+-------+-------+
3 rows in set (0.06 sec)

sql>select * from employee order by name;
+--------+-------+-------+
| emp_id | ename | salary|
+--------+-------+-------+
|   1003 | David | 15000 |
|   1001 | mike  | 12000 |
|   1001 | rambo | 13000 |
+--------+-------+-------+
3 rows in set (0.06 sec)

The above example tells that, when order by clause operation is performed on a column name like salary, then it automatically displays the entire details of employees in ascending order and if we mention in the query as desc then it will display all the values in descending order.

Summary

shape Key Points

  • SQL Order By Clause – Utilized to arrange the table column in descending or ascending order.