Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Sql Mysql-example MySQL rank

Related Tutorials


 
 

Share on Google+Share on Google+

MySQL rank

Advertisement
Many times there is a need to rank the records according to some specific field values but there is not any specific method provided in the MySQL to rank the records.

MySQL rank

     

Many times there is a need to rank the records according to some specific field values but there is not any specific method provided in the MySQL to rank the records. We can achieve ranking of the records by the combination of SQL query. 

Here in the following example we will describe how you can get the ranking of the results according to your requirement. First of all we require a database table, therefore we have created a table with the name "mca". 

 

 

 

 

 

Query CREATE TABLE `mca` (
`id` bigint(11) NOT NULL auto_increment,
`name` varchar(255) default NULL,
`subject` varchar(255) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;

/*Data for the table `mca` */

insert into `mca`(`id`,`name`,`subject`) values (1,'Amit','Computer '),(2,'Ramesh','Computer '),(3,'Suman','Computer '),(4,'Vineet','Java'),(5,'Sandeep','C++');
 

Output

 

If we use the following query 

Query SELECT * FROM mca ORDER BY id DESC;
 

Output

 

This is what we have queried that means it can results either in the descending order or in the ascending order but if we want to provide them ranking then we have to write the query as given below:

Query SET @rank=0;

SELECT @rank:=@rank+1 AS rank, id, name, subject FROM mca ORDER BY id DESC;

 

Output

 

So as you can see in the output that it has resulted one more field "rank".

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: January 17, 2009

Related Tutorials

Discuss: MySQL rank  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com