ORDER BY in SQL

For Complete YouTube Video: Click Here

In this class, we will understand ORDER BY in SQL.

We have already discussed the concepts of Number functions, String functions, and Date functions.

ORDER BY in SQL

‘ORDER BY’ is used to sort the information returned.

After fetching the items from the table, if we want to display them in a specific way or order, we use the ORDER BY clause in the query.

Example on ORDER BY

To understand this, we will use the table as shown below.

ORDER BY in SQL 1
ORDER BY in SQL 1

Usually, the rows in the table are displayed in the way they are inserted.

Let’s consider the query shown below.

SELECT * FROM students ORDER BY salary;

The output of the query is as shown below.

ORDER BY in SQL 2
ORDER BY in SQL 2

In the above table, all the rows are arranged in ascending order based on salary values.

The default arrangement of the ‘order by’ is in ascending order.

If we want the values to be displayed in descending order, we must use the desc below.

SELECT * FROM students ORDER BY salary desc;

The output has all the rows in the values in descending order based on the salary values.

ORDER BY in SQL 3
ORDER BY in SQL 3

More examples on ORDER BY

We can also order the values of the rows using one or more rows.

Consider the following query.

SELECT * FROM students ORDER BY salary, name;

The output of the query is as shown below.

ORDER BY in SQL 4
ORDER BY in SQL 4

The rows in the table are ordered by salary and name.

For example, in the above table, consider the salary values 300 within those two rows, the names now do the ordering.

SELECT * FROM students ORDER BY salary desc, name;

The output of the query is as shown below.

ORDER BY in SQL 5
ORDER BY in SQL 5

Now, the rows in the table are ordered by decreasing the salaries and ascending of names.

Consider the salary values 500; now, the ordering is done in ascending order of names within those two rows.

SELECT * FROM students ORDER BY salary desc, name desc;

The output of the query is as shown below.

ORDER BY in SQL 6
ORDER BY in SQL 6

Consider the salary values 500; now, the ordering is done in descending order of names within those two rows.