Thursday, 15 December 2011

SQL Order By


The ORDER BY keyword is used to sort the result-set by a specified column.
The ORDER BY keyword sort the records in ascending order by default.
If you want to sort the records in a descending order, you can use the DESC keyword.


The "custmast" table:

custcode
custname
city
qty
rate
1
Siva
Srivilliputtur
50
70
2
Bala
Sivakasi
30
56
3
Kanna
Madurai
100
200
4
Vijay
Chennai
30
30
5
Kodee
Srivilliputtur
60
30
5
Kodee
Srivilliputtur
60
30

Now we want to select all the CustMast from the table above, however, we want to sort the persons by their custname.


We use the following SELECT statement:


SELECT * FROM CustMast
ORDER BY CustName 

               (OR)


SELECT * FROM CustMast
ORDER BY CustName ASC



custcode
custname
city
qty
rate
2
Bala
Sivakasi
30
56
3
Kanna
Madurai
100
200
5
Kodee
Srivilliputtur
60
30
5
Kodee
Srivilliputtur
60
30
1
Siva
Srivilliputtur
50
70
4
Vijay
Chennai
30
30



ORDER BY DESC Example



Now we want to select all the persons from the table above, however, we want to sort the persons descending by their custname


We use the following SELECT statement:


SELECT * FROM CustMast
ORDER BY CustName 
DESC


custcode
custname
city
qty
rate
4
Vijay
Chennai
30
30
1
Siva
Srivilliputtur
50
70
5
Kodee
Srivilliputtur
60
30
5
Kodee
Srivilliputtur
60
30
3
Kanna
Madurai
100
200
2
Bala
Sivakasi
30
56

No comments:

Post a Comment


”Back