UPI Study › Courses › Database Programming › Free lessons › Lesson 10.3 Free with a free account
Removing Permanent and Temporary Tables with SQL DROP
Database Programming · Chapter 10: Table Cleanup and Structural ChangesSection 10.3 · lesson 62 of 7610 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: Dropping Indexes and Databases: Steps and Examples →← Removing Constraints with SQL DROP ConstraintNext lesson: Dropping Indexes and Databases: Steps and Examples →
A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →
In this lesson
Drop permanent and temporary tables safely and in the right order.
- Use DROP TABLE and IF EXISTS while confirming the exact target
- Explain how temporary tables differ in scope from permanent tables
- Order table drops so child tables go before the parents they reference
- Choose among DELETE, TRUNCATE and DROP for a cleanup task
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,129 words). Read along, or search it.
Opening Scenario
An Abandoned Archive and a Scratch Report
Amina Diallo, Lantern Books' database administrator, finds an abandoned product archive and a temporary low-stock report. Both look like tables, but their lifetimes differ. She needs to remove scratch work, while preserving the reusable structure that tomorrow's import expects to use. Should she remove selected rows, empty a table, or remove its definition? Choosing the scope comes before choosing the command.
Permanent Tables
Products That Outlive the Connection
Our disposable product table holds canonical bookstore rows. Its definition persists after this shell connection finishes. A permanent table lasts until removed. Other sessions can access it with permission; permanent does not mean protected against dropping. Run the setup. We will copy this data for demonstrations, leaving the product table available throughout the lesson.
Recovery Copy
Save the Archive Before Retiring It
Create an illustrative archive and a recovery copy. Both retain product data, without reproducing the complete source schema. Indexes, triggers, foreign keys, and other rules need separate preservation. A real recovery plan includes an independently stored backup and a tested restore. Run the copies and count saved records. Equal counts alone do not prove complete recovery; verify identities and usable content too. Eight rows were saved. The live products remain separate, so retiring the archive need not remove the bookstore's working inventory.
Transactional Drop
Rolling Back DROP TABLE in SQLite
Drop table removes the definition, all rows, and owned indexes, triggers, and constraints. Dependent objects outside the table still require investigation. In SQLite, this ordinary table drop is inside an explicit transaction. Rolling back before commit restores the archive and its contents. Run this demonstration. It tests recovery while the transaction is open, not recovery from an already committed deletion. The archive query succeeds with eight rows. SQL Server also supports transactional table drops; ordinary MySQL drop table instead causes an implicit commit.
IF EXISTS
Drop the Archive and Confirm Absence
Now retire the archive outside an explicit transaction. If exists suppresses the error when the named table is already absent. It does not verify the name or the database. A typo can quietly skip the intended cleanup, and a valid wrong name can remove another table. Run the drop and inspect metadata plus the backup. An absence check tests the definition, rather than merely observing an empty query result. The archive definition is absent, while eight backup rows remain. After a committed drop, recovery requires a usable saved copy or database backup.
Server Syntax
Permanent Table Drops on Both Servers
Both servers accept a plain table drop, and can list multiple table names. MySQL reports a warning when if exists skips an absent table. SQL Server supports if exists from twenty sixteen. Earlier versions can test object identity first; the letter U requests a user table. SQL Server's select into makes a quick data copy. MySQL uses create table as select; neither should be mistaken for preserving every source object.
Temporary Tables
A Low-Stock Report Owned by One Connection
A local temporary table belongs to a connection. This SQLite scratch report selects the bookstore products with fewer than six units in stock. Separate sessions can use the same temporary name without sharing rows. SQL Server local temporary tables use a leading hash; global temporary tables have different scope. Run this file in a fresh shell connection. It creates and reads the scratch table before that connection closes. The report contains Biology Guide and Reading Lamp, identified by their product numbers. Once this connection ends, its temporary table goes away.
Session Scope
A New Connection Cannot See It
A new shell connection cannot see the previous connection's temporary report. It can still read permanent products. A session means one database connection. Connection pools can keep sessions alive beyond one application request. Run both queries. The temporary-name count distinguishes absence from an empty temporary table. Zero temporary definitions and eight permanent rows confirm the scope difference. Use permanent storage whenever the result must reliably survive the creating connection.
Temporary Table Syntax
DROP TEMPORARY TABLE and Hash-Prefixed Names
MySQL creates temporary tables with the temporary keyword. Drop temporary table specifically targets temporary objects, protecting a permanent table from an accidental ordinary drop. SQL Server drops a local temporary table using its hash-prefixed name. A procedure-created local temporary table can disappear when that procedure finishes. Dropping scratch work early frees its name and resources. MySQL temporary create and drop do not implicitly commit, but those operations cannot be rolled back.
Drop Order
Child Tables Before Parent Tables
For the complete bookstore schema, order items reference both orders and products. Orders also reference customers, so those parent definitions have inbound dependencies. A safe retirement order is order items, then orders, then customers and products. Once a child is dropped, its outgoing foreign key disappears. If child data must stay, redesign or remove the foreign key before dropping the parent. Turning off MySQL foreign key checks can leave broken relationships.
Quick Check
A Misspelled Name Skipped Silently
A fresh import cleanup creates stage, then drops stgae with if exists. What will the final count report? Pause, and predict. It counts one saved row. Run the script: the absent misspelled name is skipped, leaving stage untouched. The declaration and drop target different names. If exists avoids a missing-object error, which makes checking the final object list especially important.
No Cascade Clause
Child-First Removal on Each Server
These server listings show child-first removal. The alternate foreign-key statements apply when orders must survive and the relationship is deliberately being retired. SQL Server has no drop table cascade clause; MySQL accepts cascade but ignores it. Do not confuse this with cascading row deletion. SQLite differs again: dropping a referenced table performs an implicit deletion and can invoke foreign key actions. Our server dependency advice is explicitly about those servers.
Choosing a Command
DELETE, TRUNCATE or DROP
Delete removes selected rows, or all rows without a filter, while retaining structure. It retains numbering state and fires applicable delete triggers; transactional deletion remains reversible until commit. Truncate empties a supported server table without a where clause, normally resets identity, and bypasses delete triggers. Referencing foreign keys can block it; SQLite has no truncate statement. Drop removes the structure too. SQL Server can roll back ordinary truncate and drop inside a transaction; MySQL's ordinary versions commit implicitly, unlike transactional InnoDB delete.
Final Check
Rollback Undoes Both Delete and Drop
A new scratch task combines a filtered delete and a table drop inside one SQLite transaction. The creation and original inserts occur before begin. After rollback, what does the final query do? Choose two rows, zero rows, or a missing-table error. Pause, and predict. It counts two existing rows. Run the script: both the deletion and the drop belong to the transaction that is rolled back. The rollback restores the definition and the deleted row. The original table and inserts predate begin, so they remain. Zero would describe losing the rows while retaining structure. A missing-table error would describe a committed drop; neither matches this SQLite transaction.
Key Takeaways
Match the Command to the Scope
Amina preserves tomorrow's import structure and retires the abandoned archive. Local reports expire with their connection, while durable results require permanent storage. Resolve inbound foreign keys, confirm exact targets, and verify a recovery copy. If exists handles absence, without establishing that the chosen target is correct. Match delete, truncate, or drop to the intended scope. Timings and storage reclamation vary; know transaction rules before relying on rollback.
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 Removing Permanent and Temporary Tables with SQL DROP
What does DROP TABLE IF EXISTS do?
Can you roll back a DROP TABLE statement?
How do you drop a temporary table in MySQL and SQL Server?
In what order should you drop tables linked by foreign keys?
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 →