mysqltransactionssynchronizationlockingdatabase-concurrency

MySQL query synchronization/locking question


I have a quick question that I can't seem to find online, not sure I'm using the right wording or not.

Do MySql database automatically synchronize queries or coming in at around the same time? For example, if I send a query to insert something to a database at the same time another connection sends a query to select something from a database, does MySQL automatically lock the database while the insert is happening, and then unlock when it's done allowing the select query to access it? Thanks


Solution

  • Do MySql databases automatically synchronize queries coming in at around the same time?

    Yes.

    Think of it this way: there's no such thing as simultaneous queries. MySQL always carries out one of them first, then the second one. (This isn't exactly true; the server is far more complex than that. But it robustly provides the illusion of sequential queries to us users.)

    If, from one connection you issue a single INSERT query or a single UPDATE query, and from another connection you issue a SELECT, your SELECT will get consistent results. Those results will reflect the state of data either before or after the change, depending on which query went first.

    You can even do stuff like this (read-modify-write operations) and maintain consistency.

     UPDATE table 
        SET update_count = update_count + 1, 
            update_time = NOW()
      WHERE id = something
    

    If you must do several INSERT or UPDATE operations as if they were one, you'll need to use the InnoDB engine, and you'll need to use transactions. The transaction will block SELECT operations while it is in progress. Teaching you to use transactions is beyond the scope of a Stack Overflow answer.