The TRUNCATE TABLE command deletes all rows of a table without causing any triggered action. Unlike the DELETE command it contains no WHERE clause to specify individual rows.
With respect to the TRUNCATE TABLE command most DBMS show significant better performance than with DELETE command. This results from the facts the DBMS can empty the table (and its indexes) as a whole. It's not necessary to access individual rows.
'TRUNCATE TABLE t2'will fail. This holds true independent from the question whether any row of t1 refers actually to one of the rows of t2 or not. The DBMS checks only the existence of the Forgeign-Key-constraint definition.
The syntax of the TRUNCATE TABLE command is very simple.
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.
To illustrate the difference between the TRUNCATE TABLE command and the DELETE command (without a WHERE clause) one can imagine a trucker, who wants to empty a trailer full of sand at a construction site. To do so he has two possibilities; either empty the trailer by tilting it - this corresponds to the TRUNCATE TABLE command, or climb onto the trailer and throw down one grain of sand after the next - this corresponds to the DELETE command.
Delete all rows of table 'person_hobby' using the DELETE command.
Verify that there are no rows left in 'person_hobby'.
Delete all rows of table 'hobby' using the TRUNCATE TABLE command.
What will happen? (Consider that there is an FK constraint from the table empty 'person_hobby' to 'hobby'.)
-- 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.
What will happen in the above example, if the TRUNCATE TABLE command is replaced by a DELETE command?
-- As there is no row in 'person_hobby' referring to 'hobby', the DELETE command deletes all rows in 'hobby'. DELETE FROM hobby; COMMIT;
The original data of the example database can be reconstructed as shown on the example database data page.
Manage research, learning and skills at IT1me. Create an account using LinkedIn to manage and organize your IT knowledge. IT1me works like a shopping cart for information -- helping you to save, discuss and share.