SQL Server - How to achieve READCOMMITED and NOLOCK at the same time?Shared and IX locks causing deadlock (Sql server)Optimizing real-time Database table in Microsoft SQL server 2008Does SQL Server place shared locks on scanned records when using REPEATABLE READIs there anyway to make this stored procedure thread safe?SQL Server - Logical Reads lowered, Execution time remained the sameUPDATE Blocking SELECT Of Unrelated RowsRead Committed Snapshot, stale data reads?Gap Locking in Read Committed isolation level in MysqlAn uncommitted transaction updates a column; how can a different transaction see the old column value?
Heat output from a 200W electric radiator?
Notice period 60 days but I need to join in 45 days
Do multi-engine jets need all engines with equal age to reduce asymmetry in thrust and fuel consumption arising out of deterioration?
Coupling two 15 Amp circuit breaker for 20 Amp
Is there a better way to use C# dictionaries than TryGetValue?
Can a network vulnerability be exploited locally?
Count the number of triangles
To what extent should we fear giving offense?
Fantasy Macro Economics: What would Merfolk trade for?
The meaning of asynchronous vs synchronous
Is it unusual for a math department not to have a mail/web server?
Why is the Grievance Studies affair considered to be research requiring IRB approval?
How to prevent a hosting company from accessing a VM's encryption keys?
Is there a word or phrase that means "use other people's wifi or Internet service without consent"?
Why did Lucius make a deal out of Buckbeak hurting Draco but not about Draco being turned into a ferret?
Are spot colors limited and why CMYK mix is not treated same as spot color mix?
Did anybody find out it was Anakin who blew up the command center?
How to say "I only speak one language which is English" in French?
If I said I had $100 when asked, but I actually had $200, would I be lying by omission?
Why does glibc's strlen need to be so complicated to run quickly?
Is this password scheme legit?
Normalized Malbolge to Malbolge translator
Should I use the words "pyromancy" and "necromancy" even if they don't mean what people think they do?
Why is there not a willingness from the world to step in between Pakistan and India?
SQL Server - How to achieve READCOMMITED and NOLOCK at the same time?
Shared and IX locks causing deadlock (Sql server)Optimizing real-time Database table in Microsoft SQL server 2008Does SQL Server place shared locks on scanned records when using REPEATABLE READIs there anyway to make this stored procedure thread safe?SQL Server - Logical Reads lowered, Execution time remained the sameUPDATE Blocking SELECT Of Unrelated RowsRead Committed Snapshot, stale data reads?Gap Locking in Read Committed isolation level in MysqlAn uncommitted transaction updates a column; how can a different transaction see the old column value?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
If I have a User table:
id | name | age
1 | Mateus | 27
The first transaction executes an update, and leaves the transaction open, without committing or rolling back:update User set name = 'John' where id = 1;
Meanwhile, the second transaction executes a select:select * from User where id = 1;
This command will wait until the first transaction releases the lock, either by commit or rollback, unless the second transaction uses a table hint with(nolock), like so:select * from User with(nolock) where id = 1;
That will return the record without locking the transaction, but it will return the uncommitted value John instead of the original Mateus.
From what I know, there are only two ways to return a locked record without locking the current transaction, one can use with(nolock) that will return the record but with the uncommitted value, and with(readpast) that will just not return the record.
Is there a way I can return the record, without locking the table, and returning its "old" values?
sql-server isolation-level
add a comment |
If I have a User table:
id | name | age
1 | Mateus | 27
The first transaction executes an update, and leaves the transaction open, without committing or rolling back:update User set name = 'John' where id = 1;
Meanwhile, the second transaction executes a select:select * from User where id = 1;
This command will wait until the first transaction releases the lock, either by commit or rollback, unless the second transaction uses a table hint with(nolock), like so:select * from User with(nolock) where id = 1;
That will return the record without locking the transaction, but it will return the uncommitted value John instead of the original Mateus.
From what I know, there are only two ways to return a locked record without locking the current transaction, one can use with(nolock) that will return the record but with the uncommitted value, and with(readpast) that will just not return the record.
Is there a way I can return the record, without locking the table, and returning its "old" values?
sql-server isolation-level
add a comment |
If I have a User table:
id | name | age
1 | Mateus | 27
The first transaction executes an update, and leaves the transaction open, without committing or rolling back:update User set name = 'John' where id = 1;
Meanwhile, the second transaction executes a select:select * from User where id = 1;
This command will wait until the first transaction releases the lock, either by commit or rollback, unless the second transaction uses a table hint with(nolock), like so:select * from User with(nolock) where id = 1;
That will return the record without locking the transaction, but it will return the uncommitted value John instead of the original Mateus.
From what I know, there are only two ways to return a locked record without locking the current transaction, one can use with(nolock) that will return the record but with the uncommitted value, and with(readpast) that will just not return the record.
Is there a way I can return the record, without locking the table, and returning its "old" values?
sql-server isolation-level
If I have a User table:
id | name | age
1 | Mateus | 27
The first transaction executes an update, and leaves the transaction open, without committing or rolling back:update User set name = 'John' where id = 1;
Meanwhile, the second transaction executes a select:select * from User where id = 1;
This command will wait until the first transaction releases the lock, either by commit or rollback, unless the second transaction uses a table hint with(nolock), like so:select * from User with(nolock) where id = 1;
That will return the record without locking the transaction, but it will return the uncommitted value John instead of the original Mateus.
From what I know, there are only two ways to return a locked record without locking the current transaction, one can use with(nolock) that will return the record but with the uncommitted value, and with(readpast) that will just not return the record.
Is there a way I can return the record, without locking the table, and returning its "old" values?
sql-server isolation-level
sql-server isolation-level
edited 8 hours ago
Paul White♦
58.6k16 gold badges307 silver badges481 bronze badges
58.6k16 gold badges307 silver badges481 bronze badges
asked 8 hours ago
Mateus ViccariMateus Viccari
2492 silver badges13 bronze badges
2492 silver badges13 bronze badges
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
What you're looking for is an optimistic isolation level, like Snapshot Isolation, or Read Committed Snapshot Isolation.
Code example:
USE Crap;
CREATE TABLE dbo.users (id INT, username NVARCHAR(40));
INSERT dbo.users ( id, username )
VALUES ( 1, N'Jimbo' )
/*To turn on Snapshot*/
ALTER DATABASE Crap SET ALLOW_SNAPSHOT_ISOLATION ON;
/*To turn on RCSI*/
ALTER DATABASE Crap SET READ_COMMITTED_SNAPSHOT ON;
UPDATE dbo.users
SET username = 'Dimbo'
WHERE id = 1;
/*Snapshot needs this, RCSI doesn't*/
SET TRANSACTION ISOLATION LEVEL SNAPSHOT
SELECT *
FROM dbo.users AS u
WHERE u.id = 1;
Things to be aware of:
- Row versioning uses space in tempdb (except SQL Server 2019 when Accelerated Database Recovery is configured - versions are stored with the user database, either in-row or in the Persisted Version Store)
- There can be race conditions where you depend on locking for queueing
Differences
One important difference between Snapshot Isolation and RCSI is inside transactions:
Under Snapshot Isolation, BEGIN TRAN marks the point when all queries inside the transaction will read from the version store.
Under RCSI, each statement after BEGIN TRAN will read the version store as of when the statement executes.
Another difference is that Snapshot Isolation can be applied to modification queries, where RCSI can't. More precisely, SI detects write conflicts and rolls one of the conflicting transactions back automatically. Updates under RCSI do not use row versions when locating data to update, but this only applies to the target table. Other tables in the same delete or update statement, including additional references to the target table, will continue to use row versions.
add a comment |
Your Answer
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "182"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f246453%2fsql-server-how-to-achieve-readcommited-and-nolock-at-the-same-time%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
What you're looking for is an optimistic isolation level, like Snapshot Isolation, or Read Committed Snapshot Isolation.
Code example:
USE Crap;
CREATE TABLE dbo.users (id INT, username NVARCHAR(40));
INSERT dbo.users ( id, username )
VALUES ( 1, N'Jimbo' )
/*To turn on Snapshot*/
ALTER DATABASE Crap SET ALLOW_SNAPSHOT_ISOLATION ON;
/*To turn on RCSI*/
ALTER DATABASE Crap SET READ_COMMITTED_SNAPSHOT ON;
UPDATE dbo.users
SET username = 'Dimbo'
WHERE id = 1;
/*Snapshot needs this, RCSI doesn't*/
SET TRANSACTION ISOLATION LEVEL SNAPSHOT
SELECT *
FROM dbo.users AS u
WHERE u.id = 1;
Things to be aware of:
- Row versioning uses space in tempdb (except SQL Server 2019 when Accelerated Database Recovery is configured - versions are stored with the user database, either in-row or in the Persisted Version Store)
- There can be race conditions where you depend on locking for queueing
Differences
One important difference between Snapshot Isolation and RCSI is inside transactions:
Under Snapshot Isolation, BEGIN TRAN marks the point when all queries inside the transaction will read from the version store.
Under RCSI, each statement after BEGIN TRAN will read the version store as of when the statement executes.
Another difference is that Snapshot Isolation can be applied to modification queries, where RCSI can't. More precisely, SI detects write conflicts and rolls one of the conflicting transactions back automatically. Updates under RCSI do not use row versions when locating data to update, but this only applies to the target table. Other tables in the same delete or update statement, including additional references to the target table, will continue to use row versions.
add a comment |
What you're looking for is an optimistic isolation level, like Snapshot Isolation, or Read Committed Snapshot Isolation.
Code example:
USE Crap;
CREATE TABLE dbo.users (id INT, username NVARCHAR(40));
INSERT dbo.users ( id, username )
VALUES ( 1, N'Jimbo' )
/*To turn on Snapshot*/
ALTER DATABASE Crap SET ALLOW_SNAPSHOT_ISOLATION ON;
/*To turn on RCSI*/
ALTER DATABASE Crap SET READ_COMMITTED_SNAPSHOT ON;
UPDATE dbo.users
SET username = 'Dimbo'
WHERE id = 1;
/*Snapshot needs this, RCSI doesn't*/
SET TRANSACTION ISOLATION LEVEL SNAPSHOT
SELECT *
FROM dbo.users AS u
WHERE u.id = 1;
Things to be aware of:
- Row versioning uses space in tempdb (except SQL Server 2019 when Accelerated Database Recovery is configured - versions are stored with the user database, either in-row or in the Persisted Version Store)
- There can be race conditions where you depend on locking for queueing
Differences
One important difference between Snapshot Isolation and RCSI is inside transactions:
Under Snapshot Isolation, BEGIN TRAN marks the point when all queries inside the transaction will read from the version store.
Under RCSI, each statement after BEGIN TRAN will read the version store as of when the statement executes.
Another difference is that Snapshot Isolation can be applied to modification queries, where RCSI can't. More precisely, SI detects write conflicts and rolls one of the conflicting transactions back automatically. Updates under RCSI do not use row versions when locating data to update, but this only applies to the target table. Other tables in the same delete or update statement, including additional references to the target table, will continue to use row versions.
add a comment |
What you're looking for is an optimistic isolation level, like Snapshot Isolation, or Read Committed Snapshot Isolation.
Code example:
USE Crap;
CREATE TABLE dbo.users (id INT, username NVARCHAR(40));
INSERT dbo.users ( id, username )
VALUES ( 1, N'Jimbo' )
/*To turn on Snapshot*/
ALTER DATABASE Crap SET ALLOW_SNAPSHOT_ISOLATION ON;
/*To turn on RCSI*/
ALTER DATABASE Crap SET READ_COMMITTED_SNAPSHOT ON;
UPDATE dbo.users
SET username = 'Dimbo'
WHERE id = 1;
/*Snapshot needs this, RCSI doesn't*/
SET TRANSACTION ISOLATION LEVEL SNAPSHOT
SELECT *
FROM dbo.users AS u
WHERE u.id = 1;
Things to be aware of:
- Row versioning uses space in tempdb (except SQL Server 2019 when Accelerated Database Recovery is configured - versions are stored with the user database, either in-row or in the Persisted Version Store)
- There can be race conditions where you depend on locking for queueing
Differences
One important difference between Snapshot Isolation and RCSI is inside transactions:
Under Snapshot Isolation, BEGIN TRAN marks the point when all queries inside the transaction will read from the version store.
Under RCSI, each statement after BEGIN TRAN will read the version store as of when the statement executes.
Another difference is that Snapshot Isolation can be applied to modification queries, where RCSI can't. More precisely, SI detects write conflicts and rolls one of the conflicting transactions back automatically. Updates under RCSI do not use row versions when locating data to update, but this only applies to the target table. Other tables in the same delete or update statement, including additional references to the target table, will continue to use row versions.
What you're looking for is an optimistic isolation level, like Snapshot Isolation, or Read Committed Snapshot Isolation.
Code example:
USE Crap;
CREATE TABLE dbo.users (id INT, username NVARCHAR(40));
INSERT dbo.users ( id, username )
VALUES ( 1, N'Jimbo' )
/*To turn on Snapshot*/
ALTER DATABASE Crap SET ALLOW_SNAPSHOT_ISOLATION ON;
/*To turn on RCSI*/
ALTER DATABASE Crap SET READ_COMMITTED_SNAPSHOT ON;
UPDATE dbo.users
SET username = 'Dimbo'
WHERE id = 1;
/*Snapshot needs this, RCSI doesn't*/
SET TRANSACTION ISOLATION LEVEL SNAPSHOT
SELECT *
FROM dbo.users AS u
WHERE u.id = 1;
Things to be aware of:
- Row versioning uses space in tempdb (except SQL Server 2019 when Accelerated Database Recovery is configured - versions are stored with the user database, either in-row or in the Persisted Version Store)
- There can be race conditions where you depend on locking for queueing
Differences
One important difference between Snapshot Isolation and RCSI is inside transactions:
Under Snapshot Isolation, BEGIN TRAN marks the point when all queries inside the transaction will read from the version store.
Under RCSI, each statement after BEGIN TRAN will read the version store as of when the statement executes.
Another difference is that Snapshot Isolation can be applied to modification queries, where RCSI can't. More precisely, SI detects write conflicts and rolls one of the conflicting transactions back automatically. Updates under RCSI do not use row versions when locating data to update, but this only applies to the target table. Other tables in the same delete or update statement, including additional references to the target table, will continue to use row versions.
edited 8 hours ago
Paul White♦
58.6k16 gold badges307 silver badges481 bronze badges
58.6k16 gold badges307 silver badges481 bronze badges
answered 8 hours ago
Erik DarlingErik Darling
26.6k13 gold badges82 silver badges133 bronze badges
26.6k13 gold badges82 silver badges133 bronze badges
add a comment |
add a comment |
Thanks for contributing an answer to Database Administrators Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f246453%2fsql-server-how-to-achieve-readcommited-and-nolock-at-the-same-time%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown