Concept Flow - Creating and switching schemas
Start
Create Schema
Switch Schema with SET search_path
Run Queries in New Schema
End
First, create a new schema. Then switch to it using SET search_path. Finally, run queries in the new schema.
CREATE SCHEMA sales; SET search_path TO sales; CREATE TABLE customers(id SERIAL PRIMARY KEY, name TEXT); INSERT INTO customers(name) VALUES ('Alice'); SELECT * FROM customers;
| Step | Command | Action | Result | Current Schema |
|---|---|---|---|---|
| 1 | CREATE SCHEMA sales; | Create new schema 'sales' | Schema 'sales' created | public |
| 2 | SET search_path TO sales; | Switch default schema to 'sales' | search_path set to 'sales' | sales |
| 3 | CREATE TABLE customers(...); | Create table 'customers' in 'sales' | Table 'customers' created | sales |
| 4 | INSERT INTO customers(name) VALUES ('Alice'); | Insert row into 'customers' | 1 row inserted | sales |
| 5 | SELECT * FROM customers; | Select all rows from 'customers' | Returns: id=1, name='Alice' | sales |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | After Step 4 | After Step 5 |
|---|---|---|---|---|---|---|
| search_path | public | public | sales | sales | sales | sales |
| schemas | public | public, sales | public, sales | public, sales | public, sales | public, sales |
| tables in sales | none | none | none | customers | customers with 1 row | customers with 1 row |
CREATE SCHEMA schema_name; -- creates a new schema SET search_path TO schema_name; -- switches default schema Unqualified table names use current search_path schema Use to organize database objects logically Switching schema affects where tables are created and queried
sales?CREATE SCHEMA schema_name;.sales.CREATE SCHEMA marketing; SET search_path TO marketing; CREATE TABLE campaigns (id SERIAL PRIMARY KEY, name TEXT);
campaigns belong to?search_path to marketing means new objects are created in that schema by default.CREATE TABLE campaigns command creates the table inside the current schema in search_path, which is marketing.SET search_path TO sales; but get an error: ERROR: schema "sales" does not exist. What is the most likely cause?sales does not exist, so PostgreSQL cannot set search_path to it.CREATE SCHEMA sales;.public and archive. You want to query a table named orders in archive without typing the full name every time. Which command will let you switch your session to use archive schema first, then public?SET search_path TO schema1, schema2; to set schema priority.archive first, then public.Pass the test and this pattern moves unknown