PostgreSQL Schema vs Database: Which Should Separate Your Modules or Tenants?
Disclosure: I build Schemity , a desktop ERD tool - this post is from our blog and uses it for the examples. TL;DR: Use schemas to separate modules that still reference each other: a foreign key, a join and a transaction all cross a schema and none crosses a database. Use a separate database only when two parts must never share a transaction, a connection or a backup. For tenants, a schema each…
In the world of database management, PostgreSQL offers a solution for separating modules or tenants within a single database or across multiple databases. The choice hinges on the level of interaction between the components.
If two modules still reference each other through foreign keys, joins, or transactions, using separate schemas within one database is recommended. This approach leverages the schema's namespace feature, allowing these connections to still function. For instance, in the provided example, both the "identity" and "billing" schemas have tables that reference each other via foreign keys.
On the other hand, if two modules must never share a transaction, connection, or backup, a separate database is the way to go. This ensures maximum isolation and avoids any potential issues that could arise from sharing resources.
In terms of performance, creating a schema takes about 2.6 milliseconds with no files on disk, while creating a database takes around 44 milliseconds and occupies 7.6 MB. Moving a table between schemas is swift, taking only 2.6 milliseconds. However, when it comes to migration, both schemas and databases require dump and restore operations, with the former being more efficient in this case.
It's worth noting that a PostgreSQL schema is similar to a MySQL database, as both can reference each other. However, the key difference lies in the level of isolation – schemas within one database can interact, while databases on separate servers cannot.
In conclusion, when deciding between PostgreSQL schemas and databases for module or tenant separation, consider the level of interaction required. Schemas within one database are suitable for modules with some form of interaction, while separate databases are the better choice when components must remain completely isolated.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to