Senior
There is a large table, and you need to update the 'status' column from 'Enable' to 'Active'. How would you do this?
sobes.tech AI
Answer from AI
To update the status column from 'Enable' to 'Active' in a large table, it is important to consider performance and minimize locking.
If the database supports transactions and indexes on the status column, a simple SQL query can be executed:
UPDATE table_name
SET status = 'Active'
WHERE status = 'Enable';
However, if the table is very large, such a query may cause long locks and system load. In this case, it is better to:
- Perform the update in parts, for example, updating 1000-10000 rows at a time using LIMIT and OFFSET or by ID.
- Use transactions for each part to avoid long lock durations.
- Check for an index on the
statuscolumn to speed up the search.
Example of updating in parts (pseudo-code):
-- Assume there is a unique ID
DECLARE @batchSize INT = 10000;
DECLARE @minId INT = (SELECT MIN(id) FROM table_name WHERE status = 'Enable');
DECLARE @maxId INT = (SELECT MAX(id) FROM table_name WHERE status = 'Enable');
WHILE @minId IS NOT NULL AND @minId <= @maxId
BEGIN
UPDATE TOP (@batchSize) table_name
SET status = 'Active'
WHERE status = 'Enable' AND id >= @minId;
SET @minId = (SELECT MIN(id) FROM table_name WHERE status = 'Enable' AND id > @minId);
END
This approach allows controlling the load and avoiding long locks.