Rank SQL query Result

I was playing with mysql client,suddenly found that it would be really great if I can rank the query results.Lets say we have a table like below:

Now we want to rank  the students based on their Roll No.To do it,we have to define a variable with the initial value of 0 and in next query we will show it by as one of the resulted field  query

like below:


set @counter=0;

select @counter:=@counter+1 as Rank,LastName,Roll_no as Roll  from Students order by Roll_no ASC;

and in next query we will show it by as one of the resulted field ,that results:

Check mysql docs from here to know details about user defined variable in mysql

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