← Back to PostgreSQL, page 1

postgresql-0007 · Easy fresher

How do schemas and search_path decide which table a query uses?

A schema is a namespace inside a database. Unqualified names are looked up in the schemas listed in search_path, in order, and the first match wins. Qualify names (sales.orders) in scripts and functions to avoid surprises, and set search_path deliberately for each application role.

Full answer

Tables and rows used here:

sql
CREATE SCHEMA sales;
CREATE SCHEMA archive;
CREATE TABLE sales.orders (id int, note text);
CREATE TABLE archive.orders (id int, note text);
INSERT INTO sales.orders VALUES (1, 'current');
INSERT INTO archive.orders VALUES (1, 'old');
sql
SET search_path TO sales, archive; SELECT note FROM orders;

Result on PostgreSQL 17:

text
   note
---------
 current
(1 row)
sql
SET search_path TO archive, sales; SELECT note FROM orders;

Result:

text
 note
------
 old
(1 row)
sql
SELECT (SELECT note FROM sales.orders) AS qualified_sales, current_schemas(false)::text AS path;

Output:

text
 qualified_sales |       path
-----------------+-----------------
 current         | {archive,sales}
(1 row)
sql
DROP SCHEMA sales CASCADE; DROP SCHEMA archive CASCADE;

PostgreSQL returns:

text
NOTICE:  drop cascades to table sales.orders
NOTICE:  drop cascades to table orders
DROP SCHEMA

The same unqualified query reads a different table depending on the order of search_path. The qualified name always reads sales.orders. current_schemas(false) shows the effective path without the implicit pg_catalog. Because a schema earlier in the path can shadow a table or function with the same name, functions marked SECURITY DEFINER should set their own search_path, and applications should not let untrusted users create objects in schemas on their path. The last run removes the two demo schemas.

sql
CREATE SCHEMA sales;
CREATE SCHEMA archive;
CREATE TABLE sales.orders (id int, note text);
CREATE TABLE archive.orders (id int, note text);
INSERT INTO sales.orders VALUES (1, 'current');
INSERT INTO archive.orders VALUES (1, 'old');

SET search_path TO sales, archive; SELECT note FROM orders;

SET search_path TO archive, sales; SELECT note FROM orders;

SELECT (SELECT note FROM sales.orders) AS qualified_sales, current_schemas(false)::text AS path;

DROP SCHEMA sales CASCADE; DROP SCHEMA archive CASCADE;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • Schemas are namespaces
  • search_path order decides unqualified names
  • Qualify names in scripts
  • Shadowing is a security concern
  • Set search_path per role

Common mistakes

  • Relying on the default public schema for everything
  • SECURITY DEFINER functions without a fixed search_path

Follow-ups

  • Why did PostgreSQL 15 change public schema permissions?
  • How would you use schemas for multi-tenant data?

Tips

  • Show the order effect