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