Two customers order item 42 at the same moment. Both orders read the stock, both subtract one, both commit. Afterwards the stock should be 98. On our lab it was 99: one order was rolled back with error 2631, and only one counted.
Part of the Teradata Internals and Operations guide.
That is a deadlock. This post shows how deadlocks form in Teradata, how Teradata finds them, which transaction it ends, and how you avoid them. It ends with a script that finds the deadlocks on your own system and tells you which statements caused them.
What a deadlock is
A transaction holds its locks until it ends. If transaction A holds a lock that B needs, B waits. That is ordinary blocking, and it resolves itself when A commits.
A deadlock is a cycle of waits: A waits for B, and B waits for A. Neither can finish, so neither will ever release its locks. Someone from outside has to break the cycle. In Teradata that is the lock manager: it picks one transaction, aborts it with error 2631, rolls back its changes and releases its locks. The other transaction then continues and commits.
Click through the diagram below. It shows, step by step, which session holds which lock on which table or row, where each AMP sits, and the moment the waits close into a cycle.
Seven deadlocks, reproduced
Each case ran with two or three concurrent BTEQ sessions, timed so that the locks interleave. The tables have 100 rows and a unique primary index on Id. Rows 1 and 2 hash to the same AMP; row 4 hashes to a different one.
| Example | What the sessions do | Kind | Wait until 2631 (run 1 / run 2) |
|---|---|---|---|
| Example 1 | A updates all of table T1, then T2; B updates T2, then T1 | global | 162 s / 139 s |
| Example 2 | Both read row 1 in a transaction, then both update it | local | 1.7 s / 10.6 s |
| Example 3 | A updates row 1, then row 2; B updates row 2, then row 1 (same AMP) | local | 24.6 s / 22.7 s |
| Example 4 | A updates row 1, then row 4; B updates row 4, then row 1 (two AMPs) | global | 215 s / 206 s |
| Example 5 | Both read the whole table (SELECT COUNT(*)), then both update row 1 |
local | 14.5 s / 23.7 s |
| Example 6 | Three sessions in a ring: A T1→T2, B T2→T3, C T3→T1 | global | 231 s / 222 s |
| Example 7 | Single-row inserts into a FALLBACK staging table while another session moves the batch | fallback | 0.00 s (19 and 17 of 400 inserts) |
They fall into two shapes.
Opposite order (Examples 1, 3, 4 and 6). Two transactions need the same objects and take them in a different order. It does not matter whether the objects are tables, rows on one AMP or rows on two AMPs, and it does not need to be two sessions: in Example 6 three sessions form a ring, and no pair of them alone would deadlock.
Read, then update (Examples 2 and 5, and the stock order). Both transactions read first, so both hold a READ lock. Then both want to update, which needs a WRITE lock. WRITE cannot be granted while the other READ is held, so each waits for the other. One row is enough. This is the most common deadlock in application code, because “read the value, then change it” is how most business logic is written.
-- Each order (the stock order): two sessions run this, B starts 2 s after A
BT;
SELECT Qty FROM DL_Stock WHERE Item_Id = 42;
UPDATE DL_Stock SET Qty = Qty - 1 WHERE Item_Id = 42;
ET;
Result on the lab: B received 2631 after 13.67 s; stock afterwards 99.
Doesn’t Teradata prevent this? Partly. The EXPLAIN of an all-row update starts like this:
1) First, we lock TUNING_DEMO.DL_T1 in TD_MAP1 for write on a
reserved RowHash to prevent global deadlock.
2) Next, we lock TUNING_DEMO.DL_T1 in TD_MAP1 for write.
This proxy lock orders requests for one table, so two all-row updates of the same table queue up instead of deadlocking across AMPs. It cannot help when two tables are taken in opposite order: Examples 1 and 6 deadlocked anyway.
Local, global and fallback: how Teradata finds them
Where the locks live decides how long a deadlock lasts.
Local deadlock: all waits on one AMP. The AMP sees the whole cycle itself. The documentation says the local check runs at a fixed 30-second interval. On the lab we ran the stock order six times, each started 5 s later than the one before. All six 2631s came on the same 30-second ticks; the waits were 8.50, 19.13, 14.40, 9.57, 4.47 and 29.07 s. Moving the start moved the wait, not the tick. A local deadlock therefore waits anywhere up to 30 s. There is no setting for this interval: a display of all DBS Control fields on the lab has none.
Global deadlock: the cycle spans AMPs. In Example 4, row 1 lives on one AMP and row 4 on another, so each AMP sees only one of the two waits. Neither sees a cycle. Only the global check, which collects the waits of all AMPs, can find it. It runs every 240 seconds by default (DBS Control field DeadLockTimeout). 240 s is the interval between checks, not the wait: a deadlock waits until the next check. On the lab the global waits were 2 min 19 s to 3 min 51 s.
Fallback deadlock: found at once. In Example 7 the lock log flagged every abort FallBackDeadLock, with a delay of 0.00 s. The documentation describes the mechanism for requests that need row-hash locks on both the primary and the fallback copy: one request gets the primary first, the other the fallback first. On the lab it hit a user staging table: a session inserting single rows while another ran INSERT INTO target SELECT * FROM staging; DELETE FROM staging; as one request. The inserter was the victim every time, 19 and 17 times in 400 inserts. Without a retry, each of those rows was missing from the load.
Changing the global interval
DeadLockTimeout is field 3 of the GENERAL group in DBS Control. We set it to 30 s on the lab:
dbscontrol
MODIFY GENERAL 3 = 30
WRITE
dbscontrol answers: “This change will become effective after the next DBS restart.” That is literal. With 30 s written but no restart, Example 4 still waited 327.5 s. After a database restart (logons were back about 20 s later), the same deadlock ended after 44.6, 45.3 and 15.9 s. So a smaller value does shorten global deadlocks a lot, but not to exactly the setting: two of three waits were about 45 s. After setting 240 s again and restarting, Example 4 waited 230.2 s.
On the lab the field accepted values from 2 to 3600 s and warned below 10 s (“less than the recommended minimal setting of 10 seconds”). The documentation gives 10–3600 s and recommends lower values (30–45 s, or as low as 10 s for mostly tactical workloads) when deadlocks are frequent.
Who loses?
The documentation says Teradata resolves a deadlock by ending the younger request. On our lab the victim was the older one in 3 of 14 deadlocks: in Example 4 (both runs) and Example 3 (run 2), A was rolled back although its transaction and its blocked request had both started first. Do not assume which side loses; check the victim in DBQL (the script below does).
The retry trap
BTEQ resubmits a failed request by default (.SET RETRY ON). We ran Example 3 again with that default. Session B received 2631, and BTEQ printed “Attempting to resubmit last request”. It resubmitted only the last statement:
-- Session B
BT;
UPDATE DL_T2 SET Val = Val + 1 WHERE Id = 2; -- rolled back with the transaction
UPDATE DL_T2 SET Val = Val + 1 WHERE Id = 1; -- 2631, then resubmitted on its own and committed
ET; -- 3510: Too many END TRANSACTION statements
The rollback undid the whole transaction, including the update of row 2. The resubmitted update of row 1 then ran outside any transaction and committed. Afterwards row 1 had B’s change and row 2 did not: half a transaction, in both runs.
A retry is safe only when the failed request is the whole transaction. In Example 7, where each insert was its own transaction, a retry of every aborted insert brought all 400 of 400 rows in. For a multi-statement transaction, retry the whole transaction in the application, or send BT … ET as one multi-statement request.
How to avoid them
Every deadlock above has a measured fix. Each fix turned the deadlock into an ordinary wait of about 4 s.
| Deadlock | Fix | Lab result |
|---|---|---|
| Example 1 (two tables, opposite order) | Both take T1 first, then T2 | B waited 4.05 s, no deadlock |
| Examples 3 and 4 (two rows, opposite order) | Both update row 1 first | B waited 4.24 s / 4.03 s |
| Example 6 (ring of three) | All three lock in the order T1, T2, T3 | C waited 4.11 s, A 0.13 s |
| Example 2 and the stock order (read, then update) | LOCKING ROW FOR WRITE on the first SELECT |
B waited 3.28 s; stock 98, both orders counted |
| Example 5 (table read, then update) | LOCKING TABLE … FOR WRITE on the SELECT COUNT(*) |
B waited 4.10 s |
| Example 7 (fallback, staging load) | LOCKING TABLE staging FOR WRITE on each insert, or retry each single-row insert |
0 deadlocks, 400 of 400 rows / 18 deadlocks, all retried, 400 of 400 rows |
The rules behind the table:
- Take locks in one agreed order. Same tables, same rows, same sequence in every transaction.
- Ask for the strongest lock first. If you will update what you read, read it with
LOCKING ROW FOR WRITE(orLOCKING TABLE … FOR WRITE). The second transaction then waits before it holds anything, so no cycle can form.
BT;
LOCKING ROW FOR WRITE SELECT Qty FROM DL_Stock WHERE Item_Id = 42;
UPDATE DL_Stock SET Qty = Qty - 1 WHERE Item_Id = 42;
ET;
- Don’t wait at all, where waiting is worse than failing.
NOWAITreturns error 7423 at once if the lock is taken. On the lab a price job withLOCKING ROW FOR WRITE NOWAIT SELECT …failed after 0.01 s; without NOWAIT it waited 4.05 s.
LOCKING ROW FOR WRITE NOWAIT SELECT Price FROM DL_Stock WHERE Item_Id = 42;
-- 7423: Object TUNING_DEMO.DL_Stock is locked by another process and NOWAIT
- Retry whole transactions, never single statements (see the retry trap).
Find your own deadlocks
DBQL tells you that a request failed with 2631. It does not tell you why, which kind of deadlock it was, or who was on the other side. For that you need the lock log.
1. Switch on lock logging for the users concerned, before the deadlock happens:
REPLACE QUERY LOGGING WITH SQL, LOCK=5 ON <user>;
LOCK=5 logs every lock wait longer than 5 centiseconds, the smallest value our release accepted. The rows land in DBC.QryLockLogXMLV, one XML document per logged wait, with the flags LocalDeadLock, GlobalDeadLock or FallBackDeadLock, AbortFlag, the wait (LockDelay, in centiseconds), the table, the AMP, and both sessions with the lock type each held or requested.
2. Run find_deadlocks.sql (full listing at the end of this post) for a time window. It reads the XML, joins each deadlock to the victim’s 2631 in DBC.QryLogV, and prints three lists:
- each deadlock: kind, wait, AMP, table, blocker and victim session with their lock types, the victim’s statement;
- the statements of both sessions, from the start of the older transaction until the abort;
- as a check, 2631s in DBQL that have no lock-log row.
Part 1 on our lab, for the stock orders and the DeadLockTimeout demo (some columns left out):
WaitStart Kind WaitSec AmpNo TableName BlockerLock VictimLock AbortedAt VictimStmt
2026-11-28 16:48:24.62 local 13.67 2 DL_Stock Read Write 16:48:38.30 UPDATE DL_Stock SET Qty = Qty - 1 WHERE Item_Id = 42;
2026-11-28 16:51:39.22 local 29.07 2 DL_Stock Read Write 16:52:08.30 UPDATE DL_Stock SET Qty = Qty - 1 WHERE Item_Id = 42;
2026-11-28 16:58:44.55 global 327.99 2 DL_T1 Write Write 17:04:12.29 UPDATE DL_T1 SET Val = Val + 1 WHERE Id = 4;
2026-11-28 17:07:40.46 global 15.99 2 DL_T1 Write Write 17:07:56.38 UPDATE DL_T1 SET Val = Val + 1 WHERE Id = 4;
Read it like this: Read against Write on one row is the read-then-update deadlock; fix it with LOCKING ROW FOR WRITE. Write against Write is an opposite-order deadlock; part 2 shows the order in which each session took its locks. global with a wait of minutes means the cycle spanned AMPs and waited for DeadLockTimeout. fallback with 0.00 s points at a FALLBACK table loaded while another request locks it whole.
Part 2 for the first row, the stock order (the reset of the stock left out):
Side Started Answered Err Stmt
other 16:48:19.55 16:48:19.55 0 BT;
other 16:48:19.57 16:48:19.59 0 SELECT Qty FROM DL_Stock WHERE Item_Id = 42;
victim 16:48:21.54 16:48:21.54 0 BT;
victim 16:48:21.57 16:48:21.57 0 SELECT Qty FROM DL_Stock WHERE Item_Id = 42;
victim 16:48:24.61 16:48:38.30 2631 UPDATE DL_Stock SET Qty = Qty - 1 WHERE Item_Id = 42;
other 16:48:24.61 16:48:38.30 0 UPDATE DL_Stock SET Qty = Qty - 1 WHERE Item_Id = 42;
Both sessions read, both tried to update; the victim got 2631, and the other session’s update finished in the same hundredth of a second.
On our test window (four hours, 106 aborts with 2631) the script found 105 deadlocks: 16 local, 11 global and 78 fallback. Every wait matched the measurements above.
Three traps the script handles, found while testing it:
- Hundredths without a leading zero. The XML writes
…16:33:18.9for 18.09 s. Read naively as 18.90 s, it no longer matches DBQL. - Two clocks. The lock log’s
TransactionStartTimewas in the node’s local time (CET on our lab), DBQL in UTC. Set the offset in the script. - One deadlock, several rows. A deadlock can be logged on several AMPs; the script keeps one row per victim.
And one it reports rather than hides: the lock log can be late, or missing. It is written in batches (DBS Control LockLoggerFlushRate, 1200 s on our lab), and FLUSH QUERY LOGGING did not force the last rows out. One global deadlock on our lab, right after a database restart, still had no lock-log row 25 minutes later, although rows logged after it had arrived. Part 3 lists such aborts, so a deadlock never disappears from the report; for those you have DBQL only.
Summary
- A deadlock is a cycle of waits. The two shapes behind every case on our lab: locks taken in opposite order, and two readers that both upgrade to write.
- Local deadlocks (one AMP) end within 30 s, globally spread ones wait for DeadLockTimeout (240 s by default, changeable, active only after a restart), fallback deadlocks end at once.
- The victim is not always the younger transaction, and BTEQ’s default retry can commit half of it.
- Fix: one lock order, the strongest lock first, NOWAIT where failing is better than waiting, and retries of whole transactions.
- Switch on lock logging now, so that the next deadlock tells you what it was.
The script
Set the two timestamps and the clock offset in DL_Window, then run it in BTEQ or any SQL client, as a user with SELECT on DBC.QryLogV and DBC.QryLockLogXMLV.
-- find_deadlocks.sql: which deadlocks happened in a time window, what kind they were,
-- who blocked whom, and which statements of both sessions were involved.
--
-- Needs, before the deadlock happens: DBQL with lock logging for the users concerned, e.g.
-- REPLACE QUERY LOGGING WITH SQL, LOCK=5 ON <user>;
-- Run as a user with SELECT on DBC.QryLogV and DBC.QryLockLogXMLV.
-- The lock log is written in batches (DBS Control LockLoggerFlushRate, 1200 s on the lab), so a
-- deadlock can be missing from part 1 for up to that long; part 3 then lists it.
-- Edit the two timestamps in DL_Window (DBQL time = the system's time, UTC on the lab).
-- The lock log writes hundredths without a leading zero ("12:00:18.9" is 18.09 s); the script pads them.
-- LockLogOffset: the lock log's TransactionStartTime is in the node's local time; set how far it is
-- ahead of DBQL time (1 hour on the lab: CET against UTC). Statements are listed from the start of the
-- older of the two transactions until the victim's 2631.
FLUSH QUERY LOGGING WITH ALL;
CREATE VOLATILE TABLE DL_Window AS (
SELECT TIMESTAMP '2026-11-28 14:00:00' AS FromTs,
TIMESTAMP '2026-11-28 18:00:00' AS ToTs,
INTERVAL '01:00' HOUR TO MINUTE AS LockLogOffset
) WITH DATA ON COMMIT PRESERVE ROWS;
-- One row per logged lock wait, with the deadlock flags and both sessions taken from the XML.
CREATE VOLATILE TABLE DL_Waits AS (
SELECT x.QueryID,
x.Txt,
CAST(REGEXP_REPLACE(OREPLACE(REGEXP_REPLACE(REGEXP_SUBSTR(x.Txt, 'DelayStartTime="[^"]+"'), '^.*="|"', ''), 'T', ' '),
'\.([0-9])$', '.0\1') AS TIMESTAMP(2)) AS WaitStart,
CAST(REGEXP_REPLACE(OREPLACE(REGEXP_REPLACE(REGEXP_SUBSTR(x.Txt, 'TransactionStartTime="[^"]+"', 1, 1), '^.*="|"', ''), 'T', ' '),
'\.([0-9])$', '.0\1') AS TIMESTAMP(2)) AS BlockerTxStart,
CAST(REGEXP_REPLACE(OREPLACE(REGEXP_REPLACE(REGEXP_SUBSTR(x.Txt, 'TransactionStartTime="[^"]+"', 1, 2), '^.*="|"', ''), 'T', ' '),
'\.([0-9])$', '.0\1') AS TIMESTAMP(2)) AS BlockedTxStart,
CAST(REGEXP_REPLACE(REGEXP_SUBSTR(x.Txt, 'LockDelay="[0-9]+"'), '[^0-9]', '') AS INTEGER) / 100.00 AS WaitSec,
CASE WHEN x.Txt LIKE '%LocalDeadLock="true"%' THEN 'local'
WHEN x.Txt LIKE '%GlobalDeadLock="true"%' THEN 'global'
WHEN x.Txt LIKE '%FallBackDeadLock="true"%' THEN 'fallback'
ELSE 'blocking only' END AS Kind,
CASE WHEN x.Txt LIKE '%AbortFlag="TRUE"%' THEN 'yes' ELSE 'no' END AS Aborted,
CAST(REGEXP_REPLACE(REGEXP_SUBSTR(x.Txt, 'SessionID_Combined="[0-9]+"', 1, 1), '[^0-9]', '') AS INTEGER) AS BlockerSession,
CAST(REGEXP_REPLACE(REGEXP_SUBSTR(x.Txt, 'SessionID_Combined="[0-9]+"', 1, 2), '[^0-9]', '') AS INTEGER) AS BlockedSession,
CAST(REGEXP_REPLACE(REGEXP_SUBSTR(x.Txt, 'LockTypeRequested="[A-Za-z0-9]+"', 1, 1), '^.*="|"', '') AS VARCHAR(10)) AS BlockerLock,
CAST(REGEXP_REPLACE(REGEXP_SUBSTR(x.Txt, 'LockTypeRequested="[A-Za-z0-9]+"', 1, 2), '^.*="|"', '') AS VARCHAR(10)) AS BlockedLock,
CAST(REGEXP_REPLACE(REGEXP_SUBSTR(x.Txt, 'TableName="[^"]+"', 1, 1), '^.*="|"', '') AS VARCHAR(128)) AS TableName,
CAST(REGEXP_REPLACE(REGEXP_SUBSTR(x.Txt, ' vproc="[0-9]+"', 1, 1), '[^0-9]', '') AS INTEGER) AS AmpNo
FROM (SELECT QueryID, CollectTimeStamp, CAST(SUBSTR(XMLTextInfo, 1, 30000) AS VARCHAR(30000)) AS Txt
FROM DBC.QryLockLogXMLV) x
CROSS JOIN DL_Window w
WHERE x.CollectTimeStamp BETWEEN w.FromTs AND w.ToTs + INTERVAL '1' HOUR
) WITH DATA ON COMMIT PRESERVE ROWS;
-- The victim's aborted request in DBQL: the 2631 request of the blocked session that was running when
-- the lock wait began. A deadlock can be logged on several AMPs; it is kept once.
CREATE VOLATILE TABLE DL_Deadlocks AS (
SELECT d.*, v.QueryID AS VictimQueryID, v.FirstRespTime AS AbortedAt,
CAST(SUBSTR(v.QueryText, 1, 70) AS VARCHAR(70)) AS VictimStmt
FROM DL_Waits d
JOIN DBC.QryLogV v
ON v.SessionID = d.BlockedSession AND v.ErrorCode = 2631
AND v.StartTime <= d.WaitStart + INTERVAL '0.01' SECOND -- the request was running when the wait began
AND v.FirstRespTime >= d.WaitStart
WHERE d.Kind <> 'blocking only' AND d.Aborted = 'yes'
QUALIFY ROW_NUMBER() OVER (PARTITION BY v.QueryID ORDER BY d.WaitStart) = 1 -- one row per deadlock
) WITH DATA ON COMMIT PRESERVE ROWS;
-- 1. The deadlocks: kind, wait, who blocked whom (one row per deadlock: the victim's wait).
SELECT WaitStart, Kind, WaitSec, AmpNo, CAST(TableName AS VARCHAR(30)) AS TableName,
BlockerSession, BlockerLock, BlockedSession AS VictimSession, BlockedLock AS VictimLock,
CAST(CAST(AbortedAt AS FORMAT 'HH:MI:SS.S(2)') AS CHAR(11)) AS AbortedAt, VictimStmt
FROM DL_Deadlocks
ORDER BY 1;
-- 2. The statements of both sessions, from the start of the older transaction until the victim's 2631.
SELECT d.WaitStart AS Deadlock,
CASE WHEN q.SessionID = d.BlockedSession THEN 'victim' ELSE 'other' END AS Side,
q.SessionID,
CAST(CAST(q.StartTime AS FORMAT 'HH:MI:SS.S(2)') AS CHAR(11)) AS Started,
CAST(CAST(q.FirstRespTime AS FORMAT 'HH:MI:SS.S(2)') AS CHAR(11)) AS Answered,
q.ErrorCode AS Err,
CAST(SUBSTR(q.QueryText, 1, 70) AS VARCHAR(70)) AS Stmt
FROM DL_Deadlocks d
CROSS JOIN DL_Window w
JOIN DBC.QryLogV q
ON q.SessionID IN (d.BlockerSession, d.BlockedSession)
AND q.StartTime BETWEEN CASE WHEN d.BlockerTxStart < d.BlockedTxStart THEN d.BlockerTxStart ELSE d.BlockedTxStart END
- w.LockLogOffset - INTERVAL '0.10' SECOND
AND d.AbortedAt
WHERE q.QueryText NOT LIKE 'SET QUERY_BAND%'
ORDER BY 1, q.StartTime, q.SessionID;
-- 3. Check: deadlock aborts (2631) in DBQL that have no lock-log row above, e.g. because lock logging
-- was off for that user or the lock logger has not written its batch yet.
SELECT CAST(CAST(v.StartTime AS FORMAT 'HH:MI:SS.S(2)') AS CHAR(11)) AS Started, v.SessionID, v.UserName,
CAST(SUBSTR(v.QueryText, 1, 70) AS VARCHAR(70)) AS Stmt
FROM DBC.QryLogV v CROSS JOIN DL_Window w
WHERE v.ErrorCode = 2631 AND v.StartTime BETWEEN w.FromTs AND w.ToTs
AND v.QueryID NOT IN (SELECT VictimQueryID FROM DL_Deadlocks)
ORDER BY v.StartTime;
DROP TABLE DL_Deadlocks;
DROP TABLE DL_Waits;
DROP TABLE DL_Window;
Need help with query performance or platform costs?
Diagnose plans, skew, spool pressure and expensive workloads. Agree a baseline and acceptance criteria before making changes.
Get the complete Teradata tuning book, free
Teradata Query Performance Tuning: The DWHPro Guide
By Roland Wenzlofsky & Artemios Vogiatzis
206 pages on statistics and demographics, access paths and indexes, query execution plans, and joins. Get the full PDF and practical Teradata updates from DWHPro.
Confirm your email to receive your download link. Privacy policy. Unsubscribe in any newsletter.
About the free book