Understand the concepts of locking, blocking, and deadlocking

Locking is what happens when a query runs against a database. There are read locks and write locks:

  • Read locks: Allow other queries reading data (SELECT) to read as well. 
  • Write locks: Other queries can't read or write data until the write (INSERT, UPDATE, DELETE) query is complete. 

Blocking can happen when one or more queries holds a lock on the same data. Deadlocking can happen when each query locks data that the other query needs.

For example, when you run a query, MySQL has to decide how to get the data from the table(s). If your table has no index, the query will need to scan through the entire table to find the data, much the same way you would have to scan through an entire book if it didn't have an index in the back. That would be very time-consuming, depending on how long the book is. The same thing goes for an index on a table. You might not notice any issues with your query running for a long time if the table is small, but once the table is large, scanning the entire table to get the results could take quite a while. Plus, if other people are also running queries on the same table, the results may never return since queries may block each other or deadlock. 

Locking happens when you run a query. Locking isn't bad in itself. Locking becomes an issue when different queries interfere with each other and cause blocking. Blocking happens when more than one query is trying to read or write the same data. Sometimes, blocking happens and it's just for a short period of time, so blocking isn't necessarily bad, but if two or more queries request the same data for creating locks that won't be resolved, MySQL will decide which is easiest to kill (usually based on how long it will take to rollback any given query), and this is what is referred to as a deadlock. MySQL will need to roll back a query if it hasn't finished inserting, updating, or deleting data to keep the data in a consistent state.

If you create indexes and use them properly with your queries, you will have less blocking and deadlocking to deal with because the index will allow you to query data more quickly. 

The main way indexes can speed up a query is by using the columns in the index when joining tables, when filtering results (that is, yearid = 2017), and when ordering results (that is, order by year descending). 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.78.30