Lesson 15

Drop tables

Over a database lifetime, some tables created earlier become obsolete due to changing analysis needs. Carrying forward unused tables reduces maintainability. SQL enables easily dropping existing tables via the DROP TABLE command. Using IF EXISTS makes this operation safer.

The DROP TABLE statement permanently deletes a table and associated data/indexes. Basic syntax:

DROP TABLE table_name;

However this errors if the table does not exist already. The IF EXISTS clause fixes this:

DROP TABLE IF EXISTS table_name;

Now the statement quietly does nothing if the table is missing.

For example to remove an obsolete products table:

DROP TABLE IF EXISTS products;

Some key points about dropping tables:

Data Loss

DROP TABLE permanently deletes all table data. Retrieve data first if required.

Remove Dependencies

If other tables reference this one via foreign keys or constraints, remove those references first.

Recovery Needs Restore

No automated recovery. Restoring a backup is the only option.

Careful Privilege Granting

Allow DROP TABLE cautiously - enables deleting valuable tables.

For example, removing a deprecated pricing table:

ALTER TABLE orders
DROP FOREIGN KEY fk_order_pricing;

DROP TABLE IF EXISTS pricing;

Here we first delete the pricing table's relationship with orders by removing the foreign key constraint before dropping.

Careful usage of DROP TABLE IF EXISTS helps keep databases lean by clearing deprecated tables. Practice deliberately creating and removing tables to understand impact.

No Data

©2024 SQLZap - Learn SQL Interactively

Twitter