MySQL: Increment an exisitng value

Contributor Icon Contributed by qmchenry Date Icon February 24, 2007  
Tag Icon Tagged: MySQL

This slick MySQL syntax allows you to increment or decrement an existing number in a table without first having to read the value. This is a nice way to increment an access counter.


To increment the value ‘counter’ by one for the row in table ‘images’ where ‘image_id’ is ‘15′, use:

UPDATE images SET counter=counter+1 WHERE image_id=15

To decrement the value, use ‘counter=counter-1′ instead. Incrementing or decrementing by other values (or using whatever valid arithmetic arm flexing you need) will work, too.

Previous recipe | Next recipe |
 
  • Super, just what I needed to know.
  • TeyBobster
    What would be the syntax for decrementing/incrementing a number and not an image?
  • He ain't incrementing an image, that is just the name of the table, and pretty sure that 'counter' is a tuple in the table, and that it's an Integer.
  • Thank you
  • Thanks this is what i was looking for.....
blog comments powered by Disqus