// SQL snippet

Move a table between schemas

Archiving old tables or splitting a database into modules means moving tables between schemas. It is one statement; the follow-up work is permissions and name resolution.

Main statement
PostgreSQL
Также охватывает
SQL Server

The task

Ownership of a table is moving to another team or the table is being filed away, and the namespace should reflect that without a data copy.

The snippet

Written for PostgreSQL. Versions for SQL Server are under Variations.

PostgreSQL
ALTER TABLE public.events SET SCHEMA archive;

Как это работает

SET SCHEMA is a catalog change: the table keeps its data and grants, and its indexes, constraints and owned sequences (serial or identity) move with it. Views and foreign keys keep working because they reference the table by OID. What breaks is name resolution: code that uses the unqualified name finds nothing unless the new schema is on its search_path. You must own the table and have CREATE on the target schema.

Variations

SQL Server

SQL Server
ALTER SCHEMA archive TRANSFER dbo.Events;
-- indexes and constraints follow, but every permission
-- granted on the table is dropped; re-grant afterwards

PostgreSQL: whole batch

PostgreSQL
-- move every table of a tenant schema at once
DO $$
DECLARE t record;
BEGIN
  FOR t IN
    SELECT table_name FROM information_schema.tables
    WHERE table_schema = 'tenant_42' AND table_type = 'BASE TABLE'
  LOOP
    EXECUTE format('ALTER TABLE %I.%I SET SCHEMA archive', 'tenant_42', t.table_name);
  END LOOP;
END $$;

Questions that come up

Why do my queries fail after the move?

Unqualified names resolve through search_path, and the table's new schema is probably not on it. Either qualify names, extend search_path for the affected roles, or create a view with the old name for a transition period.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.