blog post

SELECT returns records in no particular order.
To ensure a specific order use the ORDER BY clause.
ORDER BY allows sorting by one or more columns.
Records can be returned in ascending or descending order.

The SQL ORDER BY syntax

The general syntax is:
SELECT column-names
  FROM table-name
 WHERE condition
 ORDER BY column-names

SQL ORDER BY Examples

Problem: List all suppliers in alphabetical order
SELECT CompanyName, ContactName, City, Country
  FROM Supplier
 ORDER BY CompanyName

The default sort order is ascending, that is, low-high or a-z.
Problem: List all suppliers in reverse alphabetical order
SELECT CompanyName, ContactName, City, Country
  FROM Supplier
 ORDER BY CompanyName DESC

The keyword DESC denotes descending, i.e., reverse order.
Problem: List all customers ordered by country, then by city within each country Ordering by one or more columns is possible.
SELECT FirstName, LastName, City, Country
  FROM Customer
 ORDER BY Country, City

Problem: List all suppliers in the USA, Japan, and Germany, ordered by city, then by company name in reverse order
SELECT Id, CompanyName, City, Country
  FROM Supplier
 WHERE Country IN ('USA', 'Japan', 'Germany')
 ORDER BY Country ASC, CompanyName DESC

This shows that you can order by more than one column.
ASC denotes ascending, but is optional as it is the default sort order. <.br> Problem: Show all orders, sorted by total amount, the largest first, within each year
SELECT Id, OrderDate, CustomerId, TotalAmount
  FROM [Order]
 ORDER BY YEAR(OrderDate) ASC, TotalAmount DESC

Note: DESC means descending, but is optional as it is the default sort order. [Order] must be bracketed because it also is a keywork in SQL.

  • Share This Story


Pleas give your valuable comments to improve the contents.

about author

Atul kumar shukla


I'm Atul Kumar Shukla, working as a web developer.
Welcome to my Blog. This is my personal blog where i post my own questions and answers , articles about ASP.Net., SQL Server, HTML, CSS, Jquery and many more..

Visit Profile

Comments (1)

  • Hermann

    Wednesday, 16 November, 2016 05:13 AM

    Nice

Leave a comment

Name
E-mail
Url
Message

Get More Stuff
Subscribing to the TheOneblogs newsletter and get intersting stuff and updates to your email inbox.
Your Email

 

Style Switcher

Change Color

×! We use cookies to improve your user experience. More information