April 2, 2012

How do I get the highest number in a column?

Question by Skiroid

My table named pictures has a column named pic and I’m wanting to get the highest number in that column. Each row has a unique number in pic and it goes up by 1 each row. But one or two rows won’t have a number in the column and will have some text instead. Like grapes.

Here’s an example of the table…

  TABLE: pictures
 ___________________
|  caption  |  pic  |
|-------------------|
|   some    |   1   |
|  random   |   2   |
|  thing    |   3   |
|   here    |grapes |
|___________________|

So, how would I get the highest number in the column pic which would be 3?

Column pic is a varchar.

Answer by zerkms

SELECT MAX(CONVERT(pic, UNSIGNED INTEGER)) AS max_pic
FROM pictures
WHERE CONVERT(pic, UNSIGNED INTEGER) IS NOT NULL 

The WHERE pic = pic + 0 condition is a trick that helps checking if it is a number value

Answer by Starx

Use MAX() to get the maximum value available. Like this

SELECT MAX(pic) FROM `pictures` WHERE CONVERT(`pic`, SIGNED INTEGER) IS NOT NULL 

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!