31

I was wondering what would be the easiest way to update a column by +1? I will be updating a post count of a category based on when users submits a new post.

Thanks.

Juan Mellado
  • 14,973
  • 5
  • 47
  • 54
Cory
  • 732
  • 3
  • 7
  • 22

7 Answers7

53

The easiest way is to not store the count, relying on the COUNT aggregate function to reflect the value as it is in the database:

   SELECT c.category_name,
          COUNT(p.post_id) AS num_posts
     FROM CATEGORY c
LEFT JOIN POSTS p ON p.category_id = c.category_id

You can create a view to house the query mentioned above, so you can query the view just like you would a table...

But if you're set on storing the number, use:

UPDATE CATEGORY
   SET count = count + 1
 WHERE category_id = ?

..replacing "?" with the appropriate value.

OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
  • 2
    Thanks. Initially my thought to determine the amount of posts in a category would be to check the post tables for a cat_id matching that category and then add them up. Thought this may be resource consuming or less efficient than writing directly to that table. – Cory Oct 05 '10 at 18:37
  • 1
    It's very quick when you have an index on `p.post_id`. – Amadan Oct 06 '10 at 10:56
  • UPDATE CATEGORY SET count = count + 1; perfect solution. – Ahamadullah Saikat Aug 27 '19 at 09:55
37

You can do:

UPDATE categories SET posts = posts + 1 WHERE category_id = 42;

Michael Banzon
  • 4,879
  • 1
  • 26
  • 28
8

How about:

update table
set columnname = columnname + 1
where id = <some id>
Vincent Ramdhanie
  • 102,349
  • 23
  • 137
  • 192
5
update post set count = count + 1 where id = 101
KoolKabin
  • 17,157
  • 35
  • 107
  • 145
3
update table_name set field1 = field1 + 1;
Ahamadullah Saikat
  • 4,437
  • 42
  • 39
  • 1
    Can you provide more context? The question is nearly nine years old, and the same way has been given in answers multiple times – Nico Haase Aug 27 '19 at 10:29
  • I'm using database for 6-7 years. & yesterday I found that solution helpful. So please give positive feedback for my answer. – Ahamadullah Saikat Aug 28 '19 at 13:03
  • Please provide more explanation first - why did you post that answer, while the exact same solution (okay, with another table and column name) has been posted multiple times? – Nico Haase Aug 28 '19 at 13:09
2

How to update order column Count value

Try

  UPDATE order SET                                      
    Order_Count = Order_Count + 100
  WHERE 
    Order_ID = '1234'
SIAMWEBSITE
  • 171
  • 1
  • 4
1
update TABLENAME
set COLUMNNAME = COLUMNNAME + 1
where id = 'YOURID'
praveenraj4ever
  • 384
  • 1
  • 5
  • 14