Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PostgreSQL SCHEMA

PostgreSQL SCHEMA

A PostgreSQL SCHEMA can be viewed as a collection of tables.

A schema can contain views, indexes, data types, functions, operators, etc.

The same object name can be used in different schemas without conflict; for example, schema1 and myschema can both contain a table named mytable.

Advantages of using schemas:

A schema is similar to an operating-system-level directory, but schemas cannot be nested.

Syntax

We can use the **CREATE SCHEMA ** statement to create a schema. The syntax is as follows:



CREATE SCHEMA myschema (

...

);

The above statement creates a schema named myschema.

Schemas are commonly used to organize and isolate database objects and prevent object name conflicts.

To create a table, use the CREATE TABLE statement:

CREATE TABLE myschema.mytable (

    column1 datatype1,

    column2 datatype2,

    ...

);

The above statement creates a table named mytable in the myschema schema and defines a series of columns and their data types.

Note that datatype1, datatype2, etc. above should be replaced with actual data types, such as integer, varchar(255), and so on.

Example

Next, we connect to runoobdb to create the schema myschema:

runoobdb=# create schema myschema;

CREATE SCHEMA

The output "CREATE SCHEMA" indicates the schema was created successfully.

Next, let's create another table:

runoobdb=# 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 whether the table was created:

runoobdb=# select * from myschema.company;

 id | name | age | address | salary 

----+------+-----+---------+--------

(0 rows)

Drop a schema

Drop an empty schema (all objects in it have been removed):

DROP SCHEMA myschema;

Drop a schema and all objects it contains:

DROP SCHEMA myschema CASCADE;