Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to increment a field in the database

Suppose I have a MySQL table that keeps the page visit count and I want to keep track of total number of page visits for each user. Here's the SQL for incrementing the field:

UPDATE visits  
  SET visits = visits + 1  
  WHERE user_id = 12

It's pretty simple but I wonder whether there's a faster way to achieve this. I mean if I have a lot of visitors (ideally millions of users per day), is this method enough or I should use an alternative method. Thanks.

like image 288
Alireza Noori Avatar asked Dec 08 '11 21:12

Alireza Noori


People also ask

How do I increment a column in SQL Server?

The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record. Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5) .

How do you increase a price by 10 percent in SQL?

The standard way of expressing this is: update products set price = price * 1.1 where prod_name like 'HP%'; The from clause is not necessary in this case.

What is increment in database?

Auto Increment is a function that operates on numeric data types. It automatically generates sequential numeric values every time that a record is inserted into a table for a field defined as auto increment.


1 Answers

With an index on user_id this will be pretty fast. I doubt you'll be able to achieve a (noticeably) faster result using any other means. You will likely run into other performance / server issues with millions of users than this query (some call this "micro-optimization")

like image 100
nickb Avatar answered Sep 21 '22 21:09

nickb