Что такое schema в БД?
Что такое schema в postgreSQL? Её надо создавать сразу после создания БД? Это логическое устройство таблиц, наполнения, прав и т.д. И тогда может быть много схем и они могут использовать общие таблицы?
![]()
Schemas are analogous to directories at the operating system level, except that schemas cannot be nested.
Схемы — это дополнительный уровень структурирования объектов базы. Похоже на директории в файловой системе или пространства имён ( namespace ) в программировании. Но не могут быть вложенными.
Пользуясь аналогией с файловой системой и вебом: есть файлы стилей CSS, какие-то JS. Ничто не мешает их все размещать в корневой директории веб-сервера. Но обычно их размещают всё-таки в поддиректориях для собственного удобства.
После создания новой базы у вас будет предопределённая схема public с правами для создания новых объектов для всех пользователей. Что делать дальше — решение разработчика схемы этой базы, проигнорировать схемы и размещать всё в public , структурировать как-либо по схемам, можно удалить public схему даже.
- users
- user_settings
- user_favorites
- blog_posts
- blog_comments
- users
- users.settings
- users.favorites
- blog.posts
- blog.comments
Самой базе без разницы. Схемы — это логический уровень, как названия таблиц.
Большинство проектов схемы не используют.
Права: у схем есть права create — кто может создавать новые объекты, и usage — кто может обращаться к объектам в той схеме. Поэтому может быть удобно для разработчиков сделать отдельную схему user_tmp и исключить её из бекапов, а в остальные схемы не давать прав create — тем самым форсируя, что таблицы приложения проходят через обычную принятую у вас процедуру миграций.
Для полноты картины: схемы public может и не быть, если она была удалена в базе, которая указанна в template опции create database
Database Schema in SQL Server
In SQL Server, a schema is a logical collection of database objects such as tables, views, stored procedures, indexes, triggers, functions. It can be thought of as a container, created by a database user. The database user who creates a schema is the schema owner.
- A schema can belong to only one database whereas a database can have one or multiple schemas.
- There are no restrictions on the number of objects in a schema.
- SQL Server provides us with a few built-in schemas such as dbo, guest, sys, etc.
- A database schema can be owned by a database role or an application role along with the database user. They are called schema owners.
- dbo is the default schema for a newly created database.
- Schema ownership can be transferred from one user to another user in the same database.
- A database user can be dropped without dropping the database objects owned by the user. But the schema cannot be deleted if it owns database objects.
Create Schema Using T-SQL
A schema can be created using T-SQL.
In the above syntax, schema_name is the name of the schema you want to create. Optionally, you can specify the schema owner as AUTHORIZATION owner_name .
The following will create a new schema called hrdbo and the default user dbo will be the schema owner.
The following will create a new schema called hrdbo with a user Steve as the schema owner.
The above will create a new schema hrdbo . You can see this in SSMS under Security -> Schemas folder, as shown below.
Database Schema in SQL Server
After you create a schema, you can create objects under this schema and grant permissions to other users.
For example, the following creates a new table under hrdbo schema.
The above will create a new table Consultant in the hrdbo schema, as shown below.
Tables in Database Schema
Modify Schema
Use the ALTER SCHEMA statement to transfer database objects from one schema to another schema in the same database.
In the above ALTER SCHEMA syntax:
- schema_name is the name of a schema in the current database, into which the securable (table, view, stored procedure, etc) will be moved.
- entity_type can be Object, Type or XML Schema Collection.
- securable_name is the name of db object (table, view, stored procedure, etc.) to be moved into the specified schema_name schema.
The following transfers the Employee table from the default dbo schema to hrdbo schema.
The following shows the hrdbo.Employee table.
Note: You can use ALTER AUTHORIZATION statement to change the owner of the schema as shown below:
Delete a Schema
DROP SCHEMA deletes a schema from the database. The schema that is being dropped must not contain any database objects. If the schema contains objects, the DROP statement fails.
The following statement deletes the hrdbo schema provided no objects in that schema.
Create Schema Using SSMS
A schema can also be created in SSMS tool.
Step 1: Open SSMS and connect to the database.
Step 2: In the Object Explorer, expand the Databases folder and expand the instance of the database where you want the new schema to be created.
Step 3: Right-click on the Security folder and select New -> Schema, as shown below.
Database Schema in SQL Server
This will open the Schema New dialog box as below. On the General tab, enter the new schema name and Schema owner, as shown below.
The Schema Owner can be the name of the database user or role which will own the schema. Or to select a User/Role, click on the Search button.
Database Schema in SQL Server
In the Search Roles or User dialog box, click on the Browse button and select a User to whom you want to make as the owner of the Schema. Click Ok.
Database Schema in SQL Server
Step 4: Click on the Permissions page to see the lists of all the securables and the permissions on those securables that can be granted, as shown below.
Database Schema Permissions
Step 5: In the Extended Properties tab, you can add customized properties to store additional information. Every extended property has a user-defined name and value. It is used for adding comments for a database object, as shown below.
Database Schema Extended Properties
Extended properties can be used to store version information, tooltips for user interfaces, data lineage information, descriptions of columns, and many more.
Step 6: Click OK to create the schema and save it.
Step 7: Refresh the Database instance tab. The new schema is created under the Security -> Schema folder, as shown below.
New Schema
Thus, you can create, edit, delete database schemas using T-SQL and SSMS.
What Is a Database Schema? A Quick Guide With Examples
A database schema is an integral part of application or software development, especially those that revolve around data and databases. In short, the database schema is a term used for a structure or layout defining a set of data.
In other words, it describes how the data will be organized and connected. Hence, a database schema may include schema objects like tables, views, fields, relationships, packages, indexes, types, and many other elements.
Database designers create database schemas to establish important elements, attributes, and connections from a specific data group.
It comes in the form of a schema diagram that explains to a database administrator how the data will be stored in a relational or non-relational database. Also, the size and complexity of the diagram depend on the project.
Furthermore, database schemas are necessary for designing database management systems (DBMS) and relational database management systems (RDBMS) like MySQL, PostgreSQL, and Oracle.
This article will explain the two main types of schemas in a database, their integration requirements, and provide a couple of examples.
What Is a Schema?
A schema is a framework or blueprint for programmers to construct and code a database. It can help a database user understand and information the information that’s stored.
Logical and Physical Database Schemas
When it comes to database design, there are two types of schemas – logical and physical.
Logical Database Schema
The logical database schema describes the logical constraints or rules that will be applied to the data. The main concern is to understand the data entities, including their relations and attributes.
Creating this schema should not be limited to a particular DBMS. The logical database design will stay the same regardless of which platform you use.
One way to show a logical design is by making a visual representation called an entity-relationship diagram (ER diagram). Microsoft Visio and LucidChart are some software you can use to create the diagram. An ER diagram generally displays:
- All important entities.
- Attributes of every entity.
- A primary key that uniquely identifies a specific instance of an entity.
- Plus, a foreign key that describes the relationships between entities.
For example, let’s say the entity “Book” has the following attributes – title, subject, publisher, and year. Its primary key is the “ISBN”. Furthermore, “Book” has a relationship with the entity “Author”, represented by the foreign key “Author ID”.

Keep in mind that logical schemas for different projects are created in several ways. They will also have different syntaxes to describe the logical constraints and architecture of the data.
Physical Database Schema
The physical database schema represents how the data is physically organized in a storage system, usually in the form of files and indices. It transforms the logical database schema to the physical data structure that works on a specific DBMS.
Table structures are all displayed in the physical database schema design. This includes the column name, data type, and constraints. Plus, the primary keys, foreign keys, and the relationship among them.
A physical database model also has the following characteristics:
- Explains the data requirements of a project.
- All tables and columns are specified.
- Foreign keys are used to determine the connection between tables.
- It may be different from the logical model because of physical constraints.
At this stage, you are mapping:
- Entities to tables.
- Attributes to columns.
- Primary keys to unique indexes.
- Foreign keys to non-unique indexes.
Database Schema Integration Requirements
A database can have more than one schema. Thus, to have them work seamlessly, the following requirements need to be met:
- Overlap preservation – make sure the elements overlapping in the schemas are in a database schema table.
- Extended overlap preservation – copy entities connected with overlapping elements – but only appear in one schema – to the resulting database schema.
- Normalization – avoid grouping independent elements and relationships together in one table.
- Minimality – check that no entities from any of the database schemas are lost.
Database Schema Examples
Now that you know what a schema is and its requirements, let’s look at schema examples from the SQL and PostgreSQL databases.
1. SQL
A schema in an SQL server is a collection of unlimited database objects linking to a database system. It includes tables, functions, views, and indexes. It’s a logical type of schema that brings a number of advantages. For example:
- A single schema can be used in multiple databases.
- Security permissions can protect database objects like tables and indexes.
- Transferring the ownership of schemas is possible.
- Objects created in the database can be moved between schemas.
- It helps in the process of manipulating and accessing the database objects.
The general syntax to create a schema in SQL is:
The parameters used are:
- schema_title – the name of the schema created.
- AUTHORIZATION owner – the name of the user who owns the schema.
- DEFAULT CHARACTER SET set_name – defines the default character set for the schema objects.
- PATH schema_title[, …] – optional file path and name.
- ANSI CREATE statements […] – consists of a single CREATE statement or more.
- ANSI GRANT statements […] – consists of a single GRANT statement or more.
2. PostgreSQL
The schema in PostgreSQL is a namespace containing named database objects. This includes tables, data types, indexes, functions, views, and operators. It ensures all objects have unique names.
A database can have more than one schema, but each is part of only one database. Different objects in two schemas can also share the same name.
The syntax to create a database schema in PostgreSQL 9.3.13 is:
PostgreSQL also automatically creates a public schema for every new database. This is where you find objects without a schema name.
Conclusion
A database schema is a plan or diagram that refers to the organization of the data stored in the database. There are two types of schema – logical and physical. The first represents how data is organized, and the second defines the structure of its physical storage.
A database schema is vital for creating databases and database management systems. It helps users understand and read the information stored in the database.
We hope you learned what the role of a database schema is and how to use it. If you have any questions about this topic, feel free to leave us a comment below.
Ratna is a web hosting expert. With her experience with all things tech and SEO, she is ever-ready to share. In her spare time, Ratna likes to read a good book or resume her cross-stitch project.
SCHEMAS in SQL Server -MS SQL Server – Zero to Hero Query Master – Part 3

This is part 3 of “MS SQL Server- Zero to Hero” and in this article, we will be discussing about the SCHEMAS in SQL SERVER. Before getting into this article, please consider to visit previous articles in this series from below,
A glimpse of previous articles
Part 1
In part one, we learned the basics of data, database, database management system, and types of DBMS and SQL.
Part 2
- We learned to create a database and maintain it using SQL statements.
- Best practice methods were also mentioned.
What is SCHEMA?.
In simple terms, Schemas are like folders within a database and are mainly used to group logical objects together. It is a way of categorizing the objects like Tables, Stored Procedures, Views, Functions, Triggers, Indexes in a database. It defines how the data is organized and how the relations among them are associated. The SCHEMA concept is introduced in SQL SERVER 2005 by Microsoft.
A schema always belongs to one particular database, and the schema is associated with a usernames, which is known as SCHEMA OWNER. A database may have one or more SCHEMAS.
Predefined SCHEMAS in SQL SERVER
SQL Server provides predefined SCHEMAS for newly created tables, which is dbo. The dbo SCHEMA is owned by dbo user account. First thing first, what’s dbo stands for?. dbo acronym standing for Database Owner.
When you create a new table without specifying a SCHEMA, the table will dbo as its default schema.
Types of Database SCHEMAS
- Physical Schema
- Logical Schema
- View Schema
Physical Schema
Physical Schema represent the design of a database at Physical Level, i.e., how the data stored in blocks of storage is described.
Logical Schema
Logical Schema represent the design of a database at Logical Level, i.e., data can be described as certain types of data records get stored in data structures. programmer and Database administrators works at this level.
View Schema
View Schema represents the design of database at View Level. i.e., this is generally describing end user interaction with database system.
Benefits of SQL SCHEMAS
- A SCHEMA can be very efficient object projection tool. A Database Administrator can maintain control access to an object.
- As stated before, SCHEMA will be efficient way to manage the logical group of database objects within a database.
- Since we group the objects, it will be easy to maintain the database.
- The ownership of a schema is transferable and hence the database objects can be moved among schemas.
- A SCHEMA can be shared among multiple users.
These are the some of the main benefits of using SCHEMAS in Databases.
List all SCHEMAS in Current Database
First method to see available SCHEMAS in a particular database in SSMS is by viewing under the SECURITY->SCHEMAS. There it will list all the SCHEMAS in that database.
Fig 1. Viewing Schemas under Security in SSMS
The second method is listing using T-SQL, we can get the complete list from the table sys.schemas.
When the above statement is ran is query window, we get the list of schemas as below,
Fig 2. Listing SCHEMAS using T-SQL Statement
The principal_id result column holds the Schema user Id. When we Join with sys.sysusers table, we can get the Schema Owner Name.
When the above T-SQL is ran in the Query window, we will get the Schema Name and corresponding Schema Owner as the result columns as shown,
Fig 3. Listing Schema Name and Schema owner
Create SCHEMA using T-SQL
We can create a SCHEMA using T-SQL statement,
Syntax
Example
When we run the above T-SQL Statement in Query window, a new schema will be created and we can view that by using any of the methods mentioned in the previous section.
So, what happens when we try to create a schema which is already exists. Let’s try that to, once again if we run the Create Schema T-SQL, we encounter the error as mentioned below,
Fig 4. Error occurred when tried to create schema which already exists
SQL Server throws an error message as “There is already an object named ‘TestSchemaName’ in the database.”
Drop SCHEMA
We can drop a created schema as similar as dropping a database or a table.
Syntax
Example
When the above T-SQL statement is ran in query window, the created Schema will be dropped or deleted permanently.
As for now we have not created any objects under the created schema, that’s why we are able to delete the SCHEMA. Lets create association for the SCHEMA, i.e., lets create an object for SCHEMA. Now I am again running the Create SCHEMA T-SQL statement and the schema will be created. Now I am going to create a table as object.
Syntax
Example
Now I am drop the schema TestSchemaName. Let’s see what happens once the DROP SCHEMA Statement is ran,
Fig 5. Error occurred when we try to drop objects associated to that SCHEMA
We cannot delete or drop the SCHEMA, since an object is associated with our SCHEMA TestSchemaName, it throws an error message as “Cannot drop schema ‘TestSchemaName’ because it is being referenced by object ‘TestTable’.” It’s clear that we cannot drop a schema when it has associated object(s) in database.
GitHub – The above scripts are in my repo, please feel free to refer those from here.
Conclusion
In this article, I tried to explain about the SCHEMA in SQL SERVER as simple as I could and the work sample T-SQL Statements are in my GitHub repo, please use it if required. In my next article, I will explain the table creation and giving access rights for schemas. Please share your Feedback in the comment section and share this article with your networks.