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;








2















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?










share|improve this question
































    2















    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?










    share|improve this question




























      2












      2








      2








      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?










      share|improve this question
















      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






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      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























          1 Answer
          1






          active

          oldest

          votes


















          8















          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.






          share|improve this answer





























            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
            );



            );













            draft saved

            draft discarded


















            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









            8















            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.






            share|improve this answer































              8















              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.






              share|improve this answer





























                8














                8










                8









                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.






                share|improve this answer















                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.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                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






























                    draft saved

                    draft discarded
















































                    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.




                    draft saved


                    draft discarded














                    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





















































                    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







                    Popular posts from this blog

                    Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                    Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                    François Viète Contents Biography Work and thought Bibliography See also Notes Further reading External links Navigation menup. 21Google Bookspp. 75–77Google BooksDe thou (from University of Saint Andrews)ArchivedGoogle BooksGoogle BooksGoogle BooksGoogle booksGoogle Bookscc-parthenay.frL'histoire universelle (fr)Universal History (en)ArchivedAdsabs.harvard.eduPagesperso-orange.frArchive.orgChikara Sasaki. Descartes' mathematical thought p.259Google BooksGoogle BooksGoogle Bookspp. 152 and onwardGoogle BooksGoogle BooksScribd.comGoogle Books1257-7979Google BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGallica.bnf.frGoogle BooksGoogle Books"François Viète"Francois Viète: Father of Modern Algebraic NotationThe Lawyer and the GamblerAbout TarporleySite de Jean-Paul GuichardL'algèbre nouvelle"About the Harmonicon"cb120511976(data)1188044800000 0001 0913 5903n82164680ola2013766880073431702w6vt1sb70287374827140948071409480