Is there a way to increment a value in a database with only one query?

As opposed to first pulling the value, incrementing it with PHP, then

Page 1 of 1

2 Replies - 7053 Views - Last Post: 21 April 2008 - 12:13 PM Rate Topic: -----

#1 spearfish  Icon User is offline

  • Monkey in Training
  • member icon

Reputation: 10
  • View blog
  • Posts: 746
  • Joined: 10-March 08

Is there a way to increment a value in a database with only one query?

Posted 21 April 2008 - 12:01 PM

Sorry, I'm new to SQL.

Right now I'm using a SELECT statement, then doing something like $foo += 5 followed by another UPDATE query.

Can I do this with just one update query? How?

Thanks,
-Spear
Is This A Good Question/Topic? 0
  • +

Replies To: Is there a way to increment a value in a database with only one query?

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4188
  • View blog
  • Posts: 11,857
  • Joined: 18-April 07

Re: Is there a way to increment a value in a database with only one query?

Posted 21 April 2008 - 12:07 PM

You can use an update query....

update table set columnname = columnname + 5 where id = id



This would add 5 to the column name in one update query command where the record id = id. If you want to add 5 to all records, you could of course leave off the where clause and all records for the particular column would have 5 added to it. It works for subtraction, multiplication and division as well. Even concatenation in some databases.

Enjoy!

"At DIC we be one query updating code ninjas... we do one of everything once, even if we don't like to admit it." :snap:
Was This Post Helpful? 0
  • +
  • -

#3 spearfish  Icon User is offline

  • Monkey in Training
  • member icon

Reputation: 10
  • View blog
  • Posts: 746
  • Joined: 10-March 08

Re: Is there a way to increment a value in a database with only one query?

Posted 21 April 2008 - 12:13 PM

Thanks Martyr. That's all I needed.

Everybody on the server "bugs" at DreamHost thanks you too.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1