High-Performance Strategies for Deleting Millions of Rows Based on ID
Removing millions of database rows can be incredibly time-consuming. This guide details optimal methods for efficiently deleting these rows using their IDs.
Key Optimization Techniques
VACUUM
and ANALYZE
commands help maintain database metadata and improve query efficiency. Running these before the deletion operation can yield significant performance gains.Code Examples
Utilizing a Temporary Table:
<code class="language-sql"> -- Create a temporary table to hold rows to keep CREATE TEMP TABLE tmp AS SELECT t.* FROM tbl t LEFT JOIN del_list d USING (id) WHERE d.id IS NULL; -- Remove all rows from the original table TRUNCATE tbl; -- Repopulate the original table with the retained rows INSERT INTO tbl SELECT * FROM tmp;</code>
Direct Deletion with Foreign Key Considerations:
<code class="language-sql"> DELETE FROM tbl t USING del_list d WHERE t.id = d.id AND NOT EXISTS (SELECT 1 FROM related_table WHERE id = t.id);</code>
Important Considerations
The above is the detailed content of How to Efficiently Delete Millions of Rows from a Database by ID?. For more information, please follow other related articles on the PHP Chinese website!