PostgreSQL DROP TABLE
Summary: in this tutorial, you will learn how to use the PostgreSQL DROP TABLE
statement to remove one or more tables from the database.
Introduction to PostgreSQL DROP TABLE statement
To drop a table from the database, you use the DROP TABLE
statement as follows:
In this syntax:
- First, specify the name of the table that you want to drop after the
DROP TABLE
keywords. - Second, use the
IF EXISTS
option to remove the table only if it exists.
If you remove a table that does not exist, PostgreSQL issues an error. To avoid the error, you can use the IF EXISTS
option.
If the table is used in other database objects such as views, triggers, functions, and stored procedures, you cannot remove it. In this case, you have two options:
- Use the
CASCADE
option to remove the table and its dependent objects. - Use the
RESTRICT
option rejects the removal if there is any object depending on the table. TheRESTRICT
option is the default if you don’t explicitly specify it in theDROP TABLE
statement.
To remove multiple tables simultaneously, you can place the tables separated by commas after the DROP TABLE
keywords:
Note that you need to have the roles of the superuser, schema owner, or table owner to drop tables.
PostgreSQL DROP TABLE examples
Let’s take some examples of using the PostgreSQL DROP TABLE
statement.
1) Drop a table that does not exist
The following statement removes a table named author
in the database:
PostgreSQL issues an error because the author
table does not exist.
To avoid the error, you can use the IF EXISTS
option like this.
The output indicates that PostgreSQL issued a notice instead of an error.
2) Drop a table that has dependent objects
The following creates new tables called authors
and pages
. The pages
table has a foreign key that references the authors
table.
The following statement uses the DROP TABLE
to drop the authors
table:
Because the authors
table has a dependent object which is a foreign key that references the pages
table, PostgreSQL issues an error message:
In this case, you need to remove all dependent objects first before dropping the author
table or use CASCADE
option as follows:
This statement deletes the authors
table as well as the constraint in the pages
table.
If the DROP TABLE
statement removes the dependent objects of the table that are being dropped, it will issue a notice like this:
3) Drop multiple tables
The following statements create two tables for the demo purposes:
The following example uses a single DROP TABLE
statement to drop the tvshows
and animes
tables:
Summary
- Use the
DROP TABLE
statement to drop one or more tables. - Use the
CASCADE
option to drop a table and all of its dependent objects.