Sorting in DBMS

Sorting helps to sort the records that are retrieved. By default, it displays the records in ascending order of primary key. If we need to sort it based on different columns, then we need to specify it in ORDER BY clause. If we need to order by descending order, then DESC keyword has to be added after the column list.

SELECT * FROM EMPLOYEE ORDER BY emp_name; -- sorts the records in ascending order of emp_name
              

SELECT * FROM EMPLOYEE
ORDER BY EMPLOYEE_NAME DESC; -- Displays all records in descending order of employee name

We can even specify multiple columns to get sorted. It will sort the columns in the order they are specified in the ORDER BY clause. We can even specify some columns to sort in ascending order and some columns to sort in the descending order.

SELECT * FROM EMPLOYEE
ORDER BY EMPLOYEE_NAME, ADDRESS; -- Both EMPLOYEE_NAME and ADDRESS are sorted in ascending order


SELECT * FROM EMPLOYEE
ORDER BY EMPLOYEE_NAME, ADDRESS DESC; -- EMPLOYEE_NAME sorted in ascending order and ADDRESS are sorted in descending order
Translate ยป