{"canonical_url":"https://engineer.company/glossary/schema/","content_markdown":"# Schema\n\n## What it is\n\nA schema is a namespace inside a database: a container for tables, views, data\ntypes, functions and operators, so that the same name can be used in two schemas\nwithout conflict. PostgreSQL's manual compares schemas to directories in a file\nsystem, except that they cannot be nested: a database holds schemas, and schemas\nhold objects. The word has a second, looser sense, just as common: the schema of\na database is its whole structure, every table, column, key and constraint. Both\nsenses appear below, and the plural, schemas, almost always means the\nnamespaces.\n\nA billing area of an application can live in its own schema, and a session can\nchoose which schemas it looks in:\n\n```sql\nCREATE SCHEMA billing;\n\nCREATE TABLE billing.invoices (\n  id     bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,\n  total  numeric(12, 2) NOT NULL\n);\n\nSHOW search_path;                  -- \"$user\", public\nSET search_path = billing, public;\nSELECT count(*) FROM invoices;     -- now resolves to billing.invoices\n```\n\nA name written with its schema, such as `billing.invoices`, always means the\nsame table. A name written without one is looked up through search_path, a list\nof schemas the server walks in order until it finds a match. The default list is\n`\"$user\", public`: a schema named after the current role, if one exists, then\nthe public schema every new database starts with. The first existing schema in\nthe path is also where CREATE TABLE puts a table whose name carries no schema,\nwhich is why objects land in public unless someone says otherwise. A name found\nin none of the listed schemas raises an error, even when another schema of the\nsame database holds it.\n\n## Why it matters\n\nThe first reason is organisation. A database with a few hundred tables needs a\nlevel above the table, and schemas provide it: billing in one, accounts in\nanother, a third-party tool's tables in a third, clear of everyone else's names.\nA client connection reaches a single database, but schemas are not rigidly\nseparated: a role can use objects in any schema of the database it is connected\nto, privileges permitting, and one query can join tables from several of them.\n\nThe second reason is access control. USAGE on a schema lets a role look up the\nobjects inside it, and CREATE lets it add new ones. Taking USAGE away blocks\naccess to the objects, although their names can still be read from the system\ncatalogs, so a schema guards the data and not the knowledge of what exists.\n`CREATE SCHEMA name AUTHORIZATION role` hands a new schema to a role, and names\nbeginning with `pg_` are reserved for the system.\n\nThe third reason is security, because schemas take part in name resolution. Most\nnames in queries are written without a schema, so, in the manual's words, adding\na schema to search_path effectively trusts every role that can create objects in\nit. Such a role can make an ordinary query run functions of its choosing, as\nthough the person running the query had called them. The secure patterns keep\nschemas that others can write to off a user's path, for example one private\nschema per user, created with `CREATE SCHEMA alice AUTHORIZATION alice`, which\nthe `\"$user\"` entry then finds first. PostgreSQL 15 moved new databases in that\ndirection: it removed the right of every role to create objects in public and\nmade the database owner, through the pg_database_owner role, the owner of\npublic.\n\nPortability is the last point. The SQL standard has schemas but no public\nschema, and the manual notes that some SQL systems might not implement schemas\nat all. Qualified names travel better than code that leans on search_path.\n\n## What it looks like in practice\n\nThe data model in\n[Modeled 348 tables across 34 Postgres schemas](/portfolio/modeled-348-tables-across-34-postgres-schemas/)\nuses schemas in the first sense, as the level above the table. The maritime\ndomain, with its professionals, companies, ships, jobs and reviews, is laid out\nas normalized PostgreSQL schemas organised by domain: 348 tables across 34 of\nthem. Table names are plural inside singular-named schemas, without exception,\nwhich also sidesteps a lot of reserved-word collisions, and real foreign keys\nand constraints hold the relationships between them. Adding a feature usually\nmeans extending the schema along the existing grain rather than working against\nit, which the page calls the only reason 34 schemas is a structure rather than a\nsprawl.\n\nA schema can also be a boundary between two jobs. In\n[Built Stripe and in-app purchase entitlements](/portfolio/built-stripe-and-in-app-purchase-entitlements/)\nStripe card payments and Apple and Google in-app purchases all converge on a\npayments schema of 9 tables and 34 functions. A separate access schema of 11\ntables and 34 functions answers \"may this account do this?\" without knowing\nwhich storefront paid for it, and that answer, re-checked on the server on every\nrequest, gates the company directory, search and data export. The cost, as the\npage puts it, is two schemas where a smaller product would want one, plus an\nentitlement lookup on requests that would otherwise have been free.\n\nThe second sense of the word is the subject of\n[1,022 migrations behind a schema drift gate](/portfolio/1022-migrations-behind-a-schema-drift-gate/).\nMost projects describe a schema twice, in the initial setup that builds it from\nscratch and in the migrations that grew it, and the two drift apart unless\nsomething checks them. Here the database is versioned as 1,022 migrations,\nnumbered from 036 through 1102, and a CI job builds it twice on every change,\nonce fresh and once with every migration replayed in order, then compares the\ntwo: the seeded data as well as the structure. A migration that backfills a\nlookup table wrongly does as much damage as one that forgets a column, and only\none of those shows up in a schema diff. Any disagreement fails the build with\nthe difference printed, so every migration has to work replayed and from cold.\n\n## Where it goes wrong\n\n**A function planted in a shared schema.** The PostgreSQL wiki's guide to\nCVE-2018-1058 shows the attack: one user creates `lower(varchar)` in public. The\nbuilt-in `lower` lives in pg_catalog and takes text, so for a varchar column the\nplanted function is the closer match, and a colleague who runs\n`SELECT lower(full_name) FROM a` runs the planted code instead. Qualify calls in\nsensitive code as `pg_catalog.lower`, take CREATE on public away from the roles\nthat do not need it, and list what is already there with `\\df public.*`.\n\n**An upgrade that kept the old permissions.** PostgreSQL 15's safer default\napplies to new clusters and newly created databases. Upgrading a cluster or\nrestoring a dump preserves the permissions public already had, so a server on\nversion 15 or later can still let every role create objects there. The manual\ncalls the default path with CREATE granted on public never a secure pattern, and\nnotes that it is the default in databases upgraded from 14 or earlier. In such a\ndatabase, run `REVOKE CREATE ON SCHEMA public FROM PUBLIC`, then audit public\nfor objects named like those in pg_catalog.\n\n**A table created in the wrong place.** A migration creates `invoices` without a\nschema, and the table goes into the first existing schema on the path of\nwhichever role runs it. The application, connecting with another path, then\nreads a different table or gets `relation \"invoices\" does not exist`. Qualify\nevery name in migrations, and check `SELECT current_schema()` in the session\nthat runs them.\n\n**A drop that reaches past the schema.** `DROP SCHEMA billing` refuses while the\nschema holds anything, because RESTRICT is the default. With CASCADE it drops\nevery object inside and every object that depends on those, and the manual warns\nthat this can remove objects in schemas other than the one named. Its advice is\nto run the DROP without CASCADE first and read the DETAIL lines, which list what\nwould go.\n\n**A name the system resolves first.** pg_catalog is implicitly searched before\nthe schemas listed in search_path when the path leaves it out. When it is named\nexplicitly, its position in the path\ndetermines the search order. A table of your own whose name\nbegins with `pg_` can be shadowed when a later version adds a system table of\nthe same name, so the manual advises against such names. Reserved words such as\n`user` and `order` cause a milder version of the trouble: a table named that way\nneeds double quotes in every statement.\n\n## Further reading\n\n- [5.10. Schemas](https://www.postgresql.org/docs/current/ddl-schemas.html)\n  — the manual's chapter: qualified names, the public schema, search_path,\n  secure usage patterns and portability.\n- [CREATE SCHEMA](https://www.postgresql.org/docs/current/sql-createschema.html)\n  — the command's syntax, the AUTHORIZATION clause, the reserved `pg_` prefix\n  and where PostgreSQL departs from the standard.\n- [5.8. Privileges](https://www.postgresql.org/docs/current/ddl-priv.html)\n  — what USAGE and CREATE mean on a schema, alongside every other privilege.\n- [E.20. Release 15](https://www.postgresql.org/docs/15/release-15.html)\n  — the release that removed CREATE on public from new databases and kept it\n  for upgraded ones.\n- [A Guide to CVE-2018-1058: Protect Your Search Path](https://wiki.postgresql.org/wiki/A_Guide_to_CVE-2018-1058%3A_Protect_Your_Search_Path)\n  — the project's walk-through of the planted-function attack, with the fixes\n  and the commands to audit a database.\n\n\u003chttps://engineer.company/glossary/schema/\u003e\n","date_modified":"2026-11-09T21:50:25Z","description":"What a schema is in PostgreSQL, how search_path decides which table a bare name means, why the public schema needs locking down, and where it goes wrong.","formats":{"gemtext":"https://engineer.company/glossary/schema/index.gmi","gopher":"https://engineer.company/glossary/schema/gophermap","html":"https://engineer.company/glossary/schema/","json":"https://engineer.company/glossary/schema/index.json","markdown":"https://engineer.company/glossary/schema/index.md","pdf":"https://engineer.company/glossary/schema/index.pdf"},"kind":"page","language":"en","title":"What is a schema?","url":"https://engineer.company/glossary/schema/","version":1}