Part 10 / Topic 1 of 9
Databases, schemas and search_path
You know the hierarchy from Part 1 — the server holds databases, databases hold schemas, and schemas hold tables; now you create the layers yourself. CREATE DATABASE library; makes a new world; this lesson stays inside shopdb and uses a schema instead — a named drawer that keeps the library's tables apart from the shop's:
CREATE SCHEMA library;
CREATE TABLE library.members (
member_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL
);
SELECT count(*) FROM library.members;
CREATE SCHEMA
CREATE TABLE
count
-------
0
(1 row)
Qualified names (library.members) always work. What unqualified names mean is decided by search_path — the list of schemas Postgres searches, in order:
SHOW search_path;
search_path
-----------------
"$user", public
(1 row)
"$user", public means: a schema named after the current user first (usually absent), then public — which is why everything so far landed in public without you asking. Set SET search_path = library, public; and bare members would resolve to the library's. Teams use schemas to group modules, separate tenants, or stage migrations; for this course, one extra schema is all the machinery you need to see.
DROP SCHEMA library CASCADE;
NOTICE: drop cascades to table library.members
DROP SCHEMA
(CASCADE drops the drawer with its contents — the NOTICE lists the casualties. Respect it.)
🧪 Quick quiz — answer from memory, then check.
- What does
search_pathcontrol? - Why did your tables land in
publicall course long?
Show the answers
- Which schemas unqualified names are looked up in, and in what order (first match wins; new unqualified tables go to the first schema in it).
- The default search_path ends in
public, and nothing earlier in it existed.
Done here? The practice set for Part 10 — 6 exercises with solutions — is on the part page.