mysql UPDATE tips

Wednesday 25th July 2007 11:50 PM

TAGS: mySQL, update

Seen a few applications/examples which could easily be modified to run a little faster.

Suppose you wanted to record page views, and add to a total every time... I've seen this done before:

SELECT pageViews FROM pages WHERE id=1
UPDATE pages SET pageViews=". $row['pageViews'] + 1 ." WHERE id=1

You can do it with one query, by just using:

UPDATE pages SET pageViews=pageViews+1 WHERE id=1

In a similar style, you can also update a row with values retrieved from the row itself. Suppose you wanted to merge two fields (firstName and lastName) into a single row:

UPDATE users SET fullName=concat(firstName," ",lastName)

You can even do some more advanced (?) maths. Suppose you wanted to shift a set of prices up by 10%, you can do it really easily by simply using:

UPDATE products SET price=price*1.1 WHERE id=1

This is just the tip of the iceberg, but when you're messing with large sets of data, knowing a few "update" tricks can make your job a lot easier!

Comments on this article:


I love feedback and comments, be the first!

Add Comment:


Make a Comment

*Nb, all comments are moderated to prevent spam or inappropriate content.








netforge logo
netforge provides high quality and friendly website design services to business. We're Australian based and reliable... (find out more).