MSDN SQL Server Documentation

Explore the depths of SQL Server database objects and features.

Database Schemas

A database schema is a collection of related database objects that are organized under a single namespace. Schemas provide a logical grouping mechanism for objects such as tables, views, stored procedures, and functions. They are essential for managing permissions, organizing complex databases, and improving security.

What is a Schema?

In SQL Server, a schema is a container for database objects. It acts as a namespace, allowing you to group related objects together. This helps in:

Default Schemas

When a database is created, it typically comes with a few default schemas:

Creating and Managing Schemas

You can create new schemas using the CREATE SCHEMA statement. Here's a basic example:


CREATE SCHEMA Sales
AUTHORIZATION dbo;
            

You can also associate existing objects with a schema or transfer ownership of schemas. The ALTER SCHEMA statement is used for these operations:


ALTER SCHEMA Production TRANSFER Sales.Customers;
            

Common Use Cases

Schemas are widely used to:

Viewing Schema Information

You can query the system catalog views to see information about schemas and their objects:


SELECT s.name AS SchemaName,
       u.name AS OwnerName
FROM sys.schemas AS s
JOIN sys.database_principals AS u
  ON s.principal_id = u.principal_id;

SELECT SCHEMA_NAME(schema_id) AS SchemaName,
       name AS ObjectName,
       type_desc AS ObjectType
FROM sys.objects
WHERE SCHEMA_NAME(schema_id) = 'Sales';
            

Understanding and utilizing schemas effectively is a fundamental aspect of database design and administration in SQL Server.