結構化查詢語言/TRUNCATE
外觀
< 結構化查詢語言
TRUNCATE TABLE 命令刪除表中的所有行,不會觸發任何操作。與 DELETE 命令不同,它不包含 WHERE 子句來指定單個行。
關於 TRUNCATE TABLE 命令,大多數 DBMS 表現出比 DELETE 命令明顯更好的效能。這是因為 DBMS 可以清空整個表(及其索引),而無需訪問單個行。
- 根據定義,沒有 WHERE 子句。
- 根據定義,不會啟動任何觸發操作。
- 事務鎖定整個表。
- 如果存在從表 t1 到 t2 的外部索引鍵約束,則命令
'TRUNCATE TABLE t2'將失敗。這與 t1 中的任何行是否實際引用 t2 中的任何行無關。DBMS 只檢查 Forgeign-Key-constraint 定義的存在性。
TRUNCATE TABLE 命令的語法非常簡單。
TRUNCATE TABLE <tablename>;
-- Delete ALL rows of the table 'myTable'
TRUNCATE TABLE myTable;
-- In most DBMS ROLLBACK is not possible - in opposite to situations with a DELETE command.
為了說明 TRUNCATE TABLE 命令和 DELETE 命令(不帶 WHERE 子句)之間的區別,可以想象一個卡車司機,他想要清空一個裝滿沙子的拖車到一個建築工地。為此,他有兩種選擇:要麼傾斜拖車來清空它——這對應於 TRUNCATE TABLE 命令——,要麼爬上拖車,一次一粒地扔下沙子——這對應於 DELETE 命令。
使用 DELETE 命令刪除表 'person_hobby' 中的所有行。
驗證 'person_hobby' 中是否沒有剩餘的行。
使用 TRUNCATE TABLE 命令刪除表 'hobby' 中的所有行。
會發生什麼?(考慮到表 'person_hobby' 到 'hobby' 有一個 FK 約束。)
點選檢視解決方案
-- Delete all rows of 'person_hobby' with a DELETE command
DELETE FROM person_hobby;
COMMIT;
-- Are there any rows?
SELECT count(*) FROM person_hobby;
-- Try TRUNCATE TABLE command:
TRUNCATE TABLE hobby;
-- An exception will be thrown. Although there is no row in 'person_hobby' referring a row in 'hobby',
-- the definition of the Foreign Key constraint exists. This is the reason for the exception.
如果將上面的示例中 TRUNCATE TABLE 命令替換為 DELETE 命令,會發生什麼?
點選檢視解決方案
-- As there is no row in 'person_hobby' referring to 'hobby', the DELETE command deletes all rows in 'hobby'.
DELETE FROM hobby;
COMMIT;
示例資料庫的原始資料可以如示例資料庫資料頁面所示重建。