PostgreSQL DROP TABLESPACE Statement
Summary: in this tutorial, you will learn how to use the PostgreSQL DROP TABLESPACE statement to remove a tablespace.
Introduction to PostgreSQL DROP TABLESPACE statement
The DROP TABLESPACE
statement delete a tablespace from a database:
Here’s the syntax of the DROP TABLE
statement:
In this syntax:
- First, specify the name of the tablespace that you want to remove after the
DROP TABLESPACE
keywords. - Second, use the
IF EXISTS
option to instruct PostgreSQL to issue a notice instead of an error when the tablespace does not exist.
Only tablespace owners or superusers can execute the DROP TABLESPACE
statement to drop the tablespace.
PostgreSQL DROP TABLESPACE examples
Let’s explore some examples of using the DROP TABLESPACE
statement.
1) Basic DROP TABLESPACE statement example
First, open the Command Prompt or Terminal on a Unix-like system and create a new directory for the tablespace such as C:\pgdata\demo
:
Next, connect to the PostgreSQL server:
Then, create a new tablespace called sample_ts:
After that, drop the sample_ts
tablespace using the DROP TABLESPACE
statement:
Finally, exit psql:
2) Dropping a tablespace that has objects
First, create a new directory called C:/pgdata/demo
on your server. Replace the path with the actual one that you use:
Second, create a new tablespace named demo
and map it to the c:\pgdata\demo
directory.
Third, create a new database named dbdemo
and set its tablespace to demo
:
Fourth, connect to the demodb
database:
Fifth, create a new table named test
in the dbdemo
and set it tablespace
to demo_ts
:
Sixth, attempt to drop the demo
tablespace:
PostgreSQL issues an error:
Because the demo_ts
tablespace is not empty, you cannot drop it.
Seventh, connect to the postgres
database:
Eight, drop the demodb
database:
Ninth, drop the demo_ts
tablespace:
Instead of dropping the database, you can move it to another tablespace such as pg_default
by using the ALTER TABLE statement as follows:
And then delete the demo_ts
tablespace again:
Summary
- Use the PostgreSQL
DROP TABLESPACE
statement to drop a tablespace.