February 14, 2023 at 7:48 pm
Just to prove Grant's statement a little more, here's a quick demo.
So you can see that the first
SELECT
, which wants rows on or after the current date, is not blocked, due to there being anINDEX
onSomeDate
(whichINCLUDE
s all the columns the query needs), so the data engine is able to get all the rows without accessing the blocked data.For the second
INSERT
, however, we're now inserting a row after the current date, and when I run theSELECT
again, it now can't complete, due to theINSERT
blocking theSELECT
. As soon as thatINSERT
isCOMMIT
ed, however, theSELECT
is able to be completed.An
INSERT
can block aSELECT
, but if they do depends on both what data is beingINSERT
ed, what data is beingSELECT
ed, and whatINDEX
es the data engine has access to. There's not as simple as a "yes it (always) will" or "No it won't (ever) be".SQL from the animated gif:
--First Connection's batches
CREATE TABLE dbo.SomeTable (ID int IDENTITY(1,1) CONSTRAINT PK_SomeTable PRIMARY KEY,
SomeString varchar(10),
SomeDate date);
GO
INSERT INTO dbo.SomeTable (SomeString, SomeDate)
VALUES('abcd',GETDATE()),
('efgh',DATEADD(DAY,-2,GETDATE()));
GO
--Use a transaction to help simulate "simultaneous" statements
BEGIN TRANSACTION;
INSERT INTO dbo.SomeTable (SomeString, SomeDate)
VALUES('ijkl',DATEADD(DAY,-1,GETDATE()));
COMMIT;
GO
--Use a transaction to help simulate "simultaneous" statements
BEGIN TRANSACTION;
INSERT INTO dbo.SomeTable (SomeString, SomeDate)
VALUES('mnop',DATEADD(DAY,+1,GETDATE()));
COMMIT;
GO
DROP TABLE dbo.SomeTable;
GO
---------
--Second connection's batch
SELECT *
FROM dbo.SomeTable
WHERE SomeDate >= CONVERT(date,GETDATE());
This is really nice. Very cool stuff. Thanks a lot for taking time Thom.
Viewing post 16 (of 15 total)
You must be logged in to reply to this topic. Login to reply