0
0
PostgresqlConceptBeginner · 3 min read

What is Schema in PostgreSQL: Definition and Usage

In PostgreSQL, a schema is a way to organize and group database objects like tables and views within a database. It acts like a folder that helps keep related data separate and manageable inside the same database.
⚙️

How It Works

Think of a PostgreSQL database as a big filing cabinet. Inside this cabinet, a schema is like a drawer where you keep related files together. Each schema can hold tables, views, functions, and other objects, keeping them organized and easy to find.

This organization helps avoid name conflicts. For example, two different schemas can have tables with the same name without causing confusion, just like two drawers can have files named the same but kept separate.

By default, PostgreSQL creates a schema called public where objects are stored if no other schema is specified. You can create your own schemas to better organize your data based on your application's needs.

💻

Example

This example shows how to create a schema, add a table inside it, and query data from that table.

sql
CREATE SCHEMA sales;

CREATE TABLE sales.customers (
  id SERIAL PRIMARY KEY,
  name VARCHAR(100),
  email VARCHAR(100)
);

INSERT INTO sales.customers (name, email) VALUES ('Alice', 'alice@example.com');

SELECT * FROM sales.customers;
Output
id | name | email ----+-------+---------------------- 1 | Alice | alice@example.com (1 row)
🎯

When to Use

Use schemas when you want to organize your database objects logically. For example, if you have different parts of an application like sales, inventory, and users, you can create separate schemas for each.

This helps teams work independently on different parts without interfering with each other's tables. It also improves security by controlling access to specific schemas.

Schemas are useful in multi-tenant applications where each tenant's data is stored in its own schema to keep data isolated.

Key Points

  • A schema groups related database objects inside a PostgreSQL database.
  • It helps avoid name conflicts by separating objects with the same name.
  • Default schema is public, but you can create custom schemas.
  • Schemas improve organization, security, and multi-tenant data isolation.

Key Takeaways

A schema in PostgreSQL organizes database objects like tables and views within a database.
Schemas act like folders to separate and manage related data easily.
You can create multiple schemas to avoid name conflicts and improve data organization.
Schemas help with security and multi-tenant data isolation.
The default schema is called public, but custom schemas are recommended for complex applications.