How to move tables from public to other schema in Postgres
⚡TLDR
Transfer a public
table to target_schema
in PostgreSQL swiftly:
Proceed only if target_schema
already exists:
Use a script for multiple tables and enjoy your coffee while tables move themselves.
Pre-migration Checkup
Ensuring Smooth Transition
Identify the interdependencies that might affect the move:
- Indexes & Constraints: Verify their existence and recreate within the new schema as needed.
- Referenced Sequences: Make sure sequences paired with primary keys remain valid after the move.
- Trigger Functions: Use
ALTER FUNCTION .. SET SCHEMA
if moves impact trigger actions.
Moving Tables Right
Follow these steps for a smooth transition with no hiccup or coffee spill:
- Create Empty Schema:
- Transfer Table: Migrate each table individually, all data included!
- Update Foreign Keys: Update any tables having foreign keys that reference the moved table.
- Check Sequences: Check primary key sequences post-move to ensure sequence ownership remains intact.
Advanced Measures
- Syntax Compatibility: Ensure the syntax is compliant with your PostgreSQL version.
- Data Consistency: When moving populated tables, be cautious to avoid data corruption.
- Trigger Functions: Use
ALTER FUNCTION .. SET SCHEMA
for smoother trigger function relationships post-move.
Visualization
Imagine shifting tables in PostgreSQL like relocating from one apartment to another:
Here comes the moving truck:
Finally, Home sweet home:
All safe at their new address!
Automating your move
Scripting the Process
For a hands-free transfer, swing into action with a dynamic SQL script:
Guarding Against Pitfalls
- Broken Dependencies:
pg_dump
can help reveal dependencies, preventing post-migration breakages. - Invalid Foreign Keys: Revalidate foreign keys post-migration to avoid "dangling" relations.
- Privilege Issues: Mind to check if the acting role has suitable access rights for such schema operations.
Linked
Was this article helpful?