The SELECT FOR UPDATE
statement in Oracle is a query that locks specific rows in a table to ensure no other session can modify them while your session is working with them. This is useful for ensuring data consistency in multi-user environments.
Key Points:
Purpose:
- It locks the rows selected by the query to prevent updates or deletes by other sessions.
- Other sessions can still read the data, but they cannot modify it until your session releases the lock.
How It Works:
- When you execute
SELECT ... FOR UPDATE
, Oracle:- Retrieves the rows that meet the query's condition.
- Places an exclusive lock on those rows.
- The lock stays until your session ends the transaction with either:
COMMIT
: Save the changes and release the lock.ROLLBACK
: Undo the changes and release the lock.
- When you execute
Behavior with Locked Rows:
- If another session already holds a lock on the rows you're trying to select, your query will wait until the lock is released (default behavior).
- You can use
NOWAIT
orWAIT n
options to handle such scenarios:NOWAIT
: Returns an error immediately if the rows are locked.WAIT n
: Waits up ton
seconds for the lock to be released before throwing an error.
Example Scenario:
Step 1: Session 1 locks rows.
- Rows with
DEPTNO = 10
are locked by Session 1.
Step 2: Session 2 tries to lock the same rows.
- Session 2 will wait until Session 1 commits or rolls back.
Step 3: Session 1 commits.
- Lock is released. Session 2 can now proceed.
Real-Life Use Case:
Imagine a banking system:
- Session 1: A user is transferring money and locks their account row.
- Session 2: Another user tries to update the same account during the transfer.
- The
SELECT FOR UPDATE
ensures no conflicting updates occur until the transfer is complete.
Notes:
- Use this feature judiciously, as holding locks for too long can lead to contention or deadlocks.
- Always ensure transactions using
SELECT FOR UPDATE
end promptly withCOMMIT
orROLLBACK
.
No comments:
Post a Comment