public#
1. What is public in PostgreSQL?#
public is a schema, not a database, not a table.
π¦ Database β π Schemas β π Tables
So here:
MyDB
βββ Schemas (1)
βββ public
public is the default schema inside every PostgreSQL database.
2. Why does public exist?#
- PostgreSQL creates public automatically so beginners can:
Create tables immediately
Avoid learning schemas at the start
Run SQL without qualification
Example:
CREATE TABLE users (...);
Postgres silently does:
CREATE TABLE public.users (...);
3. Default behavior of public#
By default:
Behavior |
Status |
|---|---|
Exists automatically |
β |
In every database |
β |
Writable by everyone |
β οΈ YES |
In search_path |
β |
Beginner-friendly |
β |
Production-safe |
β |
4. Why public is dangerous in real systems#
This is very important.
- Problems with public
Everyone can create tables
No ownership boundaries
Name collisions
Security risks
Hard to audit
Bad multi-app support
Example nightmare:
CREATE TABLE users (...); -- app A
CREATE TABLE users (...); -- app B
Same schema β conflict.
How PostgreSQL finds public (search_path)
Check:
SHOW search_path;
Default:
"$user", public
- Meaning:
Look in schema named after user
Then look in public
Thatβs why tables βmagicallyβ work without schema names.
5. Who owns public?#
SELECT nspname, nspowner::regrole
FROM pg_namespace
WHERE nspname = 'public';
Usually:
public | postgres
But permissions are open unless you change them.
6. Best Practice (what professionals do)#
1οΈβ£ Keep public EMPTY
Do not put app tables there.
2οΈβ£ Lock it down
REVOKE CREATE ON SCHEMA public FROM PUBLIC;
REVOKE ALL ON SCHEMA public FROM PUBLIC;
- Now:
No accidental tables
No unauthorized access
3οΈβ£ Create real schemas
CREATE SCHEMA app;
CREATE SCHEMA auth;
CREATE SCHEMA audit;
4οΈβ£ Use explicit schema names
CREATE TABLE app.users (...);
CREATE TABLE auth.accounts (...);
7. What public is still useful for#
- You can keep public for:
Extensions (sometimes)
Shared utility views
Temporary experiments (dev only)
But never core business tables.
Important rule to remember
public is for learning β not for production.
Summary
β public = default schema
β Exists in every database
β Auto-used by SQL
β Open permissions by default
β Not production-safe
β Lock it down
β Create app-specific schemas