UPI Study › Courses › Database Programming › Free lessons › Lesson 7.2 Free with a free account
Clearing Tables with SQL TRUNCATE Table
Database Programming · Chapter 7: Text Operations and Practical Data ManipulationSection 7.2 · lesson 41 of 769 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Database Programming.
Lesson complete
Earn the 3 college credits for Database Programming
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Understanding SQL Joins — Core Concepts and Inner Join Fundamentals →← Trimming Text with SQL TRUNCATE StringNext lesson: Understanding SQL Joins — Core Concepts and Inner Join Fundamentals →
A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →
In this lesson
How TRUNCATE TABLE differs from DELETE in rollback, numbering and permissions.
- Explain how TRUNCATE TABLE removes every row while keeping the table definition
- Compare TRUNCATE and DELETE on WHERE conditions, rollback, logging and identity numbering
- Identify foreign key, permission and trigger rules that block or change a truncate
- Choose between TRUNCATE and DELETE for a given reset job
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (1,100 words). Read along, or search it.
Opening Problem
Clearing a Staging Table Before a Reload
Amina Diallo, Lantern Books' database administrator, must clear an import staging table before a fresh load. Developer Leo Park suggests deleting everything. Would truncate be a better choice? Before choosing, Amina needs to know what stays, what resets, and whether a mistake can be undone. This is a disposable import copy. The bookstore's live customer and order records are not the target.
Definition
TRUNCATE TABLE Keeps the Table Definition
Truncate table removes every row, while preserving the table's definition. This simple form names the table and ends with a semicolon. There is no where condition. If only last year's orders should go, use delete with a predicate instead. The columns, keys, constraints, and indexes remain available. New rows can be inserted without recreating the schema yourself. SQL Server also supports partition-specific truncation. We are using the whole-table form here. This is a non-run listing: SQLite has no truncate table statement. Its runnable examples will demonstrate delete, without pretending that the two commands are identical.
Count First
Confirm the Target and Its Row Count
First establish the target. This SQLite sandbox contains a disposable subset of our course orders, with their original identifiers and dates. Count before clearing if the removal count matters. MySQL's usual zero-rows-affected message for truncate does not mean the table originally contained zero rows. Run the count. Three rows are present. SQL Server's success message likewise should not be treated as a deleted-row count. Confirm the database and table name before a bulk reset. An accurate count on the wrong table is still the wrong operation.
SQLite Demonstration
DELETE Inside a Transaction Rolls Back
Now watch a real SQLite delete inside an explicit transaction. The table starts with the same three order identifiers. Delete without where clears all rows. The first count is taken before rollback; the second count is taken afterward. Run the file. Zero rows remain immediately after deletion, and rollback restores all three. We did not commit the deletion. The table definition survives delete too. This demonstration proves SQLite's transaction behavior; it does not prove how another engine handles truncate.
Dialect Difference
Rollback After TRUNCATE Depends on the Engine
For truncate, the engine changes the answer. SQL Server allows truncate inside an explicit transaction, and rollback can restore the rows. In MySQL, truncate causes an implicit commit. Wrapping it in start transaction and rollback does not recover the removed rows. The comments describe documented behavior; no server transcript is being simulated here. MySQL's transactional delete can roll back when using InnoDB. Choose the command and transaction boundary together. A rollback written after a statement is not a universal undo guarantee.
Logging and Speed
Why TRUNCATE Usually Records Less Work
Why use truncate for a reload? In these server engines, a bulk reset usually records less work than individual row deletions. SQL Server releases data pages and records deallocation in the transaction log. Some physical cleanup can occur after commit. MySQL recreates the table and logs truncate as a table-definition operation. Logging still happens; it is not an unlogged eraser. SQLite can optimize an unqualified delete when conditions permit. Avoid turning these implementation differences into a promise about every database or table size.
Auto Numbering
TRUNCATE Restarts Identity Numbering
Automatic numbering is another difference. Imagine separate sandbox tables, each previously assigned identifiers one through five, with seed and increment one. Delete does not reset these server counters. The next generated identifier is six, even after every existing row is removed. Truncate restarts MySQL auto increment and SQL Server identity numbering. For the default example, the next identifier is one. SQL Server actually returns to the configured seed. If that seed is one hundred, the next identifier is one hundred. Our real shop orders use explicit identifiers, not this sandbox counter. Do not reuse old business identifiers merely to make a sequence look tidy.
Reseeding
Resetting a Counter Deliberately
Reseeding means explicitly resetting a numbering counter. These non-run examples apply only to an emptied sandbox with the stated numbering rules. MySQL uses alter table with auto increment. SQL Server uses DBCC CHECKIDENT, with reseed. After delete in this seed-one example, reseeding to zero makes the following generated value one. Other identity states and increments require different reasoning. Existing rows and references matter. Reseeding is a deliberate administration task, not a required follow-up to every delete.
Foreign Keys
Referenced Parent Tables Block TRUNCATE
A foreign key connects a child row to a parent key. Our orders refer to customers, and order items refer to orders. In MySQL InnoDB and SQL Server, another table's foreign key blocks truncating the referenced parent. Even an empty child table still has that constraint. A self-referencing foreign key is an exception. But emptiness alone is not permission to truncate a parent referenced elsewhere. Delete may be an alternative, provided it satisfies the foreign keys and cascade rules. It is not a way to ignore referential integrity. Changing constraints requires a planned migration that preserves and rechecks relationships. Do not casually disable foreign-key checks to force a reset.
Permissions and Triggers
DROP or ALTER Rights and Skipped Triggers
An account allowed to delete rows may still lack permission to truncate. Check the required privilege before designing the reset job. Delete requires delete permission. MySQL requires drop privilege for truncate; SQL Server requires alter permission on the table. Delete triggers do not fire for truncate in these server engines. If row-deletion auditing depends on those triggers, the reset needs a different design. Other engine-specific restrictions can also block truncation. Confirm the actual table's features, relationships, and permissions before scheduling the load.
Quick Check
Counts Before and After Rollback
Try a fresh sandbox using three course products. Their stock counts are twelve, eight, and thirty, as shown in the insert. The delete selects stock at most eight. What counts appear before and after rollback, in that order? Pause, and predict. Two, then three. Only the product with stock eight qualifies, and the uncommitted deletion is then undone. Run it to verify both counts. Two then two would ignore rollback; three then two reverses the effects of deletion and recovery. A whole-table truncate could not express that stock condition. Scope and transaction behavior are separate decisions.
Applying the Choice
A Safe Reset Plan for the Staging Table
Back to Amina and Leo. Their staging table holds replaceable import data, so a bulk reset can make sense after checking dependencies and permissions. If the job runs on MySQL, they cannot rely on rollback after truncate. Their recovery plan must use the retained source or another suitable backup. If only selected rows should go, they use delete with a verified condition. If deletion triggers provide required auditing, they account for that too. The choice follows the data's purpose and the engine's behavior. Faster clearing is useful only when the reset is correct.
Key Takeaways
Check Rollback, Numbering and Dependencies
Truncate clears the target rows while retaining the table definition. Its simple form has no where condition. Check the engine's rollback and numbering rules. Do not assume that every database resets and recovers the same way. Confirm foreign keys, permissions, and trigger requirements. Count first when needed, and verify the intended target before clearing.
About Database Programming at UPI Study
Database Programming (Computer Science 381) is a self-paced online course of 76 video lessons in 12 chapters, from database applications, SQL setup, schema planning and normalization to keys and constraints, data types, filtering and sorting, joins, subqueries, views, indexes, ROLLUP and PIVOT, regular expressions and database security. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus All Computer Science courses Every credit course with PRO →
Why take it here
Why students take Database Programming with UPI Study
Where the credit goes
Universities that work with NCCRS
Database Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Clearing Tables with SQL TRUNCATE Table
What is the difference between TRUNCATE TABLE and DELETE in SQL?
Can you roll back a TRUNCATE TABLE statement?
Does TRUNCATE reset the auto-increment or identity counter?
Why does TRUNCATE TABLE fail on a table referenced by a foreign key?
About the Database Programming course
How many college credits is Database Programming?
How much does Database Programming cost and what is included?
Which universities accept UPI Study credits?
How long does Database Programming take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Database Programming.
76 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
Updated
3 credits · NCCRSEnroll →