Schema in SQL
? Schema in SQL
A Schema in SQL is a logical container or namespace that holds database objects such as tables, views, indexes, stored procedures, and more. It helps organize and group related database objects within a database.
Key Points about Schema:
A database can contain multiple schemas.
Each schema can contain multiple objects.
Schemas help manage permissions and avoid name conflicts.
Fully qualified object name syntax:
schema_name.object_nameSchemas are similar to folders/directories in a file system.
Why Use Schemas?
Organize database objects logically.
Provide security by granting/restricting permissions at the schema level.
Manage large databases better by grouping related tables, functions, etc.
Different applications can use different schemas within the same database.
Example in SQL Server:
-- Create a schema named 'sales'CREATE SCHEMA sales;-- Create a table inside the 'sales' schemaCREATE TABLE sales.orders ( order_id INT PRIMARY KEY, customer_id INT, order_date DATE);-- Query table with schema-qualified nameSELECT * FROM sales.orders;Example in PostgreSQL:
-- Create a schema named 'marketing'CREATE SCHEMA marketing;-- Create a table in the marketing schemaCREATE TABLE marketing.campaigns ( campaign_id SERIAL PRIMARY KEY, campaign_name VARCHAR(100));-- Access the tableSELECT * FROM marketing.campaigns;Notes:
In MySQL, the term "schema" is often used synonymously with "database".
In Oracle, schemas correspond to database users; each user owns a schema.
Want to know how to manage schema permissions or drop a schema?