Sub topic 1
How a PostgreSQL server is organized
This chapter explains the containment model that every later chapter relies on: a server holds databases, a database holds schemas, and a schema holds objects. Knowing where each object lives tells you which command to run and why a query sometimes can't "see" a table you know exists.
Prerequisites
This chapter assumes you have:
- Basic SQL:
SELECT,WHERE,JOIN,ORDER BY. - Basic relational concepts: tables, columns, primary keys and foreign keys.
- Comfort using a terminal.
- A PostgreSQL server you can reach, either installed locally or hosted elsewhere.
You don't need to run anything yet. Connecting with psql is the topic of the next chapter.
The four levels
A PostgreSQL installation is organized as a hierarchy.
- Server (cluster). One running PostgreSQL instance, listening on one port (5432 by default). It manages one data directory. The word "cluster" here means a collection of databases managed by one server. It does not mean several machines.
- Database. A named container inside the server, such as
mydborpostgres. - Schema. A namespace inside a database, such as
public. A schema groups objects and keeps their names from colliding. - Object. A table, view, index, sequence, function, type, and so on. Every object belongs to exactly one schema.
A fully qualified object name has the form schema.object, for example public.orders. Within a database you can write sales.monthly_totals. You can't write mydb.sales.monthly_totals to reach into a different database. The three-part form is accepted only when the database name matches the one you are connected to.
Databases are isolated from each other
A connection is made to one database. Once connected, you can only query objects in that database. A SELECT against a table in another database fails with an error, even if the server is the same.
SELECT * FROM otherdb.public.orders;
-- ERROR: cross-database references are not implemented: otherdb.public.ordersThis is the most common surprise for people coming from MySQL, where "database" and "schema" are the same thing. In PostgreSQL they are different levels. If you need data from two databases, you use a foreign data wrapper or dblink, or you put the data in two schemas of one database.
What the databases on a server do share:
- Roles. Users and groups are defined at the server level, not per database. A role named
aliceis the same role everywhere. What she may do in each database is controlled separately. - Tablespaces. These map objects to storage locations and are also server-wide.
- Configuration and processes. Memory settings, the write-ahead log and background workers belong to the server.
Template databases and the default databases
A new server usually contains three databases you didn't create.
| Database | Purpose |
|---|---|
| `postgres` | An empty default database for administrative connections. |
| `template1` | The template copied by `CREATE DATABASE` when you don't name another one. Objects you add here appear in every new database. |
| `template0` | A pristine copy of the template. Use it when you need a new database with a different encoding or locale. |
Treat template0 and template1 as read-only for everyday work. Adding objects to template1 by accident means they silently show up in every database you create afterward.
Schemas and the search path
Every new database starts with a public schema. Tables you create without a schema name usually land there. PostgreSQL also keeps built-in schemas in every database.
| Schema | What it holds |
|---|---|
| `public` | The default schema for user objects. |
| `pg_catalog` | System catalogs and built-in functions and types. |
| `information_schema` | Standard SQL views that describe the database's structure. |
| `pg_toast` | Storage for oversized column values. You rarely look at it directly. |
When you write an unqualified name like orders, PostgreSQL looks for it in the schemas listed in the search_path setting, in order. The default is "$user", public. The first part means "a schema named after the current role, if one exists." The system schema pg_catalog is always searched first unless you list it explicitly.
SHOW search_path; search_path
-----------------
"$user", publicTwo consequences matter when you explore a database:
- A table in a schema that is not on the search path is invisible by short name.
SELECT * FROM ordersfails withrelation "orders" does not exist, whileSELECT * FROM sales.ordersworks. - Two schemas can each contain a table named
orders. The unqualified name resolves to the first one found on the path. Qualify names when you aren't sure.
What counts as an object
Several kinds of object live in a schema, and they share one namespace for relations. A table and a view in the same schema can't have the same name.
| Object | Notes |
|---|---|
| Table | Stores rows. |
| View | A saved query that behaves like a table when read. |
| Materialized view | A saved query whose result is stored and must be refreshed. |
| Index | A lookup structure on a table. It lives in the same schema as its table by default. |
| Sequence | A counter, often behind an auto-numbered column. |
| Function / procedure | Stored code. Functions can be overloaded, so the same name may exist several times with different argument types. |
| Type | Enumerated, composite, domain and other custom types. |
Some things are not inside schemas. Roles, databases and tablespaces belong to the server as a whole. Extensions are installed per database, and their objects normally land in a schema.
Where the system keeps its own metadata
PostgreSQL describes itself with ordinary tables and views. These are the system catalogs. Most live in pg_catalog, such as pg_class (relations), pg_namespace (schemas) and pg_database (databases). A few, like pg_database and pg_roles, hold server-wide data and look the same from every database.
Because the catalogs are queryable with plain SQL, every graphical tool and every psql meta-command is built on them. When you run \dt in psql or expand a node in pgAdmin, the tool runs catalog queries behind the scenes. You can see the same facts with a query:
SELECT datname FROM pg_database WHERE NOT datistemplate ORDER BY datname;This lists the databases on the server except the template ones. It works from any database on the server, because pg_database is shared.
Common errors and how this model explains them
| Symptom | Likely cause |
|---|---|
| `database "mydb" does not exist` | You connected to the right server but named a database that isn't there. List databases from `postgres` to check. |
| `relation "orders" does not exist` | Wrong database, or the table is in a schema outside `search_path`. |
| `cross-database references are not implemented` | You tried to query across databases. Connect to the other database instead. |
| `permission denied for schema sales` | The role lacks `USAGE` on the schema, even if it has rights on the table. |
| A table appears in every new database | Someone created it in `template1`. |
Checking your understanding
Exercise
You are connected to the database mydb and run SELECT * FROM invoices;. PostgreSQL answers relation "invoices" does not exist, but a colleague says the table invoices is in the schema billing of the same database. What are two things you can do to read the table, and why does the original query fail?
Show answer
The query fails because the default search_path is "$user", public, so the unqualified name invoices is only looked for in a schema named after your role and in public, and billing isn't searched. You can qualify the name with SELECT * FROM billing.invoices;, or add the schema to the path for your session with SET search_path TO billing, public;.
Exercise
Your application needs to join a table in database crm with a table in database shop, both on the same server. Why does a plain JOIN fail, and what are two ways to solve it?
Show answer
Each connection is bound to one database, and PostgreSQL does not allow ordinary queries to reference objects in another database. You can move the data into two schemas of one database, or use a foreign data wrapper such as postgres_fdw or the dblink extension to reach the other database from the first.
Exercise
Does a role defined while connected to mydb exist in the database postgres as well? Explain.
Show answer
Yes. Roles are defined at the server level, so the role is visible from every database on the server. What it is allowed to do in each database is set separately through privileges.