ORDER BY Clause Sorting Explained in SQL

ORDER BY Clause Sorting Explained in SQL

Order by clause, in SQL, is used for sorting of data either in ascending order or descending order. This sorting base on one or more columns existing within the table. In some DBMS, sorting in ascending order is a default feature.

Syntax:

SELECT col_name_1, col_name_2, … , col_name_n
FROM tbl_name
ORDER BY col_name ASC|DESC, col_name ASC|DESC, … , col_name_N ASC|DESC;

In this syntax, Order by clause is followed by the column name, followed by the order type, either ascending or descending. Order by clause can be used with multiple columns.

For Example:

The current table view of the Customers table is as follows:

ID C_Name Contact_No City Email Status
1 Tim Robbins +44 54 443-4434 London tim@myemail.uk Active
2 James Chris +44 54 498-3476 Birmingham james@myemail.uk Active
3 Kevin Sputnik +44 54 487-6987 Manchester kevin@myemail.uk Inactive
4 Richard Butler +44 54 422-2345 Birmingham richard@myemail.uk Active
5 David McGregor +44 54 413-0989 Cardiff david@myemail.uk Active
6 Rita Johns +44 55 453-4534 London rita@myemail.uk Active

            SELECT * FROM Customers

            Order by C_Name

Following is the output of the above query.

ID C_Name Contact_No City Email Status
5 David McGregor +44 54 413-0989 Cardiff david@myemail.uk Active
2 James Chris +44 54 498-3476 Birmingham james@myemail.uk Active
3 Kevin Sputnik +44 54 487-6987 Manchester kevin@myemail.uk Inactive
4 Richard Butler +44 54 422-2345 Birmingham richard@myemail.uk Active
6 Rita Johns +44 55 453-4534 London rita@myemail.uk Active
1 Tim Robbins +44 54 443-4434 London tim@myemail.uk Active

In the above table, all the data is sorted in ascending order. The default execution of Order by clause is in ascending order therefore it is not mandatory to mentioned ASC, however, if sorting is required in descending order than it is mandatory to use the keyword DESC after the column.

For Example:

            SELECT * FROM Customers

            Order by C_Name DESC

Following is the output of the above query.

ID C_Name Contact_No City Email Status
1 Tim Robbins +44 54 443-4434 London tim@myemail.uk Active
6 Rita Johns +44 55 453-4534 London rita@myemail.uk Active
4 Richard Butler +44 54 422-2345 Birmingham richard@myemail.uk Active
3 Kevin Sputnik +44 54 487-6987 Manchester kevin@myemail.uk Inactive
2 James Chris +44 54 498-3476 Birmingham james@myemail.uk Active
5 David McGregor +44 54 413-0989 Cardiff david@myemail.uk Active

More Related Articles For You

    DBMS Tutorial

    SQL and DBMS Interview Questions with Answers

    DBMS and SQL Practice Tests , Questions and Quizzes

Search

Shortcodes Ultimate

 
Follow Us
 
BGP