MySQL INSERT and SELECT Order of precedence

if INSERT and SELECT are executed at the same time on the mysql table which will be the first?

Example. Suppose the number of columns in the users table is 0.

Then these two queries are run at the same time (assume they are the same mili / micro second):

INSERT into users (id) values (1)

      

and

SELECT COUNT(*) from users

      

Will the last query return 0 or 1?

+2


a source to share


2 answers


Whether your table is users

MyISAM or InnoDB dependent.

If it is MyISAM, one statement or other item is locking the table, and you can do a bit of that to constrain the locking of tables yourself.



If it is InnoDB it is transaction based. The multi-version architecture allows concurrent access to the table, and SELECT

will see the number of rows since the start of its transaction. If it goes simultaneously INSERT

, it SELECT

will see 0 lines. In fact, you might even see 0 rows of help SELECT

completed after a few seconds if the transaction for INSERT

has not yet completed.

It is not possible to start two transactions at the same time. Transactions are guaranteed to be in some order.

+5


a source


It depends on which instruction will be executed first. If the second will return 1 first, if the second will execute the first then it will return 0. Even you execute them on a machine with multiple physical cores and due to the locking mechanism, they will never execute exactly the same timestamp.



+2


a source







All Articles