SlideShare ist ein Scribd-Unternehmen logo
1 von 19
Downloaden Sie, um offline zu lesen
READPAST & Furious: Locking Blocking and Isolation · Mark
                              Broadbent · sqlcloud.co.uk




READPAST & Furious:
Transactions, Locking and Isolation

Mark Broadbent
SQLCloud
Agenda
TRANSACTIONS
 • Structure, Scope and Management


LOCKING
 • Compatibility, Multi Granularity and Escalation
 • NOLOCK, READPAST and UPDLOCK



ISOLATION
 • Snapshot Isolation and Read Committed Snapshot
 • Rolling Database Snapshots




                READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk
A bit more about little old me!
More than 21 years in IT and more than 15 years using SQL Server.
Worked at many large global corporations and SMEs such as
Microsoft, Nokia, Hewlett Packard and Encyclopaedia Britannica.
Blog: tenbulls.co.uk
Cambridgeshire SQL UG Leader sqlcambs.org.uk                 JOIN
Presented at SQLBits 7, 8 (and now 9), SQL Rally Orlando     US!!!
Awarded Microsoft Community Contributor Award 2011
MCITP DB Development SQL 2008
MCITP DBA SQL 2008/ 2005 and MCDBA SQL 2000
Microsoft Certified Application Developer (C# .net)
Microsoft Certified Systems Engineer + Internet
Participate on #sqlhelp, MSDN Forums
LinkedIn SQL Server Scripting Group http://linkd.in/pfBkRI


                READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk
Transactions basically…
Provide Atomicity (all or nothing) …or does it!

Can be defined as Implicit (evil), Explicit (declarative) or
Auto-Commit (default)

Effect duration of locks

Transactions can have batch scope (MARS), be distributed
and even be bound across sessions or servers.

Can be really confusing!

               READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk
Transactions are easy-peasy…
BEGIN TRAN transaction_1 WITH MARK ‘restorepoint’
    BEGIN TRAN
       --do something      Transaction Name
                                                  Transaction Mark
    COMMIT TRAN
    SAVE TRAN savepoint                Savepoint
    BEGIN TRAN transaction_3
       BEGIN TRAN
              --do something else      Nested Transaction
       COMMIT
       IF {something_wrong} THEN ROLLBACK TRAN savepoint
    COMMIT
COMMIT

                READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk
READPAST & Furious: Locking Blocking and Isolation · Mark
                  Broadbent · sqlcloud.co.uk




Transactions Demo
Locks, the Lock Manager and Locking
Locks are memory structures only and can be converted or escalated
…have a compatibility or incompatibility with other locks
…are taken depending upon the Isolation level
…can cause blocking or deadlocks
…will wait if they are incompatible

Lock Manager compares locks ONLY on same resource
… and that’s why so intent locks are needed (granular)

Lock escalation will occur for performance and memory savings
…and escalate straight to Table by default (not partitions)!!!
…but you can turn off ALL escalation (TF1211), due to # locks
(TF1224) or artificially by taking IS on table or by ALTER statement
<table> SET (LOCK_ESCALATION = auto|table|disable)


                 READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk
READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk
NL   SCH-S SCH-M    S     U      X     IS    IU       IX    SIU       SIX   UIX   BU RS-S RS-U RI-N RI-S RI-U RI-X RX-S RX-U RX-X
 NL
SCH-S
SCH-M
  S
  U
  X
  IS
 IU
  IX
                                                                                                             SQL Server
 SIU
 SIX                                                                                                   Lock Compatibility Chart
 UIX
 BU
RS-S
RS-U
RI-N
RI-S                                                                No Conflict
RI-U                                                                Conflict
RI-X
RX-S                                                                Illegal
RX-U
RX-X

 NL          No Lock                         IX           Intent Exclusive                RI-S     Insert Range-Shared
 SCH-S       Schema Stability Lock           SIU          Share with Intent Update        RI-U     Insert Range-Update
 SCH-M       Schema Modification Lock        SIX          Share with Intent Exclusive     RI-X     Insert Range-Exclusive
 S           Shared                          UIX          Update with Intent Exclusive    RX-S     Exclusive Range-Shared
 U           Update                          BU           Bulk Update                     RX-U     Exclusive Range-Update
 X           Exclusive                       RS-S         Shared Range-Shared             RX-X     Exclusive Range-Exclusive
 IS          Intent Shared                   RS-U         Shared Range-Update
 IU          Intent Update                   RI-N         Insert Range-Null




                                        READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk
Lock must wait!
Intent Locks
                                                                                                         Table
                                                           IX               X
                                                                                    orders
     Data Page
                            IX




     Free Space                                               X
                                                                                         Row




                  READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk
NOLOCK (a Wolf in Sheep’s clothing?)
Should use READUNCOMMITTED hint instead.

Doesn’t acquire Shared locks so is able to perform DIRTY
READS, NON-REPEATABLE READS, PHANTOMS
…and I bet you didn’t know it can also return DUPLICATE
READS!

It DOES NOT give “Oracle style” concurrency

When can this ever be acceptable?


             READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk
Well since you mention it…
  Scalable Shared Database
                                                      “There is
                SQL Server                            NOLOCK”
                Instance B
                Instance C                                                                   Database Snapshot


                  SQL Server
                  Instance A

                                                                                                      Filegroup1

                                                                                                       Filegroup2

                                                                                                        Filegroup3
                                                Readonly
                                                Database
                                                                                           Readonly Filegroup/s

               “When should you use NOLOCK?“ http://bit.ly/rdGzow

                     READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk
READPAST & (your boss) may be Furious!
 Is an alternative to NOLOCK/ READUNCOMMITTED.
 Skip over resources holding incompatible (to S) locks.
 Does not therefore cause dirty or duplicate reads. (yay!)

 …But It still DOES NOT give “Oracle style” concurrency
 …and can return INCOMPLETE DATA SETS!

 When can this ever be acceptable?




             READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk
Using READPAST and Table Queues
                                                   --Get the first record
     orders                                        --possible and update
                                                   UPDATE u SET …
 X                              X                      FROM       2
 U
                                                       (
                                                       SELECT TOP(1) *
                                                          FROM orders
                                U                         WITH (READPAST
                                                            ,UPDLOCK)
                                                          WHERE …       1
                                                       ) AS U




          READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk
READPAST & Furious: Locking Blocking and Isolation · Mark
               Broadbent · sqlcloud.co.uk




Locking Demo
Read Committed Snapshot vs Snapshot Isolation
 SI provides isolation at the transaction level, RCS provides
 isolation at the statement level

 SI must be explicitly SET in each connection, for RCS it
 becomes the new default

 Enabling SI level requires no active transactions in order to
 transition. Enabling RCS requires Exclusive Transaction
 Workspace lock (and therefore no other connections to DB).

 RCS not allowed on master, tempdb and msdb, SI is allowed

 SI implements automatic update conflict detection

              READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk
Database Snapshots                                                                                        5
                                                                                                    COMMIT
1
    BEGIN TRAN
       UPDATE
           orders                                                                                         4
           SET …
                                                                          SELECT *
           WHERE …          Buffer Cache
                                                                             FROM orders o
                                                                             …
     2
                                                                          3
         CHECKPOINT

                                                                                            Transaction Log
                                  Data FIle




                  READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk
READPAST & Furious: Locking Blocking and Isolation · Mark
                 Broadbent · sqlcloud.co.uk




Snapshots Demo
References and Thanks
Professional SQL Server 2008 Internals and Troubleshooting – Locking
and Latches Chapter - James Rowland Jones

Kalen Delaney, SQLPASS Summit 2011 DBA301P - Locking and Blocking
and Row Versions, Oh My! – DVD

Jose Barreto's Blog
http://blogs.technet.com/b/josebda/archive/2009/03/19/sql-server-2008-
locking.aspx

A special thanks to :-
Paul White @sql_kiwi http://sqlblog.com/blogs/paul_white

Benjamin Neverez @BenjaminNeverez http://www.benjaminnevarez.com/


                 READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk

Weitere ähnliche Inhalte

Andere mochten auch

Enter the Dragon - SQL 2014 on Server Core PASS Summit 2014 Edition
Enter the Dragon -  SQL 2014 on Server Core PASS Summit 2014 EditionEnter the Dragon -  SQL 2014 on Server Core PASS Summit 2014 Edition
Enter the Dragon - SQL 2014 on Server Core PASS Summit 2014 Edition
Mark Broadbent
 
11. transaction sql
11. transaction sql11. transaction sql
11. transaction sql
Umang Gupta
 

Andere mochten auch (7)

Enter the Dragon - SQL 2014 on Server Core PASS Summit 2014 Edition
Enter the Dragon -  SQL 2014 on Server Core PASS Summit 2014 EditionEnter the Dragon -  SQL 2014 on Server Core PASS Summit 2014 Edition
Enter the Dragon - SQL 2014 on Server Core PASS Summit 2014 Edition
 
Schizophrenic High Availability with SQL and Windows 2016
Schizophrenic High Availability with SQL and Windows 2016Schizophrenic High Availability with SQL and Windows 2016
Schizophrenic High Availability with SQL and Windows 2016
 
Coding for concurrency
Coding for concurrencyCoding for concurrency
Coding for concurrency
 
lock, block & two smoking barrels
lock, block & two smoking barrelslock, block & two smoking barrels
lock, block & two smoking barrels
 
SharePoint is from Mars, SQL Server is from Venus (SQL Server for SharePoint ...
SharePoint is from Mars, SQL Server is from Venus (SQL Server for SharePoint ...SharePoint is from Mars, SQL Server is from Venus (SQL Server for SharePoint ...
SharePoint is from Mars, SQL Server is from Venus (SQL Server for SharePoint ...
 
Being Buck Woody - PASS Summit 2014 Edition
Being Buck Woody - PASS Summit 2014 EditionBeing Buck Woody - PASS Summit 2014 Edition
Being Buck Woody - PASS Summit 2014 Edition
 
11. transaction sql
11. transaction sql11. transaction sql
11. transaction sql
 

Ähnlich wie READPAST & Furious: Locking

Understanding PostgreSQL LW Locks
Understanding PostgreSQL LW LocksUnderstanding PostgreSQL LW Locks
Understanding PostgreSQL LW Locks
Jignesh Shah
 
High Performance Security and Virtualization for Oracle Database and Cloud-En...
High Performance Security and Virtualization for Oracle Database and Cloud-En...High Performance Security and Virtualization for Oracle Database and Cloud-En...
High Performance Security and Virtualization for Oracle Database and Cloud-En...
Ramesh Nagappan
 
ZFS for Databases
ZFS for DatabasesZFS for Databases
ZFS for Databases
ahl0003
 

Ähnlich wie READPAST & Furious: Locking (20)

Open stack@ebay
Open stack@ebayOpen stack@ebay
Open stack@ebay
 
M|18 How Facebook Migrated to MyRocks
M|18 How Facebook Migrated to MyRocksM|18 How Facebook Migrated to MyRocks
M|18 How Facebook Migrated to MyRocks
 
Welcome to the nightmare of locking, blocking and isolation levels!
Welcome to the nightmare of locking, blocking and isolation levels!Welcome to the nightmare of locking, blocking and isolation levels!
Welcome to the nightmare of locking, blocking and isolation levels!
 
Docker Container Security - A Network View
Docker Container Security - A Network ViewDocker Container Security - A Network View
Docker Container Security - A Network View
 
SQL? NoSQL? NewSQL?!? What's a Java developer to do? - PhillyETE 2012
SQL? NoSQL? NewSQL?!? What's a Java developer to do? - PhillyETE 2012SQL? NoSQL? NewSQL?!? What's a Java developer to do? - PhillyETE 2012
SQL? NoSQL? NewSQL?!? What's a Java developer to do? - PhillyETE 2012
 
Understanding PostgreSQL LW Locks
Understanding PostgreSQL LW LocksUnderstanding PostgreSQL LW Locks
Understanding PostgreSQL LW Locks
 
What's new in Jewel and Beyond
What's new in Jewel and BeyondWhat's new in Jewel and Beyond
What's new in Jewel and Beyond
 
The nightmare of locking, blocking and isolation levels
The nightmare of locking, blocking and isolation levelsThe nightmare of locking, blocking and isolation levels
The nightmare of locking, blocking and isolation levels
 
High Performance Security and Virtualization for Oracle Database and Cloud-En...
High Performance Security and Virtualization for Oracle Database and Cloud-En...High Performance Security and Virtualization for Oracle Database and Cloud-En...
High Performance Security and Virtualization for Oracle Database and Cloud-En...
 
1.8 Data Protection.pdf
1.8 Data Protection.pdf1.8 Data Protection.pdf
1.8 Data Protection.pdf
 
BlueStore: a new, faster storage backend for Ceph
BlueStore: a new, faster storage backend for CephBlueStore: a new, faster storage backend for Ceph
BlueStore: a new, faster storage backend for Ceph
 
Spark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin OderskySpark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin Odersky
 
RocksDB meetup
RocksDB meetupRocksDB meetup
RocksDB meetup
 
ZFS for Databases
ZFS for DatabasesZFS for Databases
ZFS for Databases
 
Deploying OpenStack with Ansible
Deploying OpenStack with AnsibleDeploying OpenStack with Ansible
Deploying OpenStack with Ansible
 
Cassandra for Sysadmins
Cassandra for SysadminsCassandra for Sysadmins
Cassandra for Sysadmins
 
20171101 taco scargo luminous is out, what's in it for you
20171101 taco scargo   luminous is out, what's in it for you20171101 taco scargo   luminous is out, what's in it for you
20171101 taco scargo luminous is out, what's in it for you
 
Meetup - YugabyteDB - Introduction and key features
Meetup - YugabyteDB - Introduction and key featuresMeetup - YugabyteDB - Introduction and key features
Meetup - YugabyteDB - Introduction and key features
 
What's new in Luminous and Beyond
What's new in Luminous and BeyondWhat's new in Luminous and Beyond
What's new in Luminous and Beyond
 
DRP for Big Data - Stream Processing Architectures
DRP for Big Data - Stream Processing ArchitecturesDRP for Big Data - Stream Processing Architectures
DRP for Big Data - Stream Processing Architectures
 

Mehr von Mark Broadbent

SQL Server Clustering for Dummies
SQL Server Clustering for DummiesSQL Server Clustering for Dummies
SQL Server Clustering for Dummies
Mark Broadbent
 
Orders of-magnitude-scale-out-your-sql-server-data-slideshare
Orders of-magnitude-scale-out-your-sql-server-data-slideshareOrders of-magnitude-scale-out-your-sql-server-data-slideshare
Orders of-magnitude-scale-out-your-sql-server-data-slideshare
Mark Broadbent
 

Mehr von Mark Broadbent (9)

Persistence Is Futile - Implementing Delayed Durability
Persistence Is Futile - Implementing Delayed DurabilityPersistence Is Futile - Implementing Delayed Durability
Persistence Is Futile - Implementing Delayed Durability
 
Enter The Dragon - SQL 2014 on Server Core - SQLSaturday #341 Porto Edition
Enter The Dragon - SQL 2014 on Server Core - SQLSaturday #341 Porto EditionEnter The Dragon - SQL 2014 on Server Core - SQLSaturday #341 Porto Edition
Enter The Dragon - SQL 2014 on Server Core - SQLSaturday #341 Porto Edition
 
Ye Olde Cluster Curiosity Shoppe
Ye Olde Cluster Curiosity ShoppeYe Olde Cluster Curiosity Shoppe
Ye Olde Cluster Curiosity Shoppe
 
SQL Server AlwaysOn for Dummies SQLSaturday #202 Edition
SQL Server AlwaysOn for Dummies SQLSaturday #202 EditionSQL Server AlwaysOn for Dummies SQLSaturday #202 Edition
SQL Server AlwaysOn for Dummies SQLSaturday #202 Edition
 
Moves Like Jagger - Upgrading to SQL Server 2012 (SQLBits XI Edition)
Moves Like Jagger - Upgrading to SQL Server 2012 (SQLBits XI Edition)Moves Like Jagger - Upgrading to SQL Server 2012 (SQLBits XI Edition)
Moves Like Jagger - Upgrading to SQL Server 2012 (SQLBits XI Edition)
 
PASS 2012 "Moves Like Jagger" - Upgrading to SQL Server 2012
PASS 2012 "Moves Like Jagger" - Upgrading to SQL Server 2012PASS 2012 "Moves Like Jagger" - Upgrading to SQL Server 2012
PASS 2012 "Moves Like Jagger" - Upgrading to SQL Server 2012
 
SQL Server Clustering for Dummies
SQL Server Clustering for DummiesSQL Server Clustering for Dummies
SQL Server Clustering for Dummies
 
Orders of-magnitude-scale-out-your-sql-server-data-slideshare
Orders of-magnitude-scale-out-your-sql-server-data-slideshareOrders of-magnitude-scale-out-your-sql-server-data-slideshare
Orders of-magnitude-scale-out-your-sql-server-data-slideshare
 
Thinking outside the box, learning a little about a lot
Thinking outside the box, learning a little about a lotThinking outside the box, learning a little about a lot
Thinking outside the box, learning a little about a lot
 

Kürzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 

READPAST & Furious: Locking

  • 1. READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk READPAST & Furious: Transactions, Locking and Isolation Mark Broadbent SQLCloud
  • 2. Agenda TRANSACTIONS • Structure, Scope and Management LOCKING • Compatibility, Multi Granularity and Escalation • NOLOCK, READPAST and UPDLOCK ISOLATION • Snapshot Isolation and Read Committed Snapshot • Rolling Database Snapshots READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk
  • 3. A bit more about little old me! More than 21 years in IT and more than 15 years using SQL Server. Worked at many large global corporations and SMEs such as Microsoft, Nokia, Hewlett Packard and Encyclopaedia Britannica. Blog: tenbulls.co.uk Cambridgeshire SQL UG Leader sqlcambs.org.uk JOIN Presented at SQLBits 7, 8 (and now 9), SQL Rally Orlando US!!! Awarded Microsoft Community Contributor Award 2011 MCITP DB Development SQL 2008 MCITP DBA SQL 2008/ 2005 and MCDBA SQL 2000 Microsoft Certified Application Developer (C# .net) Microsoft Certified Systems Engineer + Internet Participate on #sqlhelp, MSDN Forums LinkedIn SQL Server Scripting Group http://linkd.in/pfBkRI READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk
  • 4. Transactions basically… Provide Atomicity (all or nothing) …or does it! Can be defined as Implicit (evil), Explicit (declarative) or Auto-Commit (default) Effect duration of locks Transactions can have batch scope (MARS), be distributed and even be bound across sessions or servers. Can be really confusing! READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk
  • 5. Transactions are easy-peasy… BEGIN TRAN transaction_1 WITH MARK ‘restorepoint’ BEGIN TRAN --do something Transaction Name Transaction Mark COMMIT TRAN SAVE TRAN savepoint Savepoint BEGIN TRAN transaction_3 BEGIN TRAN --do something else Nested Transaction COMMIT IF {something_wrong} THEN ROLLBACK TRAN savepoint COMMIT COMMIT READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk
  • 6. READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk Transactions Demo
  • 7. Locks, the Lock Manager and Locking Locks are memory structures only and can be converted or escalated …have a compatibility or incompatibility with other locks …are taken depending upon the Isolation level …can cause blocking or deadlocks …will wait if they are incompatible Lock Manager compares locks ONLY on same resource … and that’s why so intent locks are needed (granular) Lock escalation will occur for performance and memory savings …and escalate straight to Table by default (not partitions)!!! …but you can turn off ALL escalation (TF1211), due to # locks (TF1224) or artificially by taking IS on table or by ALTER statement <table> SET (LOCK_ESCALATION = auto|table|disable) READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk
  • 8. READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk
  • 9. NL SCH-S SCH-M S U X IS IU IX SIU SIX UIX BU RS-S RS-U RI-N RI-S RI-U RI-X RX-S RX-U RX-X NL SCH-S SCH-M S U X IS IU IX SQL Server SIU SIX Lock Compatibility Chart UIX BU RS-S RS-U RI-N RI-S No Conflict RI-U Conflict RI-X RX-S Illegal RX-U RX-X NL No Lock IX Intent Exclusive RI-S Insert Range-Shared SCH-S Schema Stability Lock SIU Share with Intent Update RI-U Insert Range-Update SCH-M Schema Modification Lock SIX Share with Intent Exclusive RI-X Insert Range-Exclusive S Shared UIX Update with Intent Exclusive RX-S Exclusive Range-Shared U Update BU Bulk Update RX-U Exclusive Range-Update X Exclusive RS-S Shared Range-Shared RX-X Exclusive Range-Exclusive IS Intent Shared RS-U Shared Range-Update IU Intent Update RI-N Insert Range-Null READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk
  • 10. Lock must wait! Intent Locks Table IX X orders Data Page IX Free Space X Row READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk
  • 11. NOLOCK (a Wolf in Sheep’s clothing?) Should use READUNCOMMITTED hint instead. Doesn’t acquire Shared locks so is able to perform DIRTY READS, NON-REPEATABLE READS, PHANTOMS …and I bet you didn’t know it can also return DUPLICATE READS! It DOES NOT give “Oracle style” concurrency When can this ever be acceptable? READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk
  • 12. Well since you mention it… Scalable Shared Database “There is SQL Server NOLOCK” Instance B Instance C Database Snapshot SQL Server Instance A Filegroup1 Filegroup2 Filegroup3 Readonly Database Readonly Filegroup/s “When should you use NOLOCK?“ http://bit.ly/rdGzow READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk
  • 13. READPAST & (your boss) may be Furious! Is an alternative to NOLOCK/ READUNCOMMITTED. Skip over resources holding incompatible (to S) locks. Does not therefore cause dirty or duplicate reads. (yay!) …But It still DOES NOT give “Oracle style” concurrency …and can return INCOMPLETE DATA SETS! When can this ever be acceptable? READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk
  • 14. Using READPAST and Table Queues --Get the first record orders --possible and update UPDATE u SET … X X FROM 2 U ( SELECT TOP(1) * FROM orders U WITH (READPAST ,UPDLOCK) WHERE … 1 ) AS U READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk
  • 15. READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk Locking Demo
  • 16. Read Committed Snapshot vs Snapshot Isolation SI provides isolation at the transaction level, RCS provides isolation at the statement level SI must be explicitly SET in each connection, for RCS it becomes the new default Enabling SI level requires no active transactions in order to transition. Enabling RCS requires Exclusive Transaction Workspace lock (and therefore no other connections to DB). RCS not allowed on master, tempdb and msdb, SI is allowed SI implements automatic update conflict detection READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk
  • 17. Database Snapshots 5 COMMIT 1 BEGIN TRAN UPDATE orders 4 SET … SELECT * WHERE … Buffer Cache FROM orders o … 2 3 CHECKPOINT Transaction Log Data FIle READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk
  • 18. READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk Snapshots Demo
  • 19. References and Thanks Professional SQL Server 2008 Internals and Troubleshooting – Locking and Latches Chapter - James Rowland Jones Kalen Delaney, SQLPASS Summit 2011 DBA301P - Locking and Blocking and Row Versions, Oh My! – DVD Jose Barreto's Blog http://blogs.technet.com/b/josebda/archive/2009/03/19/sql-server-2008- locking.aspx A special thanks to :- Paul White @sql_kiwi http://sqlblog.com/blogs/paul_white Benjamin Neverez @BenjaminNeverez http://www.benjaminnevarez.com/ READPAST & Furious: Locking Blocking and Isolation · Mark Broadbent · sqlcloud.co.uk