ORDER BY Clause

Whenever a SELECT query is executed, the resulting rows emerge in a pre-decided order. One can sort the results or a query in a specific order using the ‘ORDER BY’ clause. The ORDER BY clause allows string of query results by one or more columns. The sorting can be done either in ascending order or in descending order , the default sorting is the ascending order. The data in the table is not sorted inly the results that appear on the screen are sorted.

Syntax:

SELECT <column name> [, <column name>,...]
FROM <table name>
WHERE <condition>
ORDER BY <column name>

EXAMPLES

select * from students
where Subject LIKE '%y'
ORDER BY Class;
select * from students
ORDER BY Roll DESC;
select * from students
ORDER BY Subject ASC;

To specify the sort order we may specify DESC for descending order and ASC for ascending order. Furthermore, ordering/sorting can be performed on multiple attributes.

select * from students
ORDER BY Roll DESC, Name;

The multiple fields are separated by commas. In order to fulfill an ORDER BY request, SQL must perform a sort. Since sorting a large number of tuples may be costly, it is desirable to sort only when necessary.

One thought on “ORDER BY Clause

Add yours

Leave a comment

Create a website or blog at WordPress.com

Up ↑

Design a site like this with WordPress.com
Get started