This article is half-done without your Comment! *** Please share your thoughts via Comment ***
In PostgreSQL, We can apply different lock mode on the table.
This is also one of the important topics because PostgreSQL has a default MVCC architecture.
Because of MVCC architecture, all other sessions can access table new data or an old version of the data.
Sometimes Isolation Level like Repeatable Read, Serializable might not help us.
When we require explicitly lock on the table, we can use PostgreSQL different types of lock mode like:
ACCESS SHARE, ROW SHARE, ROW EXCLUSIVE, SHARE UPDATE EXCLUSIVE, SHARE, SHARE ROW EXCLUSIVE, EXCLUSIVE, ACCESS EXCLUSIVE.
For highly secure tables, we require lock mode like ACCESS EXCLUSIVE MODE.
Example of ACCESS EXCLUSIVE MODE:
Create a sample table:
1 2 3 4 5 |
CREATE TABLE tbl_Employee ( EmpID INTEGER ,EmpName VARCHAR(50) ); |
1 2 3 4 |
INSERT INTO tbl_Employee VALUES (1,'Anvesh'),(2,'Neevan') ,(3,'Roy'),(4,'Martin'); |
Apply ACCESS EXCLUSIVE MODE on tbl_Employee:
1 2 |
BEGIN TRANSACTION; LOCK TABLE tbl_Employee IN ACCESS EXCLUSIVE MODE; |
Open another session and,try to SELECT tbl_Employee data:
You can not access this table because ACCESS EXCLUSIVE MODE on tbl_Employee.
Now execute COMMIT to release the ACCESS EXCLUSIVE MODE and now you can access tbl_Employee in another session.
1 |
COMMIT TRANSACTION; |
Note: You can apply LOCK MODE on a table only in transaction block like between BEGIN…COMMIT.
Leave a Reply