Saturday, April 28, 2012

SQL ORDER BY

Hello Friends, welcome to this post, where I will be discussing about the SQL ORDER BY Query.

Pretty Interesting, I have found many people trying to inject SQL query with ORDER BY, but when asked, what does it do, answers are like, "I Dont Know", "Ummm" its so Bad.

Anyways lets start our topic, the ORDER BY query is used to sort out the result set either in Ascending Order or Descending Order, from a specific column.

By default, its set to ascending order, lets check with an example here, lets say we have a Table named "Employee", where we have 3 columns name "PID", "Name" and "Designation".

PID    Name         Designation
222    Whiskey        Admin
444    Onty             Admin
111    Gaurav          Amin
333    Kumaar        Admin

So for our Query:

SELECT * FROM Employee
ORDER BY PID


Our result-set:

PID    Name        Designation
111    Gaurav        Admin
222    Whiskey     Admin
333    Kumaar      Admin
444    Onty          Admin

See here something?? the PID column got sorted in Ascending Order. Now For Descending Order, just need to add the key word, DESC

SELECT * FROM Employee
ORDER BY PID DESC


And Our result-set will be:

PID    Name         Designation
444    Onty            Admin
333    Kumaar       Admin
222    Whiskey      Admin
111    Gaurav        Admin

So I hope Now You Understand what is the work of ORDER BY statement.

Hope this was informative and don't forget to check my next Post.

Thank You!

0 comments:

Post a Comment