Removing Permanent and Temporary Tables with SQL DROP

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

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

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

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.

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 Removing Permanent and Temporary Tables with SQL DROP

What does DROP TABLE IF EXISTS do?
DROP TABLE IF EXISTS removes the table when it exists and skips it without an error when it does not. It does not check that you typed the intended name: DROP TABLE IF EXISTS stgae; leaves the real table stage untouched, and a valid wrong name drops another table. MySQL records a note for a skipped table, visible through SHOW WARNINGS, and SQL Server supports IF EXISTS from version 2016. Afterward, list the tables to confirm the result.
Can you roll back a DROP TABLE statement?
Yes in some systems, but only before COMMIT. In SQLite and SQL Server, a DROP TABLE inside an open transaction can be undone with ROLLBACK, which restores the table and its rows. In MySQL, an ordinary DROP TABLE causes an implicit commit, so ROLLBACK cannot bring it back. After any committed drop, recovery depends on a saved copy or a database backup, and a quick data copy may not keep the table's indexes, keys or triggers.
How do you drop a temporary table in MySQL and SQL Server?
In MySQL, use DROP TEMPORARY TABLE low_stock; which targets only temporary tables, so it cannot remove a permanent table by accident. In SQL Server, drop a local temporary table by its hash-prefixed name, as in DROP TABLE #low_stock; Temporary tables also disappear when their connection ends, and a SQL Server local temporary table created in a stored procedure is dropped when the procedure finishes. Dropping early frees the name and resources sooner.
In what order should you drop tables linked by foreign keys?
Drop child tables before the parent tables they reference. If order_items references orders and products, and orders references customers, a safe order is order_items, then orders, then customers and products. SQL Server has no DROP TABLE CASCADE clause, and MySQL accepts CASCADE but ignores it. If a child table must stay, drop its foreign key first. Turning off MySQL foreign key checks to force a drop can leave broken relationships.

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 →