SQL Server – SELECT Statement with ORDER BY clause

SELECT Statement with ORDER BY clause

The records displayed by any query will be ordered by default as they are stored in the database table.

But we can use ORDER BY clause to order the result set in ascending or descending order. By default it will display the result set in ascending order. It has to be the last clause in your query.

Example:

USE AdventureWorks

— It will return rows order by StateProvinceID

SELECT * FROM Person.Address ORDER BY StateProvinceID

— It will return retrun same result as above query

SELECT * FROM Person.Address ORDER BY StateProvinceID ASC

— It will return rows order by StateProvinceID in descending order

SELECT * FROM Person.Address ORDER BY StateProvinceID DESC

We can sort the data based two or more columns also, see the example below:

Example:

USE AdventureWorks

— It will sort reslt first on StateProvinceID then on City

SELECT * FROM Person.Address ORDER BY StateProvinceID, City

— It will sort reslt first on StateProvinceID then on City in Desc. order

SELECT * FROM Person.Address ORDER BY StateProvinceID, City DESC

See also:

DML SELECT Statement

SELECT Statement with WHERE clause

SELECT Statement with WHERE BETWEEN clause

SELECT Statement with WHERE IN clause

SELECT Statement with WHERE LIKE clause

SELECT Statement multiple WHERE conditions

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: