search_path Schema Name Resolution

Unqualified table and function names resolve through search_path left to right, so switching schemas re-points the same queries.

SqlConfig Management

Code

snippet
-- 模式是命名空间:同名表可以各放一份
CREATE SCHEMA billing;
CREATE SCHEMA analytics;

CREATE TABLE billing.invoices (id integer, cents bigint);
CREATE TABLE analytics.invoices (id integer, cents bigint);

-- 未限定名字按 search_path 从左到右 resolution,第一个匹配生效
SHOW search_path;

SET search_path = billing, public;
INSERT INTO invoices (id, cents) VALUES (1, 500);  -- 落到 billing.invoices

SET search_path = analytics, public;
SELECT * FROM invoices;                            -- 现在读到 analytics.invoices

-- 带 schema 前缀永远精确,不受会话设置影响
SELECT * FROM billing.invoices WHERE id = 1;

-- search_path 解析表、函数与运算符;列名不参与,列永远属于被查询的表
SELECT current_user, current_schema;

How the snippet works

What runs here is SELECT / INSERT / CREATE — invoices and billing.invoices are the objects involved.

Breaking the statements into their working parts: a WHERE clause constraining which rows the statement operates on.

Applying it

The invoices table is the working surface here.

Statements that matter

SELECT * FROM billing.invoices WHERE id = 1;
SELECT * FROM invoices;                            -- 现在读到 analytics.invoices
INSERT INTO invoices (id, cents) VALUES (1, 500);  -- 落到 billing.invoices

Interactive Tools for This Topic

FAQ

What relations does the SQL touch?
`invoices`, `billing.invoices`.