Clusters, Databases and Schemas
A new developer at Pedal writes a query that joins pedal.public.rentals to a table in the billing database, and PostgreSQL refuses. The query is fine; the mental model is wrong. PostgreSQL arranges objects in a strict nesting, and knowing the layers tells you what can see what.
The rule
A cluster holds databases; a database holds schemas; a schema holds tables.
- Cluster: one running PostgreSQL server and the data directory it manages. Pedal's server
db1is one cluster. Roles (users) belong to the cluster, so one login works for every database in it. - Database: a separate, self-contained collection of objects. A connection always goes to exactly one database, and a normal query cannot reach into another one. A fresh cluster already has
postgres,template0andtemplate1;CREATE DATABASEcopiestemplate1by default. - Schema: a namespace inside a database, like a folder. Every database starts with a schema called
public. Unlike databases, schemas in the same database can be joined freely. - Table (and view, function, sequence, index): lives in exactly one schema.
A fully qualified name reads from the outside in, but only the last two parts are needed once you are connected:
-- connected to database "pedal"
CREATE SCHEMA billing;
CREATE TABLE billing.invoices (invoice_id bigint PRIMARY KEY, rental_id bigint);
SELECT r.rental_id, i.invoice_id
FROM public.rentals AS r
JOIN billing.invoices AS i USING (rental_id); -- two schemas, one database: fineWhen you write a bare name like rentals, PostgreSQL searches the schemas listed in search_path, which defaults to "$user", public: first a schema named after your role, then public.
Inside the cluster, one main server process (the postmaster) listens for connections and starts a backend process for each client, alongside helper processes such as the checkpointer and autovacuum. You will meet those helpers later in the course.