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.
Code
-- 模式是命名空间:同名表可以各放一份
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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.CSS Color Name LookupTranslate between CSS keyword color names and hex values with RGB and HSL conversions, exact name matching, and nearest-color suggestions.
FAQ
- What relations does the SQL touch?
- `invoices`, `billing.invoices`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.