Are databases single threaded?

Let's say there is a hospital running a simple database. This database contains a table "patients" with 1,000,000 records - each record is a patient whose status is either "active" or "empty".

Bob runs the following query, which will take a few seconds, or maybe minutes, to complete:

SELECT COUNT(*) FROM PATIENTS WHERE STATUS = "active"

      

At the moment Bob is starting to fulfill the request, 100 patients are active.

However, while the query is running, Susie runs the following command on the table:

UPDATE PATIENTS SET STATUS = "discharged" WHERE PATIENT_ID = 583739789

      

This command discharges one of the active patients, changing the actual "active" patient reading to 99.

After Susie does this, Bob's request ends. Will his query result in 100 or 99 active patients? How are different databases handled (Oracle, MySQL, SQLite, etc.)?

+3


source to share


1 answer


Considering that the question mentions SQL queries, I'm going to assume you mean "all SQL queries with one thread".

SQL servers are designed to handle multiple connections, but each transaction log entry must be processed sequentially.

In short, many people can connect to multiple threads with the server, but only one transaction can happen at any given time.



The best way to look at this is a bit like file access (databases are pretty much the same in this regard).

2 threads cannot really "reliably" write a file at the same time unless there is some definite knowledge (like which part of the file is written), but even knowing that it will write the stream earlier part of the file pushing the content later in file.

So, for that kind of mind, SQL is "transactional" and processes each statement in a sequential manner ... it's just really good at it quickly!

+1


source







All Articles