Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
SQL- Lock Table
Next article icon

SQL- Lock Table

Last Updated : 06 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

SQL Server is a versatile database and it is the most used Relational Database that is used across many software industries. In this article, let us see about the SQL Lock table in SQL Server by taking some practical examples. As it is meeting  Atomicity(A), Consistency(C), Isolation(I), and Durability(D) requirements it is called a relational database. In order to maintain ACID mechanisms, in SQL Server, a lock is maintained. 

By using Azure Data Studio, let us see the concepts of the Lock mechanism by starting with creating the database, table creation, locks, etc. Azure Data Studio works well for Windows 10, Mac, and Linux environments. It can be installed from here.

Database creation :

Command to create the database.  Here GEEKSFORGEEKS is the db name.

--CREATE DATABASE <dbname>;

Create Database GEEKSFORGEEKS:

Make the database active

USE GEEKSFORGEEKS;
Once the database is made active, at the top, the database name will be shown

Adding the tables to the database :

Creating a table with Primary Key. Here ID is a PRIMARY KEY meaning each author will have their own ID

CREATE TABLE Authors (     ID INT NOT NULL PRIMARY KEY,     <other column name1> <datatype> <null/not null>,     ..........  );

If explicitly "NOT NULL" is specified, that column should have values. If not specified, it is by default "NULL".

"Authors" named table is created under "GEEKSFORGEEKS" database

Inserting rows in the table :

There will be scenarios like either we can add all columns or few column values to the table. The reason is some columns might require null values by default. 

Example 1 :

INSERT INTO <table_name> (column1, column2, column3, ...)  VALUES (value1, value2, value3, ...);

Here we are taking into consideration the mentioned columns and hence only their required values are inserted by the above query.

Example 2 :

INSERT INTO <table_name> VALUES (value1, value2, value3, ...);

Here we are not specifying any columns means, all the values to all the columns need to be inserted.

Violation of PRIMARY KEY constraint 'PK__Authors__3214EC277EBB8ED1'.   Cannot insert duplicate key in object 'dbo.Authors'. The duplicate key value is (1).

The above errors occurred in the above screenshot shows that "ID" column is unique and it should not have duplicate values

Now, let us correct that and query the table by using:

SELECT * FROM <tablename>
Clear output for the applied Example 1 and Example 2 methods

It is observed that Row 1 is having 'Null' values in the place of 'Skillsets' and 'NumberOfPosts' column. The reason is as we have not specified values for those columns, it has taken default Null values. 

  • SQL Locks :

SQL Server is a relational database, data consistency is an important mechanism, and it can be done by means of SQL Locks. A lock is established in SQL Server when a transaction starts, and it is released when it is ended.. There are different types of locks are there.

  • Shared (S) Locks: When the object needs to be read, this type of lock will occur, but this is not harmful.
  • Exclusive (X) Locks: It prevents other transactions like inserting/updating/deleting etc., Hence no modifications can be done on a locked object.
  • Update (U) Locks: More or less similar to Exclusive lock but here the operation can be viewed as "read phase" and "write phase". Especially during the read phase, other transactions are prevented. 
  • Intent Locks: When SQL Server has the shared (S) lock or exclusive (X) lock on a row, then the intent lock is on the table.
  • Regular intent locks: Intent exclusive (IX) , Intent shared (IS), and Intent update (IU).
  • Conversion locks: Shared with intent exclusive (SIX), Shared with intent update (SIU), and Update with intent exclusive (UIX).

Lock hierarchy starts from Database, then table, then row.

The shared lock on a database level is very much important as it prevents dropping of the database or restoring a database backup over the database in use.

Lock occurrences when there is a "SELECT" statement is issued.

During DML statement execution i.e. either during insert/update/delete.

With our example, let us see the locking mechanisms. 

--Let us create an open transaction and analyze the locked resource.  BEGIN TRAN  Let us update the Skillsets column for ID = 1  UPDATE Authors SET Skillsets='Java,Android,PHP' where ID=1  select @@SPID
select * from sys.dm_tran_locks  WHERE request_session_id=<our session id. here it is 52>

 Let us insert some more records(nearly around 100 records) into the table and then using a transaction, let us update few columns as well as parallel apply the select query also

--Let us create an open transaction and analyze the locked resources.  BEGIN TRAN  --Let us update the Skillsets when ID < 20  UPDATE Authors SET Skillsets='Java,Android,R Programming' where ID < 20    --Let us update the Skillsets when ID >= 25  UPDATE Authors SET Skillsets='Android,IOS,R Programming' where ID >= 25    --Other DML statements like Update/Delete. This statement must be taking a long time  --(if there are huge updates are happening) as previous statement itself  --is either not committed or rolled back yet  SELECT * FROM Authors;  select @@SPID

Actually when the earlier command transaction are not yet complete(if there are huge records at least 100 records) and update is happening on each and every row and before completion of it, if we are proceeding for another set of commands like "select"

Then there are possibilities of the status will be "Awaiting" (Queries which are executing) and "Suspended" (Queries which are halt)

How to overcome the so far running process?

KILL <spid> -> Kill the session

(Or) Inside a transaction, after each query, apply

COMMIT -> TO COMMIT THE CHANGES  ROLLBACK -> TO ROLLBACK THE CHANGES

By doing this process, we are enforcing the operation either to get committed or rolled back(depends upon the requirements, it has to be carried out)

But unless we know that the entire process is required or not, we cannot either commit or rollback the transaction.

Alternative way :

By using NOLOCK with SELECT QUERY, we can overcome

SELECT * FROM Authors WITH (NOLOCK);

For SELECT statement status using the sp_who2 command. The query runs without waiting for the UPDATE transaction to be completed successfully and release the locking on the table,

SELECT * FROM Authors WITH (READUNCOMMITTED);  --This way also we can do

Conclusion :

SQL Locks are much important for any RDBMS. SQL Server handles them in the mentioned ways.


Next Article
SQL- Lock Table

P

priyarajtt
Improve
Article Tags :
  • SQL
  • SQL-Server
  • SQL-Query

Similar Reads

    PostgreSQL - Locks
    A lock in PostgreSQL is a mechanism to control access to database objects such as tables, rows, or entire database files. It prevents conflicts by ensuring each transaction can safely modify or access data without interference. This helps achieve data integrity in high-concurrency environments. In t
    4 min read
    PL/SQL Transactions
    PL/SQL transactions are vital components in database management, providing a means to maintain data integrity, consistency, and reliability within a relational database. A transaction in PL/SQL is defined as a series of SQL operations treated as a single unit of work. In this article, We will learn
    5 min read
    How to Use SELECT Without Locking a Table?
    Using the SELECT statement with an ongoing INSERT or UPDATE statement, put an exclusive lock on rows or possibly on the whole table until the operation's transaction is committed or rolled back. Suppose, you are working on a very big table with thousands of rows and the database table is not efficie
    4 min read
    PL/SQL Cursor Update
    PL/SQL stands for Procedural Language/Structured Query Language. It has block structure programming features. In Oracle PL/SQL, cursors play a vital role in managing and processing query results. Among the various types of cursors, updatable cursors stand out for their ability to fetch data and modi
    5 min read
    Predicate Locking
    A lock, in DBMS, is a variable that is associated with a data item. Locks in DBMS help synchronize access to the database items by concurrent transactions. Lock Based Protocol in DBMS is used to eliminate concurrency problems for simultaneous transactions, (this refers to a situation wherein one tra
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences