← Back to PostgreSQL, page 2

postgresql-0030 · Easy fresher

Explain how a PostgreSQL server is organised: cluster, database, schema, role and tablespace.

One PostgreSQL server process manages a cluster: a data directory holding several databases. Each database contains schemas, which contain tables, views and functions; queries cannot join tables across databases directly. Roles (users and groups) are global to the cluster, and tablespaces map storage to directories.

Full answer

The hierarchy, from the outside in:

  • Cluster: one running server (one port, one data directory) with shared configuration, WAL and roles. initdb creates it.
  • Database: an isolated set of schemas. A connection is always to one database, so cross-database queries need extensions such as postgres_fdw or dblink.
  • Schema: a namespace inside a database (public by default). Schemas can be joined across freely within the same database.
  • Objects: tables, indexes, views, sequences, functions and types live in schemas.
  • Roles: global to the cluster. A role with LOGIN acts as a user; roles can be members of other roles, which is how groups are built. Privileges are granted per object, schema or database.
  • Tablespaces: optional storage locations; most deployments use only the default.

A common design question is whether tenants or modules should be separate databases or separate schemas. Schemas allow joins and share one connection pool; databases give stronger isolation and separate backups but cannot be queried together. This item is descriptive and has nothing to run.

Key points

  • A cluster is one server with many databases
  • Connections target one database
  • Schemas are namespaces within a database
  • Roles are cluster-wide
  • Choose schemas versus databases deliberately

Common mistakes

  • Expecting cross-database joins to work
  • Granting everything to one superuser role

Follow-ups

  • How do you give a role read-only access to a schema?
  • When would you use postgres_fdw?

Tips

  • Draw the hierarchy