Introduction
Schemas help organize database objects like tables and views. The public schema is the default place for these objects, while custom schemas let you group objects separately for clarity and control.
CREATE SCHEMA schema_name; -- To create a custom schema SET search_path TO schema_name, public; -- To use a custom schema along with public SELECT * FROM schema_name.table_name; -- To query a table in a specific schema
CREATE TABLE public.users ( id SERIAL PRIMARY KEY, name TEXT );
CREATE SCHEMA sales; CREATE TABLE sales.orders ( order_id SERIAL PRIMARY KEY, amount NUMERIC );
SET search_path TO sales, public; SELECT * FROM orders;
SELECT * FROM public.users;
CREATE SCHEMA hr; CREATE TABLE hr.employees ( id SERIAL PRIMARY KEY, name TEXT ); INSERT INTO hr.employees (name) VALUES ('Alice'), ('Bob'); SELECT * FROM hr.employees;
public schema in PostgreSQL?public schema is created by default in every new database.public schema automatically.sales in PostgreSQL?CREATE SCHEMA schema_name;.CREATE SCHEMA marketing; CREATE TABLE marketing.campaigns (id SERIAL PRIMARY KEY, name TEXT); SET search_path TO marketing, public; SELECT * FROM campaigns;
search_path is set to look first in marketing schema, then public.campaigns exists in marketing schema, so the query finds and returns data from marketing.campaigns.SELECT * FROM sales.orders;
ERROR: schema "sales" does not exist.hr and finance. You create tables with the same name employees in both schemas. How can you write a query to select all employees from the finance schema without changing the search_path?finance.employees which directly accesses the table in the finance schema without changing search_path.Pass the test and this pattern moves unknown