Clearing Tables with SQL TRUNCATE Table, Explained

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

← 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 →

Earn 3 college credits for Database ProgrammingRecommended for credit by NCCRS · Computer Science 381 · self-paced · one payment, lifetime access

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.

Compare: Database Fundamentals vs Database Programming

Why take it here

Why students take Database Programming with UPI Study

Write the SQL behind every appDatabase Programming teaches SQL in MySQL and SQL Server side by side: designing and normalizing tables, keys and constraints, data types, inserting, updating and deleting rows, filtering, grouping, joins, subqueries, views, indexes, transactions, and protecting data from SQL injection. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

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.

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?
TRUNCATE TABLE removes every row while keeping the table's columns, keys, constraints and indexes, but it accepts no WHERE clause. DELETE can remove selected rows, such as DELETE FROM orders WHERE order_date < '2025-01-01'. In MySQL and SQL Server, TRUNCATE usually records less work, restarts automatic numbering and does not fire delete triggers, so the two commands are not interchangeable.
Can you roll back a TRUNCATE TABLE statement?
It depends on the database. In SQL Server, TRUNCATE TABLE inside an explicit transaction can be rolled back, restoring the rows. In MySQL, TRUNCATE causes an implicit commit, so a later ROLLBACK cannot recover the data, although a DELETE on an InnoDB table can be rolled back before COMMIT. SQLite has no TRUNCATE statement. When the engine cannot undo it, plan recovery from a backup or the retained source data.
Does TRUNCATE reset the auto-increment or identity counter?
Yes, in MySQL and SQL Server. TRUNCATE restarts MySQL's AUTO_INCREMENT counter and returns SQL Server's IDENTITY to its seed, so an identity seeded at 100 next generates 100. DELETE does not reset these counters: after deleting rows 1 to 5, the next value is normally 6. Resetting after a DELETE is a deliberate task, using ALTER TABLE ... AUTO_INCREMENT in MySQL or DBCC CHECKIDENT with RESEED in SQL Server.
Why does TRUNCATE TABLE fail on a table referenced by a foreign key?
In MySQL InnoDB and SQL Server, TRUNCATE is refused when another table has a foreign key referencing the target, even if that child table is empty. A self-referencing foreign key is the exception. TRUNCATE also needs more than delete rights: MySQL requires the DROP privilege and SQL Server requires ALTER permission on the table. Use a DELETE that satisfies the foreign keys rather than disabling constraint checks.

About the Database Programming course

How many college credits is Database Programming?
Database Programming (Computer Science 381) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Database Programming cost and what is included?
$250, paid once, with lifetime access: all 76 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Database Programming take?
It is self-paced with no deadlines. The 76 lessons total about 11 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

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

Database Programming
3 credits · NCCRS
Enroll →