MySQL - UNLOCK TABLES Statement



MySQL UNLOCK TABLES Statement

A session releases all the tables locks with it at once. You can implicitly release the table locks. If the connection to the server terminates explicitly or implicitly all the locks will be released.

You can release the locks of a table explicitly using the UNLOCK TABLES statement.

Syntax

Following is the syntax of the MySQL UNLOCK TABLES statement −

UNLOCK TABLES

Example

Suppose we have created a table that contains the sales details along with the contact details of the customers as shown below −

CREATE TABLE SalesDetails (
   ID INT,
   ProductName VARCHAR(255),
   CustomerName VARCHAR(255),
   DispatchDate date,
   DeliveryTime time,
   Price INT,
   Location VARCHAR(255),
   CustomerAge INT,
   CustomrtPhone BIGINT,
   DispatchAddress VARCHAR(255),
   Email VARCHAR(50)
);

Now, let’s insert 2 records into the above created table using the INSERT statement as −

Insert into SalesDetails values
(1, 'Key-Board', 'Raja', DATE('2019-09-01'), TIME('11:00:00'), 7000, 
'Hyderabad', 25, '9000012345', 'Hyderabad – Madhapur', 
'pujasharma@gmail.com'),
(2, 'Mobile', 'Vanaja', DATE('2019-03-01'), TIME('10:10:52'), 9000, 
'Chennai', 30, '9000012365', 'Chennai- TNagar', 
'vanajarani@gmail.com'); 

If we want another table with just the contact details of the customer create a table as −

CREATE TABLE CustContactDetails (
   ID INT,
   Name VARCHAR(255),
   Age INT,
   Phone BIGINT,
   Address VARCHAR(255),
   Email VARCHAR(50)
);

Following queries insets records into the CustContactDetails table using the INSERT INTO SELECT statement. Here, we are trying to insert records from the SALES_DETAILS table to CustContactDetails table.

Here before the transfer, we are acquiring the write lock on the table to which we are inserting records and acquiring read lock on the table from which we are inserting records. Finally, after the transfer we are releasing the records.

LOCK TABLES SalesDetails READ, CustContactDetails WRITE;
INSERT INTO CustContactDetails (ID, Name, Age, Phone, Address, Email)
SELECT
ID, CustomerName, CustomerAge, CustomrtPhone, DispatchAddress, Email
FROM SalesDetails
WHERE ID = 1 AND CustomerName = 'Raja';

Let us insert another record −

INSERT INTO CustContactDetails (ID, Name, Age, Phone, Address, Email)
SELECT
ID, CustomerName, CustomerAge, CustomrtPhone, DispatchAddress, Email
FROM SalesDetails
WHERE ID = 2 AND CustomerName = 'Vanaja';
UNLOCK TABLES;

Verification

You can verify the contents of the CustContactDetails table as shown below −

SELECT * FROM CustContactDetails;

Output

The above mysql query will generate the following output −

ID Name Age Phone Address Email
1 Raja 25 9000012345 Hyderabad - Madhapur pujasharma@gmail.com
2 Vanaja 30 9000012365 Chennai - TNagar vanajarani@gmail.com
Advertisements