Home Sql Mysql-example MySQL rank



MySQL rank
Posted on: January 17, 2009 at 12:00 AM
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".

Related Tags for MySQL rank:
sqlmysqlcquerycomidetimeiomethodvivaluefieldidifierecordnatrecordsvaluestorankingldcibienotcanpeimmaninnorankmcaesspecmeprocombinationbinsspsoeeatanymykisimeccspecificrdsvassrdthchiatialumanypronombomo


Ask Questions?    Discuss: MySQL rank  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.