Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 3, 2022 08:42 pm GMT

Let's run deadlock manually ! [SQL]

What is deadlock?

This is a situation that multiple users wait for releasing each locks, and forever lock wont release.

Let's do deadlock

1 create these tables

-- schemaCREATE TABLE Lefty (    Id INT NOT NULL AUTO_INCREMENT,    Number INT,    PRIMARY KEY(Id));CREATE TABLE Righty (    Id INT NOT NULL AUTO_INCREMENT,    Number INT,    PRIMARY KEY(Id));-- dataINSERT INTO Lefty (Number) VALUES (1);INSERT INTO Righty (Number) VALUES (1);

Lefty table

IdNumber
11

Right table

IdNumber
11

2 Let's start

1.At first both tables start transaction, in other words they start BLOCKING

Imagine 2 users(tabs) try to do something now at same time
sql

2.Execute UPDATE Righty SET Number = Number+1; from left tab
query block

As you see UPDATE SQL waits... and does't finish because Righty was locked before. It's gonna wait forever

3.While executes order2, run UPDATE Lefty SET Number = Number+1; from right tab
Then deadlock error appeared !! Both users wait for releasing each locks now.
deadlock

Nobody can stop running because everybody waits for someone stops to stop running!

If deadlock error didn't appear, you could change autocommit setting

mysql> SELECT @@session.autocommit;+----------------------+| @@session.autocommit |+----------------------+|                    1 |+----------------------+-- change autocommit to 0SET autocommit=0;

Thanks for reading

(just note for me in the future)
Nobody can stop running because everybody waits for someone stops to stop running!
->


Original Link: https://dev.to/kaziusan/lets-run-deadlock-manually-sql-1h

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To