YouTip LogoYouTip

Postgresql Schema

# PostgreSQL Schema A PostgreSQL schema can be considered a collection of tables. A schema can contain views, indexes, data types, functions, and operators, etc. The same object names can be used in different schemas without conflict. For example, both `schema1` and `myschema` can contain a table named `mytable`. Advantages of using schemas: * Allows multiple users to use a database without interfering with each other. * Organizes database objects into logical groups for easier management. * Objects from third-party applications can be placed in separate schemas, so they don't conflict with the names of other objects. Schemas are similar to directories at the operating system level, but schemas cannot be nested. ### Syntax We can use the **CREATE SCHEMA** statement to create a schema. The syntax is as follows: ```sql CREATE SCHEMA myschema (...); The above statement will create a schema named `myschema`. Schemas are typically used to organize and isolate database objects, preventing object name conflicts. To create a table, use the `CREATE TABLE` statement: ```sql CREATE TABLE myschema.mytable ( column1 datatype1, column2 datatype2, ...); The above statement will create a table named `mytable` under the `myschema` schema, defining a series of columns and their data types. Please note that `datatype1`, `datatype2`, etc., should be replaced with actual data types, such as `integer`, `varchar(255)`, etc. ### Example Next, we connect to `tutorialdb` to create the schema `myschema`: ```sql tutorialdb=# create schema myschema; CREATE SCHEMA The output "CREATE SCHEMA" indicates that the schema was created successfully. Next, we create a table: ```sql tutorialdb=# create table myschema.company( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR (25), SALARY DECIMAL (18, 2), PRIMARY KEY (ID) ); The above command creates an empty table. We use the following SQL to check if the table was created: ```sql tutorialdb=# select * from myschema.company; id | name | age | address | salary ----+------+-----+---------+-------- (0 rows) ### Deleting a Schema To delete an empty schema (where all objects have been removed): ```sql DROP SCHEMA myschema; To delete a schema and all objects contained within it: ```sql DROP SCHEMA myschema CASCADE;
← Postgresql SelectCollection Enumeration β†’