Summary: in this tutorial, you will learn how to remove a tablespace by using the PostgreSQL DROP TABLESPACE statement.
Introduction to DROP TABLESPACE statement
To remove a tablespace, you use DROP TABLESPACE
statement as follows:
1 | DROP TABLESPACE IF EXISTS tablespace_name; |
You need to specify the name of the tablespace after the DROP TABLESPACE
clause. The IF EXISTS
helps you avoid the error of removing a non-existent tablespace.
Only tablespace owner or the superuser can delete the tablespace.
Before deleting the tablespace, make sure that it is empty, which means there are no database objects inside it.
PostgreSQL DROP TABLESPACE example
First, create a new tablespace named demo
and maps it to the c:\data\demo directory
.
1 | CREATE TABLESPACE demo LOCATION 'c:/data/demo'; |
Second, create a new database named dbdemo
and set its tablespace to demo
:
1 | CREATE DATABASE dbdemo TABLESPACE = demo; |
Third, create a new table named test
in the dbdemo
and set it tablespace
to demo
:
1 2 3 4 | CREATE TABLE test ( ID serial PRIMARY KEY, title VARCHAR (255) NOT NULL ) TABLESPACE demo; |
You can get all objects in the demo
tablespace by using the following query:
1 2 3 4 5 6 7 8 | SELECT ts.spcname, cl.relname FROM pg_class cl JOIN pg_tablespace ts ON cl.reltablespace = ts.oid WHERE ts.spcname = 'demo'; |
Fourth, try to delete the demo
tablespace:
1 | DROP TABLESPACE demo; |
We got an error message:
1 | [Err] ERROR: tablespace "demo" is not empty |
Because the demo tablespace is not empty, we could not delete it.
Fifth, login to the postgres
database and delete the dbdemo
database:
1 | DROP DATABASE dbdemo; |
Instead of deleting the database, you can move it to the another tablespace e.g., pg_default
by using the ALTER TABLE statement as follows:
1 2 | ALTER DATABASE dbdemo SET TABLESPACE = pg_default; |
Sixth, delete the demo
tablespace again:
1 | DROP TABLESPACE demo; |
It worked. The demo tablespace was deleted.
In this tutorial, we have shown you how step by step how to delete tablespace by using the PostgreSQL DROP TABLESPACE
statement.