Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lock on table while inserting data in SQL Server database

I have question on lock on table in SQL Server while inserting data using multiple processes at a single time into same table.

Here are my questions on this,

  1. Is it default behavior of SQL server to lock table while doing insert?
  2. if yes to Q1, then how we can implicitly mention while inserting data.
  3. If I have 4 tables and one table has foreign keys from rest of the 3 tables, on this scenario do I need to use the table lock explicitly or without that I can insert records into those tables?

Please help me to understand the same.

like image 766
user2986108 Avatar asked Dec 05 '22 06:12

user2986108


1 Answers

Is it default behavior of SQL server to lock table while doing insert?

No. SQL Server by default locks by row - so new rows being inserted are locked - but not the whole table.

This will change if you insert more than 5000 rows in a single transaction. In that case, keeping that many individual locks just becomes too much and SQL Server will do a lock escalation and lock the entire table instead.

like image 126
marc_s Avatar answered Dec 28 '22 23:12

marc_s