SlideShare una empresa de Scribd logo
1 de 57
Descargar para leer sin conexión
Database for Developers
Session 6: Transactions
    Avishai Krepel & Tal Olier
Agenda
 Preface
 Database transactions and the ACID model
 Locking - basics
 Concurrency
 Locking - advanced
So many users, so little time…
 User A interacts with data X
 User B interacts with data Y
 User C interacts with data X and Y
Conflict?


  Multi user applications has a parallel aspect…
Ideal world
 Suggestion - each user working on it’s own copy of the data,
  and sees other users’ (copy of the) data when required,
  updated to the correct time required.
 Concerns:
   How do we decide who owns the data?
   What is the correct time ?
Ideal world (cont.)
 Throughput compromise!
   User A works on Sundays, Tuesdays and Thursdays
   User B works on Mondays, Wednesdays and Fridays
   User C will have to work Saturdays…
What is a database transaction?
 Something we perform on our data?
 Will it keeps my data safe?
 How does it lets multiple users to do their work
  simultaneously?
 From Babylon:
   “interaction between two parties, negotiation, settlement;
    business deal”
   What is the contract?
The ACID model
 A set of rules for “keep our data safe”
 Acronym for
   Atomicity
   Consistency
   Isolation
   Durability
ACID - Atomicity


           “All in one proposition”
ACID - Consistency
 Data’s state is kept consistent
 Data structures kept correct
 Failed transaction’s impact is canceled
ACID - Isolation
 Transaction separation until finished
   Modification's separation
   Data visibility separation
ACID - Durability
 Modification persistency
 Crash recovery
   Data recovery
   Log implementation
Locking (basics)
Locking
 Resource regulation
 Possible in several levels
   Object
   Page/Block
   Row
 Conceptual types:
   Exclusive lock
   Share lock
Exclusive lock
 Prevents sharing
 Obtained to modify data
 State assured until lock is removed
Share lock
 Allows limited sharing
 Used by data readers to block writers
 Share likes “to share” with share
… Consistency

•   Data’s state is kept consistent
•   Data structures kept correct
•   Failed transaction’s impact is canceled …
Read consistency
 Data changes according to time
 Readers and writers conflicts
 Default level
   Oracle: statement
   SQL Server: none
Stmt level read consistency (Oracle)
 SELECT statement starts at
  08:00 (SCN 10023)
 UPDATE statement update
                               1-
  data in block #3 and block
                               2-
  #5 at 09:00 (SCN
  10024)                       3-
 The SELECT gets to blocks
                               4-
  #3 and #5 at 10:00 and       5-
  reads them from the          6-
  rollback segment (UNDO       7-
  tablespace)
Concurrency
Concurrency side effects
 Dirty reads
 Nonrepeatable (fuzzy) reads
 Phantom reads (or phantoms)
Isolation levels
Isolation Levels
The SQL standard defines four levels:
 Read uncommitted
 Read committed
 Repeatable read
 Serializable
Isolation Levels - Read uncommitted
 The only rule is – “no rules”
 One transaction may see uncommitted changes made by
  some other transaction
Isolation Levels - Read committed
 The default isolation level
 Query sees only data committed before (what?)
 Good for conflicting transactions
Isolation Levels - Repeatable read
 Read data can not be changed
 The transaction require specific locks
 The transaction will see new data committed
Isolation Levels - Serializable
 Create the feeling that no other user changed
  data
 Implementations difference
   Oracle: The transaction sees only changes
    committed before it started
   SQL Server: The transaction sees the changes as if
    all transactions are ordered by time
 Require extra developer work
Read phenomena by isolation levels
Isolation levels – Oracle and SQL
Server
 Oracle offers the following        SQL Server offers all 4
  isolation levels                    isolation levels:
   Read committed                     Read uncommitted
   Serializable isolation levels      Read committed
   Read-only mode that is not         Repeatable read
    part of SQL92                      Serializable
 Read committed is the              Read committed is the
  default                             default
Setting isolation level
Oracle                           SQL Server
 SET TRANSACTION ISOLATION
    LEVEL READ COMMITTED;
                                 SET TRANSACTION
   SET TRANSACTION ISOLATION      ISOLATION LEVEL
    LEVEL SERIALIZABLE;             READ UNCOMMITTED
   SET TRANSACTION READ ONLY;
   ALTER SESSION SET               READ COMMITTED
    ISOLATION_LEVEL                 REPEATABLE READ
    SERIALIZABLE;
   ALTER SESSION SET               SERIALIZABLE
    ISOLATION_LEVEL READ
    COMMITTED;
Back to locking (advanced…)
Readers and writers
Oracle                     SQL Server
 Data versioning based     Read-lock mechanism
   Readers do not block    based
    writers                   Readers block writers
   Writers do not block      Writers block readers
    readers
Locking - Oracle
Types of locks
Oracle DML locks
 Assure integrity of data being accessed by multiple users
 Both table and row locks are used
 Partition is considered a table
Row locks (Oracle DML locks)
A transaction acquires an exclusive row lock for each individual
  row modified by one of the following statements:
 INSERT
 UPDATE
 DELETE
 SELECT (only with the FORUPDATE clause)
Table locks (Oracle DML locks)


  LOCK TABLE <table name> IN EXCLUSIVE MODE
Oracle manual (explicit ) data locking
Possible via one of the following:
 The SET TRANSACTION ISOLATION LEVEL statement
 The LOCK TABLE statement
 The SELECT ... FOR UPDATE statement


Locks acquired by these statements are released after the
  transaction commits or rolls back
Locking – SQL Server
Resources that can be locked by SQL Server
Locking explicitly – SQL Server
 Done via hints (proprietary syntax)
 Example:
  select *
  from t1
  with (PAGLOCK ,HOLDLOCK)
  where c1 between 17 and 32
Locking explicitly – SQL Server (cont.)
 Some more examples of hints
   NOLOCK/READUNCOMMITTED – dirty read
   PAGLOCK – takes page locks instead of row locks (statement
    scoped)
   TABLOCK/X - takes page locks (share, exclusive) instead of
    row locks (statement scoped)
   UPDLOCK/XLOCK – takes exclusive locks for read rows
    (transaction scoped)
Locking and transactions
 Transaction modes are managed at the session level
 Connection is the object that encapsulates the session “state”
Transaction management - syntax
Oracle                      SQL Server
BEGIN                       BEGIN TRANSACTION
  update emp set salary =     update emp set salary =
  salary * 0.95;              salary * 0.95;
  update emp set salary =     update emp set salary =
  salary * 0.95 where
                              salary * 0.95 where
  manager_flag = 1;
                              manager_flag = 1;
COMMIT;
                            COMMIT;
END;
/                           GO
Transaction – possible endings
 Commit – makes changes visible
 Rollback – cancel changes
 commit/rollback
   Remove all locks
   Start a new implicit transaction
Auto commit
 Every SQL statement is committed (upon completion)
 The default mode for ADO, OLE DB, ODBC, DB-Library
  and Java
SQL tools behavior
 Notice the auto-commit setting prior to updating records
 SQL Server
   SQL Server management studio (SSMS)
     Every query window is a different connection

 Oracle
   Oracle SQL developer (until release 2)
     All windows of the same connection share the same transaction (and
      locks)
Partial rollback
SQL Server “save transaction”          Oracle “savepoint”

begin transaction trans1               begin

                                          insert into t1 values (1, 'one');
   insert into t1 values (1, 'one');
                                          savepoint two;
   save transaction two
                                          insert into 1 values (2, 'two');
   insert into 1 values (2, 'two');
                                          rollback to savepoint two;

   rollback transaction two               commit;

commit                                 end;
Partial rollback (cont.)

SQL Server “save transaction”   Oracle “savepoint”



After a partial rollback        After a partial rollback
  transaction do not free         transaction do free locks
  locks held by roll backed       held by roll backed
  statements                      statements
Select for update (demo)
Oracle                 SQL Server
 SELECT ID FROM EMP    SELECT ID FROM EMP
 FOR UPDATE             WITH (UPD LOCK)
Locking example
1         2      3      4     5
6         7      8      9     10
11        12     13     14    15
16        17     18     19    20
21        22     23     24    25

…
101       102    103    104   105
106       107    108    109   110
111       112    113    114   115
116       117    118    119   120
121       122    123    124   125
Lock escalation
 Occurs when numerous locks are held at one level of
  granularity
 Database decides to raise some/all of the locks to a higher
  level
 Tradeoff between number of locks and restrictiveness
Lock escalation – Oracle


        Oracle never escalate locks!
Lock escalation – SQL Server
 Escalation thresholds:
   T-SQL level – amount of locked rows (~5000)
   Instance level – amount of memory occupied by locks (40%)
 Thresholds can be changed
   SQL Sever instance ‘locks’ parameter
 Escalation can fail because of other locking transactions
Lock escalation – SQL Server (cont.)
Escalation success             Escalation failure
 The full table lock is        Full lock cannot be
  acquired                       acquired
 All heap or B-tree, page      Database Engine will
  (PAGE), or row-level           continue to acquire row,
  (RID) locks held by the        key, or page locks
  transaction on the heap or    Database Engine will retry
  index are released             the lock escalation for each
                                 additional ~1,250 locks
                                 acquired by the transaction
Lock escalation – demo (SQL Server)
 Demo table




 Update of x rows from the
  table
 Check the locks on the
  table
Lock escalation – disable
 At instance level
   DBCC TRACEON (1211,-1) – disable memory or # of locks
    escalations
   DBCC TRACEON (1224,-1) – disable # locks escalations
 At table level (SQL Server 2008 only)
   ALTER TABLE SET LOCK_ESCALATION = DISABLE
 At session level
   DBCC TRACEON (1211)
   DBCC TRACEON (1224)
Lock escalation – DEV pitfalls
Note:
   Cases when multiple updates/deletes from various clients
    happen on the same table and spanned across many rows
   Select with updlock (select for update) is considered as update
   Oracle developers do not know this behavior
Deadlock (example)
This is it.

Más contenido relacionado

La actualidad más candente

SQL Server 2016 AlwaysOn Availability Groups New Features
SQL Server 2016 AlwaysOn Availability Groups New FeaturesSQL Server 2016 AlwaysOn Availability Groups New Features
SQL Server 2016 AlwaysOn Availability Groups New FeaturesJohn Martin
 
Andrewfraserdba.com training sql_training
Andrewfraserdba.com training sql_trainingAndrewfraserdba.com training sql_training
Andrewfraserdba.com training sql_trainingmark jerald Canal
 
Sql training
Sql trainingSql training
Sql trainingpremrings
 
Elastic beanstalk
Elastic beanstalkElastic beanstalk
Elastic beanstalkParag Patil
 
Sql Server 2008 Enhancements
Sql Server 2008 EnhancementsSql Server 2008 Enhancements
Sql Server 2008 Enhancementskobico10
 
VirtualCenter Database Maintenance: VirtualCenter 2.0.x and ...
VirtualCenter Database Maintenance: VirtualCenter 2.0.x and ...VirtualCenter Database Maintenance: VirtualCenter 2.0.x and ...
VirtualCenter Database Maintenance: VirtualCenter 2.0.x and ...webhostingguy
 
Alwayson AG enhancements
Alwayson AG enhancementsAlwayson AG enhancements
Alwayson AG enhancementsHarsh Chawla
 
Configuring sql server - SQL Saturday, Athens Oct 2014
Configuring sql server - SQL Saturday, Athens Oct 2014Configuring sql server - SQL Saturday, Athens Oct 2014
Configuring sql server - SQL Saturday, Athens Oct 2014Antonios Chatzipavlis
 
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 EditionMark Broadbent
 
Ajuste (tuning) del rendimiento de SQL Server 2008
Ajuste (tuning) del rendimiento de SQL Server 2008Ajuste (tuning) del rendimiento de SQL Server 2008
Ajuste (tuning) del rendimiento de SQL Server 2008Eduardo Castro
 
SQL Server 2012 High Availability with AlwaysOn Availability Groups
SQL Server 2012 High Availability with AlwaysOn Availability GroupsSQL Server 2012 High Availability with AlwaysOn Availability Groups
SQL Server 2012 High Availability with AlwaysOn Availability GroupsEdwin M Sarmiento
 
Database Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event SchedulersDatabase Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event SchedulersAbdul Rahman Sherzad
 

La actualidad más candente (13)

SQL Server 2016 AlwaysOn Availability Groups New Features
SQL Server 2016 AlwaysOn Availability Groups New FeaturesSQL Server 2016 AlwaysOn Availability Groups New Features
SQL Server 2016 AlwaysOn Availability Groups New Features
 
Andrewfraserdba.com training sql_training
Andrewfraserdba.com training sql_trainingAndrewfraserdba.com training sql_training
Andrewfraserdba.com training sql_training
 
Sql training
Sql trainingSql training
Sql training
 
Elastic beanstalk
Elastic beanstalkElastic beanstalk
Elastic beanstalk
 
Sql Server 2008 Enhancements
Sql Server 2008 EnhancementsSql Server 2008 Enhancements
Sql Server 2008 Enhancements
 
VirtualCenter Database Maintenance: VirtualCenter 2.0.x and ...
VirtualCenter Database Maintenance: VirtualCenter 2.0.x and ...VirtualCenter Database Maintenance: VirtualCenter 2.0.x and ...
VirtualCenter Database Maintenance: VirtualCenter 2.0.x and ...
 
Alwayson AG enhancements
Alwayson AG enhancementsAlwayson AG enhancements
Alwayson AG enhancements
 
Configuring sql server - SQL Saturday, Athens Oct 2014
Configuring sql server - SQL Saturday, Athens Oct 2014Configuring sql server - SQL Saturday, Athens Oct 2014
Configuring sql server - SQL Saturday, Athens Oct 2014
 
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
 
Ajuste (tuning) del rendimiento de SQL Server 2008
Ajuste (tuning) del rendimiento de SQL Server 2008Ajuste (tuning) del rendimiento de SQL Server 2008
Ajuste (tuning) del rendimiento de SQL Server 2008
 
Sql2008 (1)
Sql2008 (1)Sql2008 (1)
Sql2008 (1)
 
SQL Server 2012 High Availability with AlwaysOn Availability Groups
SQL Server 2012 High Availability with AlwaysOn Availability GroupsSQL Server 2012 High Availability with AlwaysOn Availability Groups
SQL Server 2012 High Availability with AlwaysOn Availability Groups
 
Database Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event SchedulersDatabase Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event Schedulers
 

Destacado

Sql Server Replication Idf
Sql Server Replication   IdfSql Server Replication   Idf
Sql Server Replication Idfsqlserver.co.il
 
4 extreme performance - part ii
4   extreme performance - part ii4   extreme performance - part ii
4 extreme performance - part iisqlserver.co.il
 
Sql Server Replication Isug 1 2009
Sql Server Replication   Isug 1 2009Sql Server Replication   Isug 1 2009
Sql Server Replication Isug 1 2009sqlserver.co.il
 
What Is Good Performance Isqlug Jan 2010
What Is Good Performance Isqlug Jan 2010What Is Good Performance Isqlug Jan 2010
What Is Good Performance Isqlug Jan 2010sqlserver.co.il
 
Appointment reciept
Appointment recieptAppointment reciept
Appointment recieptNandeesh B
 
Windows azure sql_database_security_isug012013
Windows azure sql_database_security_isug012013Windows azure sql_database_security_isug012013
Windows azure sql_database_security_isug012013sqlserver.co.il
 

Destacado (6)

Sql Server Replication Idf
Sql Server Replication   IdfSql Server Replication   Idf
Sql Server Replication Idf
 
4 extreme performance - part ii
4   extreme performance - part ii4   extreme performance - part ii
4 extreme performance - part ii
 
Sql Server Replication Isug 1 2009
Sql Server Replication   Isug 1 2009Sql Server Replication   Isug 1 2009
Sql Server Replication Isug 1 2009
 
What Is Good Performance Isqlug Jan 2010
What Is Good Performance Isqlug Jan 2010What Is Good Performance Isqlug Jan 2010
What Is Good Performance Isqlug Jan 2010
 
Appointment reciept
Appointment recieptAppointment reciept
Appointment reciept
 
Windows azure sql_database_security_isug012013
Windows azure sql_database_security_isug012013Windows azure sql_database_security_isug012013
Windows azure sql_database_security_isug012013
 

Similar a Database concurrency and transactions - Tal Olier

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!Boris Hristov
 
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!Boris Hristov
 
The Nightmare of Locking, Blocking and Isolation Levels!
The Nightmare of Locking, Blocking and Isolation Levels!The Nightmare of Locking, Blocking and Isolation Levels!
The Nightmare of Locking, Blocking and Isolation Levels!Boris Hristov
 
The Nightmare of Locking, Blocking and Isolation Levels!
The Nightmare of Locking, Blocking and Isolation Levels!The Nightmare of Locking, Blocking and Isolation Levels!
The Nightmare of Locking, Blocking and Isolation Levels!Boris Hristov
 
Database Transactions and SQL Server Concurrency
Database Transactions and SQL Server ConcurrencyDatabase Transactions and SQL Server Concurrency
Database Transactions and SQL Server ConcurrencyBoris Hristov
 
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 levelsBoris Hristov
 
Choosing A Concurrency Model, Optimistic Or Pessimistic
Choosing A Concurrency Model, Optimistic Or PessimisticChoosing A Concurrency Model, Optimistic Or Pessimistic
Choosing A Concurrency Model, Optimistic Or PessimisticVinod Kumar
 
Concurrency in SQL Server (SQL Night #24)
Concurrency in SQL Server (SQL Night #24)Concurrency in SQL Server (SQL Night #24)
Concurrency in SQL Server (SQL Night #24)Antonios Chatzipavlis
 
Managing Memory & Locks - Series 2 Transactions & Lock management
Managing  Memory & Locks - Series 2 Transactions & Lock managementManaging  Memory & Locks - Series 2 Transactions & Lock management
Managing Memory & Locks - Series 2 Transactions & Lock managementDAGEOP LTD
 
SQL Server Transaction Management
SQL Server Transaction ManagementSQL Server Transaction Management
SQL Server Transaction ManagementMark Ginnebaugh
 
SQL Server Blocking Analysis
SQL Server Blocking AnalysisSQL Server Blocking Analysis
SQL Server Blocking AnalysisHậu Võ Tấn
 
Intro to tsql unit 12
Intro to tsql   unit 12Intro to tsql   unit 12
Intro to tsql unit 12Syed Asrarali
 
11g Identity Management - InSync10
11g Identity Management - InSync1011g Identity Management - InSync10
11g Identity Management - InSync10Peter McLarty
 
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 levelsBoris Hristov
 
Sql server-dba
Sql server-dbaSql server-dba
Sql server-dbaNaviSoft
 
The nightmare of locking, blocking and isolation levels!
The nightmare of locking, blocking and isolation levels!The nightmare of locking, blocking and isolation levels!
The nightmare of locking, blocking and isolation levels!Boris Hristov
 
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!Boris Hristov
 
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...Alex Zaballa
 

Similar a Database concurrency and transactions - Tal Olier (20)

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!
 
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!
 
The Nightmare of Locking, Blocking and Isolation Levels!
The Nightmare of Locking, Blocking and Isolation Levels!The Nightmare of Locking, Blocking and Isolation Levels!
The Nightmare of Locking, Blocking and Isolation Levels!
 
The Nightmare of Locking, Blocking and Isolation Levels!
The Nightmare of Locking, Blocking and Isolation Levels!The Nightmare of Locking, Blocking and Isolation Levels!
The Nightmare of Locking, Blocking and Isolation Levels!
 
Database Transactions and SQL Server Concurrency
Database Transactions and SQL Server ConcurrencyDatabase Transactions and SQL Server Concurrency
Database Transactions and SQL Server Concurrency
 
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
 
Choosing A Concurrency Model, Optimistic Or Pessimistic
Choosing A Concurrency Model, Optimistic Or PessimisticChoosing A Concurrency Model, Optimistic Or Pessimistic
Choosing A Concurrency Model, Optimistic Or Pessimistic
 
Ibm db2 case study
Ibm db2 case studyIbm db2 case study
Ibm db2 case study
 
Concurrency in SQL Server (SQL Night #24)
Concurrency in SQL Server (SQL Night #24)Concurrency in SQL Server (SQL Night #24)
Concurrency in SQL Server (SQL Night #24)
 
Managing Memory & Locks - Series 2 Transactions & Lock management
Managing  Memory & Locks - Series 2 Transactions & Lock managementManaging  Memory & Locks - Series 2 Transactions & Lock management
Managing Memory & Locks - Series 2 Transactions & Lock management
 
SQL Server Transaction Management
SQL Server Transaction ManagementSQL Server Transaction Management
SQL Server Transaction Management
 
SQL Server Blocking Analysis
SQL Server Blocking AnalysisSQL Server Blocking Analysis
SQL Server Blocking Analysis
 
Intro to tsql unit 12
Intro to tsql   unit 12Intro to tsql   unit 12
Intro to tsql unit 12
 
Sql server 2012 ha dr
Sql server 2012 ha drSql server 2012 ha dr
Sql server 2012 ha dr
 
11g Identity Management - InSync10
11g Identity Management - InSync1011g Identity Management - InSync10
11g Identity Management - InSync10
 
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
 
Sql server-dba
Sql server-dbaSql server-dba
Sql server-dba
 
The nightmare of locking, blocking and isolation levels!
The nightmare of locking, blocking and isolation levels!The nightmare of locking, blocking and isolation levels!
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!
Welcome to the nightmare of locking, blocking and isolation levels!
 
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
 

Más de sqlserver.co.il

Things you can find in the plan cache
Things you can find in the plan cacheThings you can find in the plan cache
Things you can find in the plan cachesqlserver.co.il
 
Sql server user group news january 2013
Sql server user group news   january 2013Sql server user group news   january 2013
Sql server user group news january 2013sqlserver.co.il
 
Query handlingbytheserver
Query handlingbytheserverQuery handlingbytheserver
Query handlingbytheserversqlserver.co.il
 
Adi Sapir ISUG 123 11/10/2012
Adi Sapir ISUG 123 11/10/2012Adi Sapir ISUG 123 11/10/2012
Adi Sapir ISUG 123 11/10/2012sqlserver.co.il
 
Products.intro.forum version
Products.intro.forum versionProducts.intro.forum version
Products.intro.forum versionsqlserver.co.il
 
SQL Explore 2012: P&T Part 3
SQL Explore 2012: P&T Part 3SQL Explore 2012: P&T Part 3
SQL Explore 2012: P&T Part 3sqlserver.co.il
 
SQL Explore 2012: P&T Part 2
SQL Explore 2012: P&T Part 2SQL Explore 2012: P&T Part 2
SQL Explore 2012: P&T Part 2sqlserver.co.il
 
SQL Explore 2012: P&T Part 1
SQL Explore 2012: P&T Part 1SQL Explore 2012: P&T Part 1
SQL Explore 2012: P&T Part 1sqlserver.co.il
 
SQL Explore 2012 - Tzahi Hakikat and Keren Bartal: Extended Events
SQL Explore 2012 - Tzahi Hakikat and Keren Bartal: Extended EventsSQL Explore 2012 - Tzahi Hakikat and Keren Bartal: Extended Events
SQL Explore 2012 - Tzahi Hakikat and Keren Bartal: Extended Eventssqlserver.co.il
 
SQL Explore 2012 - Michael Zilberstein: ColumnStore
SQL Explore 2012 - Michael Zilberstein: ColumnStoreSQL Explore 2012 - Michael Zilberstein: ColumnStore
SQL Explore 2012 - Michael Zilberstein: ColumnStoresqlserver.co.il
 
SQL Explore 2012 - Meir Dudai: DAC
SQL Explore 2012 - Meir Dudai: DACSQL Explore 2012 - Meir Dudai: DAC
SQL Explore 2012 - Meir Dudai: DACsqlserver.co.il
 
SQL Explore 2012 - Aviad Deri: Spatial
SQL Explore 2012 - Aviad Deri: SpatialSQL Explore 2012 - Aviad Deri: Spatial
SQL Explore 2012 - Aviad Deri: Spatialsqlserver.co.il
 
Bi303 data warehousing with fast track and pdw - Assaf Fraenkel
Bi303 data warehousing with fast track and pdw - Assaf FraenkelBi303 data warehousing with fast track and pdw - Assaf Fraenkel
Bi303 data warehousing with fast track and pdw - Assaf Fraenkelsqlserver.co.il
 
Fast transition to sql server 2012 from mssql 2005 2008 for developers - Dav...
Fast transition to sql server 2012 from mssql 2005 2008 for  developers - Dav...Fast transition to sql server 2012 from mssql 2005 2008 for  developers - Dav...
Fast transition to sql server 2012 from mssql 2005 2008 for developers - Dav...sqlserver.co.il
 

Más de sqlserver.co.il (20)

Things you can find in the plan cache
Things you can find in the plan cacheThings you can find in the plan cache
Things you can find in the plan cache
 
Sql server user group news january 2013
Sql server user group news   january 2013Sql server user group news   january 2013
Sql server user group news january 2013
 
DAC 2012
DAC 2012DAC 2012
DAC 2012
 
Query handlingbytheserver
Query handlingbytheserverQuery handlingbytheserver
Query handlingbytheserver
 
Adi Sapir ISUG 123 11/10/2012
Adi Sapir ISUG 123 11/10/2012Adi Sapir ISUG 123 11/10/2012
Adi Sapir ISUG 123 11/10/2012
 
Products.intro.forum version
Products.intro.forum versionProducts.intro.forum version
Products.intro.forum version
 
SQL Explore 2012: P&T Part 3
SQL Explore 2012: P&T Part 3SQL Explore 2012: P&T Part 3
SQL Explore 2012: P&T Part 3
 
SQL Explore 2012: P&T Part 2
SQL Explore 2012: P&T Part 2SQL Explore 2012: P&T Part 2
SQL Explore 2012: P&T Part 2
 
SQL Explore 2012: P&T Part 1
SQL Explore 2012: P&T Part 1SQL Explore 2012: P&T Part 1
SQL Explore 2012: P&T Part 1
 
SQL Explore 2012 - Tzahi Hakikat and Keren Bartal: Extended Events
SQL Explore 2012 - Tzahi Hakikat and Keren Bartal: Extended EventsSQL Explore 2012 - Tzahi Hakikat and Keren Bartal: Extended Events
SQL Explore 2012 - Tzahi Hakikat and Keren Bartal: Extended Events
 
SQL Explore 2012 - Michael Zilberstein: ColumnStore
SQL Explore 2012 - Michael Zilberstein: ColumnStoreSQL Explore 2012 - Michael Zilberstein: ColumnStore
SQL Explore 2012 - Michael Zilberstein: ColumnStore
 
SQL Explore 2012 - Meir Dudai: DAC
SQL Explore 2012 - Meir Dudai: DACSQL Explore 2012 - Meir Dudai: DAC
SQL Explore 2012 - Meir Dudai: DAC
 
SQL Explore 2012 - Aviad Deri: Spatial
SQL Explore 2012 - Aviad Deri: SpatialSQL Explore 2012 - Aviad Deri: Spatial
SQL Explore 2012 - Aviad Deri: Spatial
 
מיכאל
מיכאלמיכאל
מיכאל
 
נועם
נועםנועם
נועם
 
עדי
עדיעדי
עדי
 
מיכאל
מיכאלמיכאל
מיכאל
 
Bi303 data warehousing with fast track and pdw - Assaf Fraenkel
Bi303 data warehousing with fast track and pdw - Assaf FraenkelBi303 data warehousing with fast track and pdw - Assaf Fraenkel
Bi303 data warehousing with fast track and pdw - Assaf Fraenkel
 
DBCC - Dubi Lebel
DBCC - Dubi LebelDBCC - Dubi Lebel
DBCC - Dubi Lebel
 
Fast transition to sql server 2012 from mssql 2005 2008 for developers - Dav...
Fast transition to sql server 2012 from mssql 2005 2008 for  developers - Dav...Fast transition to sql server 2012 from mssql 2005 2008 for  developers - Dav...
Fast transition to sql server 2012 from mssql 2005 2008 for developers - Dav...
 

Database concurrency and transactions - Tal Olier

  • 1. Database for Developers Session 6: Transactions Avishai Krepel & Tal Olier
  • 2. Agenda  Preface  Database transactions and the ACID model  Locking - basics  Concurrency  Locking - advanced
  • 3. So many users, so little time…  User A interacts with data X  User B interacts with data Y  User C interacts with data X and Y Conflict? Multi user applications has a parallel aspect…
  • 4. Ideal world  Suggestion - each user working on it’s own copy of the data, and sees other users’ (copy of the) data when required, updated to the correct time required.  Concerns:  How do we decide who owns the data?  What is the correct time ?
  • 5. Ideal world (cont.)  Throughput compromise!  User A works on Sundays, Tuesdays and Thursdays  User B works on Mondays, Wednesdays and Fridays  User C will have to work Saturdays…
  • 6. What is a database transaction?  Something we perform on our data?  Will it keeps my data safe?  How does it lets multiple users to do their work simultaneously?  From Babylon:  “interaction between two parties, negotiation, settlement; business deal”  What is the contract?
  • 7. The ACID model  A set of rules for “keep our data safe”  Acronym for  Atomicity  Consistency  Isolation  Durability
  • 8. ACID - Atomicity “All in one proposition”
  • 9. ACID - Consistency  Data’s state is kept consistent  Data structures kept correct  Failed transaction’s impact is canceled
  • 10. ACID - Isolation  Transaction separation until finished  Modification's separation  Data visibility separation
  • 11. ACID - Durability  Modification persistency  Crash recovery  Data recovery  Log implementation
  • 13. Locking  Resource regulation  Possible in several levels  Object  Page/Block  Row  Conceptual types:  Exclusive lock  Share lock
  • 14. Exclusive lock  Prevents sharing  Obtained to modify data  State assured until lock is removed
  • 15. Share lock  Allows limited sharing  Used by data readers to block writers  Share likes “to share” with share
  • 16. … Consistency • Data’s state is kept consistent • Data structures kept correct • Failed transaction’s impact is canceled …
  • 17. Read consistency  Data changes according to time  Readers and writers conflicts  Default level  Oracle: statement  SQL Server: none
  • 18. Stmt level read consistency (Oracle)  SELECT statement starts at 08:00 (SCN 10023)  UPDATE statement update 1- data in block #3 and block 2- #5 at 09:00 (SCN 10024) 3-  The SELECT gets to blocks 4- #3 and #5 at 10:00 and 5- reads them from the 6- rollback segment (UNDO 7- tablespace)
  • 20. Concurrency side effects  Dirty reads  Nonrepeatable (fuzzy) reads  Phantom reads (or phantoms)
  • 22. Isolation Levels The SQL standard defines four levels:  Read uncommitted  Read committed  Repeatable read  Serializable
  • 23. Isolation Levels - Read uncommitted  The only rule is – “no rules”  One transaction may see uncommitted changes made by some other transaction
  • 24. Isolation Levels - Read committed  The default isolation level  Query sees only data committed before (what?)  Good for conflicting transactions
  • 25. Isolation Levels - Repeatable read  Read data can not be changed  The transaction require specific locks  The transaction will see new data committed
  • 26. Isolation Levels - Serializable  Create the feeling that no other user changed data  Implementations difference  Oracle: The transaction sees only changes committed before it started  SQL Server: The transaction sees the changes as if all transactions are ordered by time  Require extra developer work
  • 27. Read phenomena by isolation levels
  • 28. Isolation levels – Oracle and SQL Server  Oracle offers the following  SQL Server offers all 4 isolation levels isolation levels:  Read committed  Read uncommitted  Serializable isolation levels  Read committed  Read-only mode that is not  Repeatable read part of SQL92  Serializable  Read committed is the  Read committed is the default default
  • 29. Setting isolation level Oracle SQL Server  SET TRANSACTION ISOLATION LEVEL READ COMMITTED; SET TRANSACTION  SET TRANSACTION ISOLATION ISOLATION LEVEL LEVEL SERIALIZABLE;  READ UNCOMMITTED  SET TRANSACTION READ ONLY;  ALTER SESSION SET  READ COMMITTED ISOLATION_LEVEL  REPEATABLE READ SERIALIZABLE;  ALTER SESSION SET  SERIALIZABLE ISOLATION_LEVEL READ COMMITTED;
  • 30. Back to locking (advanced…)
  • 31. Readers and writers Oracle SQL Server  Data versioning based  Read-lock mechanism  Readers do not block based writers  Readers block writers  Writers do not block  Writers block readers readers
  • 33. Oracle DML locks  Assure integrity of data being accessed by multiple users  Both table and row locks are used  Partition is considered a table
  • 34. Row locks (Oracle DML locks) A transaction acquires an exclusive row lock for each individual row modified by one of the following statements:  INSERT  UPDATE  DELETE  SELECT (only with the FORUPDATE clause)
  • 35. Table locks (Oracle DML locks) LOCK TABLE <table name> IN EXCLUSIVE MODE
  • 36. Oracle manual (explicit ) data locking Possible via one of the following:  The SET TRANSACTION ISOLATION LEVEL statement  The LOCK TABLE statement  The SELECT ... FOR UPDATE statement Locks acquired by these statements are released after the transaction commits or rolls back
  • 37. Locking – SQL Server Resources that can be locked by SQL Server
  • 38. Locking explicitly – SQL Server  Done via hints (proprietary syntax)  Example: select * from t1 with (PAGLOCK ,HOLDLOCK) where c1 between 17 and 32
  • 39. Locking explicitly – SQL Server (cont.)  Some more examples of hints  NOLOCK/READUNCOMMITTED – dirty read  PAGLOCK – takes page locks instead of row locks (statement scoped)  TABLOCK/X - takes page locks (share, exclusive) instead of row locks (statement scoped)  UPDLOCK/XLOCK – takes exclusive locks for read rows (transaction scoped)
  • 40. Locking and transactions  Transaction modes are managed at the session level  Connection is the object that encapsulates the session “state”
  • 41. Transaction management - syntax Oracle SQL Server BEGIN BEGIN TRANSACTION update emp set salary = update emp set salary = salary * 0.95; salary * 0.95; update emp set salary = update emp set salary = salary * 0.95 where salary * 0.95 where manager_flag = 1; manager_flag = 1; COMMIT; COMMIT; END; / GO
  • 42. Transaction – possible endings  Commit – makes changes visible  Rollback – cancel changes  commit/rollback  Remove all locks  Start a new implicit transaction
  • 43. Auto commit  Every SQL statement is committed (upon completion)  The default mode for ADO, OLE DB, ODBC, DB-Library and Java
  • 44. SQL tools behavior  Notice the auto-commit setting prior to updating records  SQL Server  SQL Server management studio (SSMS)  Every query window is a different connection  Oracle  Oracle SQL developer (until release 2)  All windows of the same connection share the same transaction (and locks)
  • 45. Partial rollback SQL Server “save transaction” Oracle “savepoint” begin transaction trans1 begin insert into t1 values (1, 'one'); insert into t1 values (1, 'one'); savepoint two; save transaction two insert into 1 values (2, 'two'); insert into 1 values (2, 'two'); rollback to savepoint two; rollback transaction two commit; commit end;
  • 46. Partial rollback (cont.) SQL Server “save transaction” Oracle “savepoint” After a partial rollback After a partial rollback transaction do not free transaction do free locks locks held by roll backed held by roll backed statements statements
  • 47. Select for update (demo) Oracle SQL Server  SELECT ID FROM EMP  SELECT ID FROM EMP FOR UPDATE WITH (UPD LOCK)
  • 48. Locking example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 … 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
  • 49. Lock escalation  Occurs when numerous locks are held at one level of granularity  Database decides to raise some/all of the locks to a higher level  Tradeoff between number of locks and restrictiveness
  • 50. Lock escalation – Oracle Oracle never escalate locks!
  • 51. Lock escalation – SQL Server  Escalation thresholds:  T-SQL level – amount of locked rows (~5000)  Instance level – amount of memory occupied by locks (40%)  Thresholds can be changed  SQL Sever instance ‘locks’ parameter  Escalation can fail because of other locking transactions
  • 52. Lock escalation – SQL Server (cont.) Escalation success Escalation failure  The full table lock is  Full lock cannot be acquired acquired  All heap or B-tree, page  Database Engine will (PAGE), or row-level continue to acquire row, (RID) locks held by the key, or page locks transaction on the heap or  Database Engine will retry index are released the lock escalation for each additional ~1,250 locks acquired by the transaction
  • 53. Lock escalation – demo (SQL Server)  Demo table  Update of x rows from the table  Check the locks on the table
  • 54. Lock escalation – disable  At instance level  DBCC TRACEON (1211,-1) – disable memory or # of locks escalations  DBCC TRACEON (1224,-1) – disable # locks escalations  At table level (SQL Server 2008 only)  ALTER TABLE SET LOCK_ESCALATION = DISABLE  At session level  DBCC TRACEON (1211)  DBCC TRACEON (1224)
  • 55. Lock escalation – DEV pitfalls Note:  Cases when multiple updates/deletes from various clients happen on the same table and spanned across many rows  Select with updlock (select for update) is considered as update  Oracle developers do not know this behavior