PostgreSQL Tablespaces

PostgreSQL Tablespace Management

Table of Contents



1. What Is a Tablespace?

A tablespace is a named location on disk where PostgreSQL stores the data files of tables, indexes and databases. By default everything lives under $PGDATA (pg_default). With tablespaces you can place objects on other disks or mount points.

  • Storage growth: add space on a new disk when the data directory file system is full.
  • Performance: keep hot tables and indexes on fast storage (SSD or NVMe) and old data on cheaper storage.
  • Separation: keep large or archive data away from the main data directory.
Tablespace Purpose Location
pg_default Default for user objects $PGDATA/base
pg_global Shared system catalogs $PGDATA/global
User-defined Created by you with CREATE TABLESPACE Any directory you choose

Important: A tablespace is part of the cluster, not of one database. Several databases can store objects in the same tablespace, and it cannot be dropped until it is empty in every database.

2. Lab Environment

Item Value
Server pglab01 (PostgreSQL 17)
Data directory /pgdata/pgsql-17/data
Tablespace 1 ts_data at /tsdata/pgsql-17/ts_data
Tablespace 2 ts_arch at /tsdata/pgsql-17/ts_arch
Demo database dell
Demo tables emp, dept

Note: The OIDs, file numbers and dates in the sample output will be different on your server. Use the commands as they are and compare the pattern, not the numbers.

3. Create the Directories (OS Level)

The directory must already exist, be empty, and be owned by the postgres OS user with 700 permission.

[root@pglab01 ~]# mkdir -p /tsdata/pgsql-17/ts_data /tsdata/pgsql-17/ts_arch
[root@pglab01 ~]# chown postgres:postgres /tsdata/pgsql-17/ts_data /tsdata/pgsql-17/ts_arch
[root@pglab01 ~]# chmod 700 /tsdata/pgsql-17/ts_data /tsdata/pgsql-17/ts_arch

4. Create the Tablespaces

postgres=# CREATE TABLESPACE ts_data LOCATION '/tsdata/pgsql-17/ts_data';
CREATE TABLESPACE
postgres=# CREATE TABLESPACE ts_arch LOCATION '/tsdata/pgsql-17/ts_arch';
CREATE TABLESPACE

Note: Only a superuser can create a tablespace. Do not create it inside $PGDATA.

5. Verify the Tablespaces

Inside PostgreSQL:

postgres=# \db
               List of tablespaces
    Name    |  Owner   |         Location
------------+----------+--------------------------
 pg_default | postgres |
 pg_global  | postgres |
 ts_arch    | postgres | /tsdata/pgsql-17/ts_arch
 ts_data    | postgres | /tsdata/pgsql-17/ts_data
(4 rows)

postgres=# SELECT oid, spcname, pg_tablespace_location(oid) FROM pg_tablespace;
  oid  |  spcname   |  pg_tablespace_location
-------+------------+--------------------------
  1663 | pg_default |
  1664 | pg_global  |
 32824 | ts_data    | /tsdata/pgsql-17/ts_data
 32825 | ts_arch    | /tsdata/pgsql-17/ts_arch

At the OS level:

[postgres@pglab01 ~]$ ls -ltr /pgdata/pgsql-17/data/pg_tblspc/
total 0
lrwxrwxrwx. 1 postgres postgres 24 Dec  2 09:33 32824 -> /tsdata/pgsql-17/ts_data
lrwxrwxrwx. 1 postgres postgres 24 Dec  2 09:33 32825 -> /tsdata/pgsql-17/ts_arch

[postgres@pglab01 ~]$ ls -ltr /tsdata/pgsql-17/ts_data
total 0
drwx------. 2 postgres postgres 6 Dec  2 09:33 PG_17_202406281

[postgres@pglab01 ~]$ ls -l /tsdata/pgsql-17/ts_data/PG_17_202406281/
total 0
  • pg_tblspc has one symbolic link per tablespace. The link name is the tablespace OID.
  • PG_17_202406281 is created automatically. It holds the major version (17) and the catalog version, so different versions can never clash.
  • The version directory is empty until something is stored in the tablespace.

6. Create a Database in a Tablespace

postgres=# CREATE DATABASE dell TABLESPACE ts_data;
CREATE DATABASE

postgres=# SELECT d.oid, d.datname, t.spcname AS default_tablespace
           FROM pg_database d JOIN pg_tablespace t ON t.oid = d.dattablespace
           WHERE d.datname = 'dell';
  oid  | datname | default_tablespace
-------+---------+--------------------
 32826 | dell    | ts_data
[postgres@pglab01 ~]$ ls -l /tsdata/pgsql-17/ts_data/PG_17_202406281/
total 0
drwx------. 2 postgres postgres 4096 Dec  2 09:40 32826

Remember: the numbered directory is the database OID. The unquoted name DELL is folded to lowercase, so connect with \c dell.

7. Create a Simple Table (Default Tablespace)

With no TABLESPACE clause, a table goes to the default tablespace of the database. For dell that is ts_data.

postgres=# \c dell
You are now connected to database "dell" as user "postgres".

dell=# CREATE TABLE emp (eno int);
CREATE TABLE

SELECT 'emp'::regclass::oid;          <------------ Get the OID  
-- or ---
SELECT pg_relation_filenode('emp');   <------------- Get the physical file number (OID) 
-- or ---
dell=# SELECT pg_relation_filepath('emp');   <--------------- Get the exact table file path on disk (use this always)
              pg_relation_filepath
------------------------------------------------
 pg_tblspc/32824/PG_17_202406281/32826/32832

dell=# SELECT tablename, tablespace FROM pg_tables WHERE tablename = 'emp';
 tablename | tablespace
-----------+------------
 emp       |  (empty)

Check the file at OS level. The table has one file, and it is empty (0 bytes) because there are no rows yet:

[postgres@pglab01 ~]$ ls -l $PGDATA/pg_tblspc/32824/PG_17_202406281/32826/32832
-rw-------. 1 postgres postgres 0 Dec  2 09:41 /pgdata/pgsql-17/data/pg_tblspc/32824/PG_17_202406281/32826/32832
  • The path reads as pg_tblspc / tablespace OID / version / database OID / file number.
  • The tablespace column of pg_tables is empty when a table is in the database default tablespace.
  • If dell had been created in pg_default, the path would start with base/ instead.

8. Create a Table in a Specific Tablespace

To map an object to a different tablespace, name it explicitly with TABLESPACE:

dell=# CREATE TABLE dept (dno int, dname varchar(30)) TABLESPACE ts_arch;
CREATE TABLE

dell=# CREATE INDEX idx_dept ON dept (dno) TABLESPACE ts_arch;
CREATE INDEX

dell=# SELECT pg_relation_filepath('dept');   <---- Check file path of table
              pg_relation_filepath
------------------------------------------------
 pg_tblspc/32825/PG_17_202406281/32826/32835

dell=# SELECT pg_relation_filepath('idx_dept');  <---- Check file path of index
              pg_relation_filepath
------------------------------------------------
 pg_tblspc/32825/PG_17_202406281/32826/32837

dell=# SELECT tablename, tablespace FROM pg_tables WHERE tablename IN ('emp','dept');
 tablename | tablespace
-----------+------------
 emp       |
 dept      | ts_arch

Now look inside the database directory in ts_arch. This tablespace is not the default of dell, so the directory holds only the objects you placed there:

dell=# SELECT relname, relfilenode FROM pg_class WHERE relname IN ('dept','idx_dept');
 relname  | relfilenode
----------+-------------
 dept     |       32835
 idx_dept |       32837
[postgres@pglab01 ~]$ ls -l /tsdata/pgsql-17/ts_arch/PG_17_202406281/32826/
total 8
-rw-------. 1 postgres postgres    0 Dec  2 09:45 32835
-rw-------. 1 postgres postgres 8192 Dec  2 09:45 32837
  • One file per object: 32835 is the dept table (0 bytes, no rows yet) and 32837 is idx_dept (8192 bytes, the index meta page).
  • The database directory of the default tablespace (ts_data) also holds the copied system catalog files, so filter it with ls | grep <file number>.

Why varchar(30) and not text? A table with an unbounded column such as text gets an extra TOAST table and TOAST index, which appear as additional files in the directory and can confuse a demo. A table with only int and a small varchar(n) column has no TOAST table, so you see exactly one file per table. This guide uses varchar(n) for every demo table. (varchar2 is an Oracle type; PostgreSQL uses varchar(n).)

Tip: If you create an index without TABLESPACE, it goes to default_tablespace (or the database default), not to the tablespace of its table. Always name it when you want them together.

To see every table and index in the database and where it sits:

dell=# SELECT c.relname, c.relkind,
       CASE WHEN c.reltablespace = 0 THEN 'database default' ELSE t.spcname END AS tablespace
FROM pg_class c LEFT JOIN pg_tablespace t ON t.oid = c.reltablespace
WHERE c.relnamespace = 'public'::regnamespace AND c.relkind IN ('r','i');
 relname  | relkind |    tablespace
----------+---------+------------------
 emp      | r       | database default
 dept     | r       | ts_arch
 idx_dept | i       | ts_arch

9. Default Tablespace: New Database and Session Setting

Many people create a database without the TABLESPACE clause. It then takes the tablespace of the template database, which is pg_default, so all its tables go under $PGDATA/base:

postgres=# CREATE DATABASE dell2;
CREATE DATABASE

postgres=# SELECT d.oid, d.datname, t.spcname FROM pg_database d JOIN pg_tablespace t ON t.oid = d.dattablespace WHERE d.datname = 'dell2';
  oid  | datname |  spcname
-------+---------+------------
 32870 | dell2   | pg_default

postgres=# \c dell2
dell2=# CREATE TABLE t1 (id int);
CREATE TABLE
dell2=# SELECT pg_relation_filepath('t1');
 pg_relation_filepath
----------------------
 base/32870/32873

You do not have to type TABLESPACE on every CREATE TABLE. Set default_tablespace for your session, and every new table and index you create in that session goes there:

dell2=# SET default_tablespace = ts_data;
SET

dell2=# SHOW default_tablespace;
 default_tablespace
--------------------
 ts_data

dell2=# CREATE TABLE t2 (id int);
CREATE TABLE
dell2=# SELECT pg_relation_filepath('t2');
              pg_relation_filepath
------------------------------------------------
 pg_tblspc/32824/PG_17_202406281/32870/32876

dell2=# SELECT tablename, tablespace FROM pg_tables WHERE tablename IN ('t1','t2');
 tablename | tablespace
-----------+------------
 t1        |
 t2        | ts_data

dell2=# RESET default_tablespace;
RESET
  • The setting lasts only for this session. A new connection goes back to the normal default.
  • An explicit TABLESPACE clause always overrides it.
  • You need the CREATE privilege on the tablespace (see the grant section below).

To make it permanent, store the setting at a wider level. It applies to new sessions, so reconnect after running it:

ALTER DATABASE dell2 SET default_tablespace = ts_data;  <-- every new session in dell2
ALTER ROLE some_user SET default_tablespace = ts_data;  <-- every new session of that user
-- or 
in postgresql.conf for the whole cluster:  default_tablespace = 'ts_data'

Remember: default_tablespace only affects objects created after it is set. It does not move existing objects. Use ALTER TABLE ... SET TABLESPACE for that.

Clean up:

dell2=# \c postgres
postgres=# DROP DATABASE dell2;
DROP DATABASE

10. Find the Data File of a Table (Empty Table, Insert, Select)

Every table is stored in its own physical file. Create an empty table, find its file, then watch the file change as you insert data:

postgres=# \c dell
You are now connected to database "dell" as user "postgres".
dell=#

dell=# CREATE TABLE emp_demo (eno int, ename varchar(30));
CREATE TABLE

dell=# SELECT pg_relation_filepath('emp_demo');
              pg_relation_filepath
------------------------------------------------
 pg_tblspc/32824/PG_17_202406281/32826/32840
[postgres@pglab01 ~]$ ls -ltr $PGDATA/pg_tblspc/32824/PG_17_202406281/32826/32840
-rw-------. 1 postgres postgres 0 Dec  2 10:02 /pgdata/pgsql-17/data/pg_tblspc/32824/PG_17_202406281/32826/32840

The file exists but its size is 0 bytes, because the table is empty. Now insert some rows and look again:

dell=# INSERT INTO emp_demo VALUES (1,'RAJ'), (2,'SUGI'), (3,'TEJA');
INSERT 0 3

dell=# SELECT * FROM emp_demo;
 eno | ename
-----+-------
   1 | RAJ
   2 | SUGI
   3 | TEJA
(3 rows)
[postgres@pglab01 ~]$ ls -ltr $PGDATA/pg_tblspc/32824/PG_17_202406281/32826/32840
-rw-------. 1 postgres postgres 8192 Dec  2 10:03 /pgdata/pgsql-17/data/pg_tblspc/32824/PG_17_202406281/32826/32840
  • PostgreSQL stores data in 8 KB pages, so the file grows in steps of 8192 bytes. Three small rows fit in one page.
  • For a table in pg_default the path starts with base/, so use $PGDATA/base/<db_oid>/<file>.

11. Simulate a Missing Data File (Move It Away and Back)

This shows that the catalog knows the table, but the data lives only in the file. Flush the data to disk first, then move the file away:

dell=# CHECKPOINT;
CHECKPOINT
[postgres@pglab01 ~]$ mv $PGDATA/pg_tblspc/32824/PG_17_202406281/32826/32840 /tmp/32840.bak

Open a new connection and select from the table:

dell=# \c dell
You are now connected to database "dell" as user "postgres".

dell=# \d emp_demo
              Table "public.emp_demo"
 Column |         Type          | Collation | Nullable | Default
--------+-----------------------+-----------+----------+---------
 eno    | integer               |           |          |
 ename  | character varying(30) |           |          |

dell=# SELECT * FROM emp_demo;
ERROR:  could not open file "pg_tblspc/32824/PG_17_202406281/32826/32840": No such file or directory

The table definition is still there (\d works because it reads the catalog), but the rows cannot be read because their file is missing.

Now move the file back and select again:

[postgres@pglab01 ~]$ mv /tmp/32840.bak $PGDATA/pg_tblspc/32824/PG_17_202406281/32826/32840
dell=# SELECT * FROM emp_demo;
 eno | ename
-----+-------
   1 | RAJ
   2 | SUGI
   3 | TEJA
(3 rows)

All data is back. The file name, owner (postgres) and permission (600) must stay exactly the same.

  • Why the CHECKPOINT? It writes changed pages to the file first, so nothing is waiting in memory to be written to a file that is missing.
  • Why a new connection? A session that already has the file open, or has the pages cached in shared_buffers, may still return rows and hide the error.

Note: Do this only in a test lab, and put the file back quickly. A checkpoint or a write to the table while the file is missing will raise errors. Never move or delete data files by hand in production.

12. Find the Table Name from the File Number (Reverse Lookup)

Sometimes you only have a file path, for example from an OS alert or a corruption message. Split the path into its parts:

Part of pg_tblspc/32824/PG_17_202406281/32826/32840 Meaning
32824 Tablespace OID
PG_17_202406281 Version directory
32826 Database OID
32840 File number (relfilenode)
postgres=# SELECT spcname FROM pg_tablespace WHERE oid = 32824;
 spcname
---------
 ts_data

postgres=# SELECT datname FROM pg_database WHERE oid = 32826;
 datname
---------
 dell

postgres=# \c dell

dell=# SELECT pg_relation_filepath(32840);
            pg_relation_filepath
---------------------------------------------
 pg_tblspc/32824/PG_17_202406281/32826/32840
(1 row)

dell=#

---- OR ----

dell=# SELECT pg_filenode_relation(32824, 32840);     <---------------- 32824 tablespace oid and 32840 is emp_demo table
 pg_filenode_relation
----------------------
 emp_demo


dell=# SELECT relname, relkind FROM pg_class WHERE relfilenode = 32840;
 relname  | relkind
----------+---------
 emp_demo | r

The oid2name tool (from the contrib package) does the same from the shell:

[postgres@pglab01 ~]$ oid2name -d dell -f 32840
From database "dell":
  Filenode  Table Name
----------------------
     32840    emp_demo

[postgres@pglab01 ~]$ oid2name -d dell -t emp_demo
From database "dell":
  Filenode  Table Name
----------------------
     32840    emp_demo

If you want to see all associated objects (including TOAST tables and indexes):

oid2name -d dell -x
  • Run the lookup inside the database named in the path (here dell). pg_filenode_relation only searches the current database.
  • Search by relfilenode, not by oid. The file number changes after TRUNCATE, VACUUM FULL or SET TABLESPACE, so it may differ from the table OID.
  • Files such as 32840_fsm, 32840_vm and 32840.1 belong to the same file number.

Clean up the demo table:

dell=# DROP TABLE emp_demo;
DROP TABLE

13. Large Tables Split into 1 GB Files

PostgreSQL stores a table in files of at most 1 GB. When a table grows past that, it continues in new files with the suffix .1, .2 and so on. To see this, create a small table and insert about 3 GB of data:

[postgres@pglab01 ~]$ df -h /tsdata
dell=# CREATE TABLE big_tab (id int, filler varchar(1000));
CREATE TABLE

dell=# INSERT INTO big_tab SELECT g, repeat('x', 1000) FROM generate_series(1, 2500000) g;
INSERT 0 2500000

dell=# SELECT pg_size_pretty(pg_relation_size('big_tab'));
 pg_size_pretty
----------------
 2790 MB

dell=# SELECT pg_relation_filepath('big_tab');
              pg_relation_filepath
------------------------------------------------
 pg_tblspc/32824/PG_17_202406281/32826/32845
[postgres@pglab01 ~]$ ls -lh $PGDATA/pg_tblspc/32824/PG_17_202406281/32826/ | grep 32845
-rw-------. 1 postgres postgres 1.0G Dec  2 10:21 32845
-rw-------. 1 postgres postgres 1.0G Dec  2 10:21 32845.1
-rw-------. 1 postgres postgres 742M Dec  2 10:21 32845.2
  • One table, one file number, but three files on disk: 32845, 32845.1 and 32845.2.
  • pg_relation_filepath shows only the first file. The other segments follow the same name with .1, .2.
  • pg_relation_size adds up all the segments. Use pg_total_relation_size to include indexes and TOAST.
  • After a vacuum you will also see 32845_fsm (free space map) and 32845_vm (visibility map).

Note: Use a test server. The insert needs about 3 GB of free space in the tablespace and writes roughly the same amount of WAL, so also check space for pg_wal. It can take a few minutes. Adjust generate_series(1, 2500000) for a smaller or bigger table.

Clean up to free the space:

dell=# DROP TABLE big_tab;
DROP TABLE

14. Move a Table or Index to Another Tablespace

dell=# ALTER TABLE emp SET TABLESPACE ts_arch;
ALTER TABLE

dell=# SELECT pg_relation_filepath('emp');
              pg_relation_filepath
------------------------------------------------
 pg_tblspc/32825/PG_17_202406281/32826/32890

The tablespace OID in the path changed from 32824 to 32825, and the file number is new because PostgreSQL copied the file. Indexes do not move with the table, so move them separately:

dell=# ALTER INDEX idx_dept SET TABLESPACE ts_data;
ALTER INDEX

Move everything in one tablespace to another (current database only):

ALTER TABLE ALL IN TABLESPACE ts_arch SET TABLESPACE ts_data;
ALTER INDEX ALL IN TABLESPACE ts_arch SET TABLESPACE ts_data;
ALTER MATERIALIZED VIEW ALL IN TABLESPACE ts_arch SET TABLESPACE ts_data;

Note: SET TABLESPACE takes an ACCESS EXCLUSIVE lock and rewrites the whole file, so large tables block reads and writes while they move. Use a maintenance window. The TOAST table moves together with its table. The ALL IN TABLESPACE forms work only on the database you are connected to, so repeat them in each database.

15. Move a Whole Database to Another Tablespace

You cannot be connected to the database you are moving, so connect to postgres first:

dell=# \c postgres
You are now connected to database "postgres" as user "postgres".

postgres=# ALTER DATABASE dell SET TABLESPACE pg_default;
ALTER DATABASE

postgres=# SELECT d.datname, t.spcname FROM pg_database d JOIN pg_tablespace t ON t.oid = d.dattablespace WHERE d.datname = 'dell';
 datname | spcname
---------+------------
 dell    | pg_default

Check where the files are now:

postgres=# \c dell
dell=# SELECT pg_relation_filepath('idx_dept') AS idx, pg_relation_filepath('emp') AS emp;
              idx               |                  emp
--------------------------------+----------------------------------------
 base/32826/32893               | pg_tblspc/32825/PG_17_202406281/32826/32890
[postgres@pglab01 ~]$ ls -l /tsdata/pgsql-17/ts_data/PG_17_202406281/
total 0
  • Only objects that used the old database default tablespace moved (here idx_dept, now under base/).
  • Objects explicitly placed in another tablespace (emp and dept in ts_arch) stay where they are.
  • The same command moves a database to any other tablespace: ALTER DATABASE dell SET TABLESPACE ts_data;

Requirements and errors: You must own the database and have CREATE on the target tablespace. If anyone is connected you get database "dell" is being accessed by other users. If the target tablespace already holds objects of this database you get some relations of database "dell" are already in tablespace "ts_arch", so move those objects out first.

16. Change the Owner of a Tablespace

The owner is the user who ran CREATE TABLESPACE, unless OWNER was given.

postgres=# CREATE ROLE dba_user LOGIN;
CREATE ROLE

postgres=# SELECT spcname, pg_get_userbyid(spcowner) AS owner FROM pg_tablespace WHERE spcname LIKE 'ts_%';
 spcname |  owner
---------+----------
 ts_data | postgres
 ts_arch | postgres

postgres=# ALTER TABLESPACE ts_arch OWNER TO dba_user;
ALTER TABLESPACE

postgres=# SELECT spcname, pg_get_userbyid(spcowner) AS owner FROM pg_tablespace WHERE spcname LIKE 'ts_%';
 spcname |  owner
---------+----------
 ts_data | postgres
 ts_arch | dba_user

You can also set the owner when you create the tablespace:

CREATE TABLESPACE ts_new OWNER dba_user LOCATION '/tsdata/pgsql-17/ts_new';
  • You must be a superuser, or the current owner and a member of the new owning role.
  • Changing the tablespace owner does not change who owns the tables or databases stored in it.

17. Grant and Revoke Access

Users other than the owner and superusers cannot create objects in a tablespace until they get the CREATE privilege:

postgres=# CREATE ROLE app_user LOGIN;
CREATE ROLE
postgres=# GRANT CREATE ON TABLESPACE ts_data TO app_user;
GRANT

postgres=# SELECT spcname, spcacl FROM pg_tablespace WHERE spcname = 'ts_data';
 spcname |         spcacl
---------+------------------------
 ts_data | {postgres=C/postgres,app_user=C/postgres}

postgres=# REVOKE CREATE ON TABLESPACE ts_data FROM app_user;
REVOKE

Note: REVOKE only blocks new objects. Objects the user already created in the tablespace stay there.

18. Rename a Tablespace

postgres=# ALTER TABLESPACE ts_arch RENAME TO ts_archive;
ALTER TABLESPACE

postgres=# SELECT oid, spcname, pg_tablespace_location(oid) FROM pg_tablespace WHERE oid = 32825;
  oid  |  spcname   |  pg_tablespace_location
-------+------------+--------------------------
 32825 | ts_archive | /tsdata/pgsql-17/ts_arch
[postgres@pglab01 ~]$ ls -l /pgdata/pgsql-17/data/pg_tblspc/
lrwxrwxrwx. 1 postgres postgres 24 Dec  2 09:33 32824 -> /tsdata/pgsql-17/ts_data
lrwxrwxrwx. 1 postgres postgres 24 Dec  2 09:33 32825 -> /tsdata/pgsql-17/ts_arch
  • The OID stays the same, so the symlink is unchanged and every object keeps working.
  • The directory on disk is not renamed. It is still /tsdata/pgsql-17/ts_arch.
  • It only updates the catalog, so it is instant and needs no downtime.
  • You must own the tablespace (or be a superuser), and the new name cannot start with pg_.

⚠️ Note: From here on the demo uses the new name ts_archive.

19. Scenario 1: Mount Point Is Full, Add a New Tablespace for Future Objects

Situation: The mount point of ts_data (/tsdata) is almost full. The system admin gives you a new mount point (/tsdata2). You do not want to move any existing data. You only want all future objects to be created on the new mount point.

What to expect:

  • New tables and indexes go to the new tablespace.
  • Old objects stay in ts_data. SELECT, INSERT, UPDATE and DELETE on them keep working exactly as before. Applications do not need to know which tablespace holds a table.
  • Old tables still grow in ts_data when you insert into them, so a nearly full old mount point can still run out of space (see the note at the end).

Step 1: Create a table in the old tablespace (this plays the role of your existing data)

dell=# CREATE TABLE old_tab (id int, note varchar(30)) TABLESPACE ts_data;
CREATE TABLE
dell=# INSERT INTO old_tab VALUES (1,'old row 1'), (2,'old row 2');
INSERT 0 2

dell=# SELECT pg_relation_filepath('old_tab');
              pg_relation_filepath
------------------------------------------------
 pg_tblspc/32824/PG_17_202406281/32826/32900

Step 2: Prepare the directory on the new mount point (as root)

[root@pglab01 ~]# df -h /tsdata /tsdata2
Filesystem      Size  Used Avail Use% Mounted on
/dev/sdc1       100G   98G  2.0G  98% /tsdata        <---- old mount point is almost full
/dev/sdd1       200G  1.0G  199G   1% /tsdata2       <---- new mount point has free space

[root@pglab01 ~]# mkdir -p /tsdata2/pgsql-17/ts_data2
[root@pglab01 ~]# chown postgres:postgres /tsdata2/pgsql-17/ts_data2
[root@pglab01 ~]# chmod 700 /tsdata2/pgsql-17/ts_data2

Step 3: Create the new tablespace and allow users to create objects in it

postgres=# CREATE TABLESPACE ts_data2 LOCATION '/tsdata2/pgsql-17/ts_data2';
CREATE TABLESPACE
postgres=# GRANT CREATE ON TABLESPACE ts_data2 TO PUBLIC;
GRANT

postgres=# SELECT oid, spcname, pg_tablespace_location(oid) FROM pg_tablespace WHERE spcname = 'ts_data2';
  oid  | spcname  |      pg_tablespace_location
-------+----------+-----------------------------
 32950 | ts_data2 | /tsdata2/pgsql-17/ts_data2

Step 4: Make it the default for new objects

postgres=# ALTER DATABASE dell SET default_tablespace = 'ts_data2';   <-- every new session in dell
ALTER DATABASE

-- Or for all databases in the cluster (reload only, no restart):
postgres=# ALTER SYSTEM SET default_tablespace = 'ts_data2';
postgres=# SELECT pg_reload_conf();

Note: The setting applies to new sessions. Disconnect and reconnect before testing.

Step 5: Create a new table and check where it goes

postgres=# \c dell
You are now connected to database "dell" as user "postgres".

dell=# SHOW default_tablespace;
 default_tablespace
--------------------
 ts_data2

dell=# CREATE TABLE new_tab (id int, note varchar(30));        <---- no TABLESPACE clause
CREATE TABLE
dell=# INSERT INTO new_tab VALUES (1,'new row 1');
INSERT 0 1

dell=# SELECT pg_relation_filepath('new_tab');
              pg_relation_filepath
------------------------------------------------
 pg_tblspc/32950/PG_17_202406281/32826/32955        <---- 32950 = ts_data2 (new mount)

Step 6: Confirm the old objects are untouched and still work

dell=# SELECT pg_relation_filepath('old_tab');
              pg_relation_filepath
------------------------------------------------
 pg_tblspc/32824/PG_17_202406281/32826/32900        <---- same path as in Step 1, still ts_data (old mount)

dell=# SELECT * FROM old_tab;
 id |   note
----+-----------
  1 | old row 1
  2 | old row 2
(2 rows)

dell=# INSERT INTO old_tab VALUES (3,'old row 3');        <---- still works, row is written to the OLD tablespace
INSERT 0 1

dell=# SELECT c.relname, CASE WHEN c.reltablespace = 0 THEN 'database default' ELSE t.spcname END AS tablespace
FROM pg_class c LEFT JOIN pg_tablespace t ON t.oid = c.reltablespace
WHERE c.relname IN ('old_tab','new_tab');
 relname | tablespace
---------+------------
 old_tab | ts_data
 new_tab | ts_data2

Result: new objects are created in ts_data2 on the new mount point. Old objects stay in ts_data and every query on them still works.

Step 7 (optional): Move the biggest old tables later, in a quiet window

dell=# ALTER TABLE old_tab SET TABLESPACE ts_data2;        <---- copies the table to the new mount and locks it while it runs
ALTER TABLE
dell=# SELECT pg_relation_filepath('old_tab');
              pg_relation_filepath
------------------------------------------------
 pg_tblspc/32950/PG_17_202406281/32826/32960

See section 14 for the details and for the ALL IN TABLESPACE forms.

Step 8: Clean up the demo

dell=# DROP TABLE old_tab, new_tab;
DROP TABLE
dell=# \c postgres
postgres=# ALTER DATABASE dell RESET default_tablespace;
ALTER DATABASE
postgres=# ALTER SYSTEM RESET default_tablespace;
ALTER SYSTEM
postgres=# SELECT pg_reload_conf();
postgres=# DROP TABLESPACE ts_data2;
DROP TABLESPACE
[root@pglab01 ~]# rmdir /tsdata2/pgsql-17/ts_data2

Remember: default_tablespace affects only objects created after it is set. If the old mount point is almost full, inserts into old tables can still fail with No space left on device. Free some space, or move the biggest old tables to the new tablespace (Step 7). An explicit TABLESPACE clause always overrides the default, and temporary files are controlled by temp_tablespaces, not by this setting.

20. Scenario 2: Move a Whole Tablespace to a New Mount Point

Situation: This is a different case. You want the entire tablespace, with all its existing data, to live on a new mount point. The tablespace keeps its name and OID, so no object changes. Only the directory behind the symlink changes.

PostgreSQL has no ALTER TABLESPACE ... SET LOCATION. So the manual method is: stop, copy, re-point the symlink, start. This demo moves ts_archive (OID 32825) from /tsdata/pgsql-17/ts_arch to /tsdata2/pgsql-17/ts_archive.

Downtime: the server must be stopped while you copy the files and change the link. Plan a maintenance window, take a backup first, and test the whole procedure in a lab.

Step 1: Add some data and note the OID and current location

dell=# INSERT INTO dept VALUES (10,'SALES'), (20,'HR');
INSERT 0 2

postgres=# SELECT oid, spcname, pg_tablespace_location(oid) FROM pg_tablespace WHERE spcname = 'ts_archive';
  oid  |  spcname   |  pg_tablespace_location
-------+------------+--------------------------
 32825 | ts_archive | /tsdata/pgsql-17/ts_arch

Step 2: Prepare the new directory on the new mount point (as root)

[root@pglab01 ~]# mkdir -p /tsdata2/pgsql-17/ts_archive
[root@pglab01 ~]# chown postgres:postgres /tsdata2/pgsql-17/ts_archive
[root@pglab01 ~]# chmod 700 /tsdata2/pgsql-17/ts_archive
[root@pglab01 ~]# df -h /tsdata2        <---- free space must be larger than the data you are moving
[root@pglab01 ~]# du -sh /tsdata/pgsql-17/ts_arch

Step 3: Stop PostgreSQL cleanly

[postgres@pglab01 ~]$ pg_ctl stop -D /pgdata/pgsql-17/data -m fast
waiting for server to shut down.... done
server stopped

Step 4: Copy everything and compare

[postgres@pglab01 ~]$ rsync -aH /tsdata/pgsql-17/ts_arch/ /tsdata2/pgsql-17/ts_archive/      <---- note the trailing slashes

[postgres@pglab01 ~]$ du -s /tsdata/pgsql-17/ts_arch /tsdata2/pgsql-17/ts_archive
24     /tsdata/pgsql-17/ts_arch
24     /tsdata2/pgsql-17/ts_archive         <---- same size

[postgres@pglab01 ~]$ ls -l /tsdata2/pgsql-17/ts_archive
total 0
drwx------. 3 postgres postgres 20 Dec  2 11:10 PG_17_202406281        <---- the version directory was copied
  • -a keeps owner, permissions and timestamps. The files must stay owned by postgres with 600 and directories 700.
  • Copy the contents (ts_arch/), not the folder itself, so PG_17_... ends up directly inside the new directory.

Step 5: Re-point the symbolic link

[postgres@pglab01 ~]$ cd /pgdata/pgsql-17/data/pg_tblspc
[postgres@pglab01 pg_tblspc]$ ls -l
lrwxrwxrwx. 1 postgres postgres 24 Dec  2 09:33 32824 -> /tsdata/pgsql-17/ts_data
lrwxrwxrwx. 1 postgres postgres 24 Dec  2 09:33 32825 -> /tsdata/pgsql-17/ts_arch        <---- old link

[postgres@pglab01 pg_tblspc]$ rm 32825                                        <---- removes only the link
[postgres@pglab01 pg_tblspc]$ ln -s /tsdata2/pgsql-17/ts_archive 32825
[postgres@pglab01 pg_tblspc]$ ls -l
lrwxrwxrwx. 1 postgres postgres 24 Dec  2 09:33 32824 -> /tsdata/pgsql-17/ts_data
lrwxrwxrwx. 1 postgres postgres 33 Dec  2 11:12 32825 -> /tsdata2/pgsql-17/ts_archive        <---- new link

Careful: remove only the symlink (rm 32825), never rm -r. The link name must stay the tablespace OID.

Step 6: Start PostgreSQL and verify

[postgres@pglab01 ~]$ pg_ctl start -D /pgdata/pgsql-17/data
postgres=# SELECT spcname, pg_tablespace_location(oid) FROM pg_tablespace WHERE spcname = 'ts_archive';
  spcname   |    pg_tablespace_location
------------+-------------------------------
 ts_archive | /tsdata2/pgsql-17/ts_archive

postgres=# \c dell
dell=# SELECT * FROM dept;
 dno | dname
-----+-------
  10 | SALES
  20 | HR
(2 rows)

dell=# SELECT pg_relation_filepath('dept');
              pg_relation_filepath
------------------------------------------------
 pg_tblspc/32825/PG_17_202406281/32826/32835        <---- same path as before, but the data is now physically on /tsdata2

dell=# INSERT INTO dept VALUES (30,'IT');
INSERT 0 1
[postgres@pglab01 ~]$ ls -l /tsdata2/pgsql-17/ts_archive/PG_17_202406281/32826/
-rw-------. 1 postgres postgres 8192 Dec  2 11:15 32835        <---- dept table is written on the new mount
-rw-------. 1 postgres postgres 8192 Dec  2 11:15 32837

Result: the tablespace name, OID, object paths and all data are unchanged. Only the physical location moved to the new mount point.

Step 7: Keep the old copy for a while, then remove it

[root@pglab01 ~]# mv /tsdata/pgsql-17/ts_arch /tsdata/pgsql-17/ts_arch_old        <---- rename first, do not delete yet

# After a few days of normal running and a good backup:
[root@pglab01 ~]# rm -rf /tsdata/pgsql-17/ts_arch_old
  • SELinux: if it is enabled, run restorecon -Rv /tsdata2/pgsql-17/ts_archive after the copy.
  • Standby servers: apply the same copy and symlink change on every streaming standby, or the standby will fail to find the tablespace.
  • Shortcut: if the admin can mount the new disk at the old path (for example /tsdata), copy the data and remount it there. No symlink change is needed.
  • No-downtime alternative: create a new tablespace on the new mount, move the objects with ALTER ... SET TABLESPACE (section 14), then drop the old tablespace. This is slower and locks each table while it moves, but the server stays up.

Scenario 1 and Scenario 2 side by side

Scenario 1: new tablespace Scenario 2: move whole tablespace
Goal Stop new objects going to the full mount Relocate everything to another mount
Existing data Stays in the old tablespace Moves to the new mount
Downtime None Short (stop and start)
Method CREATE TABLESPACE + default_tablespace Stop, copy files, re-point pg_tblspc symlink, start
Old mount space freed? No (unless you move objects) Yes, after you delete the old copy

21. Drop a Tablespace

A tablespace can be dropped only when it is completely empty in every database.
Step 1: try to drop it. It still holds emp and dept:

postgres=# DROP TABLESPACE ts_archive;
ERROR:  tablespace "ts_archive" is not empty

Step 2: find which databases still use it.

postgres=# SELECT datname FROM pg_database
           WHERE oid IN (SELECT pg_tablespace_databases(oid) FROM pg_tablespace WHERE spcname = 'ts_archive');
 datname
---------
 dell

Step 3: in that database, list the objects.

postgres=# \c dell
dell=# SELECT c.relname, c.relkind FROM pg_class c JOIN pg_tablespace t ON t.oid = c.reltablespace WHERE t.spcname = 'ts_archive';
 relname | relkind
---------+---------
 emp     | r
 dept    | r

Tip: relkind is r for table, i for index, m for materialized view. Objects in a database whose default tablespace is the one you want to drop have reltablespace = 0, so also check pg_database.dattablespace.

Step 4: move everything out, then drop.

dell=# ALTER TABLE ALL IN TABLESPACE ts_archive SET TABLESPACE pg_default;
ALTER TABLE
dell=# ALTER INDEX ALL IN TABLESPACE ts_archive SET TABLESPACE pg_default;
ALTER INDEX
dell=# \c postgres

postgres=# DROP TABLESPACE ts_archive;
DROP TABLESPACE
postgres=# DROP TABLESPACE ts_data;
DROP TABLESPACE

postgres=# \db
               List of tablespaces
    Name    |  Owner   | Location
------------+----------+----------
 pg_default | postgres |
 pg_global  | postgres |
(2 rows)
[postgres@pglab01 ~]$ ls -l /pgdata/pgsql-17/data/pg_tblspc/
total 0

Done. The symlinks in pg_tblspc are gone. The empty directories under /tsdata and /tsdata2 can now be removed at the OS level.

22. Clean Up & Quick Reference

postgres=# DROP DATABASE dell;
postgres=# DROP ROLE app_user;
postgres=# DROP ROLE dba_user;
Task Command
Create CREATE TABLESPACE name LOCATION '/path';
List \db, \db+
Database in tablespace CREATE DATABASE db TABLESPACE name;
Table in tablespace CREATE TABLE t (...) TABLESPACE name;
Check file location SELECT pg_relation_filepath('t');
Move table ALTER TABLE t SET TABLESPACE name;
Move index ALTER INDEX i SET TABLESPACE name;
Move all objects ALTER TABLE ALL IN TABLESPACE a SET TABLESPACE b;
Move database ALTER DATABASE db SET TABLESPACE name; (no connections)
Show owner SELECT spcname, pg_get_userbyid(spcowner) FROM pg_tablespace;
Change owner ALTER TABLESPACE name OWNER TO new_owner;
Rename ALTER TABLESPACE old RENAME TO new;
Grant / revoke GRANT CREATE ON TABLESPACE name TO user; / REVOKE ... FROM user;
Session default SET default_tablespace = name;
Permanent default ALTER DATABASE db SET default_tablespace = name;
Mount point full: new objects to a new mount CREATE TABLESPACE on the new mount, GRANT CREATE, then ALTER DATABASE db SET default_tablespace (section 19)
Move a whole tablespace to a new mount Stop server, rsync -aH, re-point the pg_tblspc/<OID> symlink, start server (section 20)
Drop DROP TABLESPACE name; (must be empty everywhere)
  • Backups: pg_basebackup includes tablespaces. A file-system copy of $PGDATA alone does not. On a standby, the same directories must exist, or use --tablespace-mapping.
  • Do not delete files inside a tablespace directory by hand. Always use SQL.
Caution: Your use of any information or materials on this website is entirely at your own risk. It is provided for educational purposes only. It has been tested internally, however, we do not guarantee that it will work for you. Ensure that you run it in your test environment before using.
Thank you
Rajasekhar Amudala