debugsqlMinor
How to make sure that simultaneous INSERT and SELECT on one table won't make a deadlock?
Viewed 0 times
insertwondeadlockmakesuresimultaneousonethathowand
Problem
I have the following table in my SQL Server 2008 database:
One process inserts data into this table, another process reads all data from this table. Both processes work simultaneously.
I see that second query does a full table scan, but I need to get all data from this table for further processing(it won't be a very big table, because it will be cleaned periodically. it will contain a 1K-2K rows).
Are there any way to make sure that deadlocks will never happen for this two queries?
CREATE TABLE [dbo].[SomeTable]
(
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[Column1] [varchar](30) NOT NULL,
[Column2] [varchar](30) NOT NULL,
[Column3] [varchar](50) NOT NULL,
CONSTRAINT [PK_SomeTable] PRIMARY KEY CLUSTERED
(
[Id] ASC
)
)One process inserts data into this table, another process reads all data from this table. Both processes work simultaneously.
one process:
INSERT INTO dbo.SomeTable VALUES ('col1', 'col2', 'col3')
another process:
SELECT Id, Column1, Column2, Column3 FROM dbo.SomeTableI see that second query does a full table scan, but I need to get all data from this table for further processing(it won't be a very big table, because it will be cleaned periodically. it will contain a 1K-2K rows).
Are there any way to make sure that deadlocks will never happen for this two queries?
Solution
Deadlocks will always happen at some point under the default locking strategy. However, it is unlikely in your given scenario because of the straight table scan.
However, it's more likely if you have several concurrent INSERTs and SELECTs.
Using NOLOCK means dirty reads and isn't best practice. Everyone seems to suggest them though...
The alternative is to use snapshot isolation modes: the SELECT will read the last committed data, rather than being blocked by the INSERT.
However, it's more likely if you have several concurrent INSERTs and SELECTs.
Using NOLOCK means dirty reads and isn't best practice. Everyone seems to suggest them though...
The alternative is to use snapshot isolation modes: the SELECT will read the last committed data, rather than being blocked by the INSERT.
Context
StackExchange Database Administrators Q#14403, answer score: 8
Revisions (0)
No revisions yet.