Mysql Get Highest Value for Column in Table

Today I had a project where I had to find what the highest year was in a database table that contained MLB statistics.  The table contained a column for year and I wanted to see if it was updated for the last year, so I figured out the following query to determine the last year inserted into the table.

MYSQL Query:

SELECT MAX(year) AS year FROM TableName

PHP MYSQL Query:

mysql_query(“SELECT MAX(year) AS year FROM TableName”) or die(mysql_error())

while($r=mysql_fetch_array($result)){

$yr = $r[‘year’];

echo “Highest Year Found: $yr<br />”;

}

Summary

I hope that helps. I have shown how you can get the highest value of a column in basic SQL which could be done from a PHPMyAdmin query window and how to do it with PHP.  All you have to do in the above examples is replace “year” with the column name containing the value you want to find the maximum of and replace “tableName” with the name of the actual table. Of course in the php example, you would also have to add a database connection string before the code for it to work.

Leave a Reply

Your email address will not be published. Required fields are marked *