What is Schema in PostgreSQL: Definition and Usage
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.
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;
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
schemagroups 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.