| by Arround The Web | No comments

CREATE TABLE in a Schema Postgres

PostgreSQL is one of the most popular object-relational database systems. It’s free and open-source software that extends the SQL language with additional features to handle the complex data workloads. It can work with various data types, reliable and secure. Learn more about the features of PostgreSQL.

In this guide, we will learn more about creating tables in a schema in PostgreSQL.

Schemas in PostgreSQL

A PostgreSQL database may contain one or more named schemas, each schema containing tables.

The same object name can be assigned across multiple schemas without conflict. For example, the following schema/table tree is valid:

  • schema_a
    • table_1
    • table_2
  • schema_b
    • table_1
    • table_2

You can think of schemas like directories at the operating system level. The difference is, there can’t be nested schemas. Learn more in-depth about schema on PostgreSQL documentation.

There can be multiple reasons to implement the schemas:

  • Multiple users using the same database without conflicting with each other.
  • Better organization and management of databases into logical groups.
  • Third-party apps can create their unique schema without colliding with the existing schemas or other objects.

Tables in PostgreSQL

Any relational database consists of multiple related tables, each consisting of rows and columns. PostgreSQL comes with several built-in tables that contain various system info. However, we can also create new tables under user-defined databases and schemas.

Pre-requisites:

To perform the steps demonstrated in this guide, you will need the following components:

For the purpose of this guide, we will use postgres to perform all the actions in PostgreSQL.

Creating Tables in a Schema

Creating a Demo Database

As mentioned earlier, schemas exist under a database. For demonstration purposes, we create a dummy database, avoiding disruption to any existing database.

Access the PostgreSQL shell as postgres:

$ sudo -i -u postgres psql

Create a new database demo_db:

$ CREATE DATABASE demo_db;

Verify if the database is created successfully:

$ \l

Finally, connect to the newly-created database:

$ \connect demo_db;

The Public Schema

Any new database in PostgreSQL comes with a default schema – public. If you try to create an object without specifying the schema name, the public schema is selected by default.

The following command prints all the available schema in the PostgreSQL database:

$ \dn

Alternatively, we can also use the following SQL query:

$ SELECT * FROM pg_catalog.pg_namespace;

Creating a New Schema

To create a new schema under a specific database, the command structure is as follows:

$ CREATE SCHEMA <schema_name>;

Following the rule, let’s create a new schema demo_schema:

$ CREATE SCHEMA demo_schema;

Check the schema list for verification:

$ \dn

Creating a Table in a Schema

Now that we have the target schema created, we can populate it with tables.

The syntax for creating a table is as follows:

CREATE TABLE <schema>.<table_name> (

    ...
)

Here:

  • schema: This field specifies the name of the schema where the table is created. If no value is provided, the table is created under the public schema.

For demonstration, we create a simple table:

CREATE TABLE demo_schema.demo_table (

        NAME CHAR(64),

        ID INT NOT NULL

);

Here:

  • The field NAME is specified to store a string of 64 characters.
  • The field ID contains the integer values. The term “NOT NULL” indicates that ID can’t be empty or null.

We can verify the existence of the table using the following query:

$ SELECT * FROM demo_schema.demo_table;

Inserting Data into the Table

With the table in place, we can now insert some values:

INSERT INTO demo_schema.demo_table (NAME, ID)

VALUES

   ( 'PQR', 45),

    ('IJK', 99)

;

Check the content of the table:

$ SELECT * FROM demo_schema.demo_table;

Schema Management

Schema Permissions

With the help of schema permission, we can manage what role can perform what action on a specific schema. Out of all the possible privileges, schemas only support CREATE and USAGE.

To update the schema permission for a particular role, the command structure is as follows:

$ GRANT <permission> ON SCHEMA <schema_name> TO <role>;

To revoke the schema permission for a particular role, the command structure is as follows:

$ REVOKE <permission> ON SCHEMA <schema_name> TO <role>;

Verify the change using the following command:

$ \dn+

Alter Schema Properties

With the help of the ALTER SCHEMA statement, we can modify the various properties of a schema. For example: ownership, schema name, etc.

To change the schema name, use the following query:

$ ALTER SCHEMA <schema_name> RENAME TO <new_schema_name>;

To change the ownership of a schema, use the following query:

$ ALTER SCHEMA <schema_name> OWNER TO <role>;

Note that to change the ownership, the current user must have the CREATE permission to the schema.

Deleting a Schema

If a schema is no longer necessary, we can delete it using the DROP query:

$ DROP SCHEMA <schema_name>

If the schema contains any object, we need the CASCADE modifier:

$ DROP SCHEMA <schema_name> CASCADE;

Table Management

Table Permissions

Like schema, each table also comes with permission management, defining what action does a role can perform on the table.

To check the permissions of a table, use the following command in psql:

$ \dp <table_name>

Alter Table Properties

With the help of the ALTER TABLE statement, we can modify the numerous aspects of an already-existing table.

For example, to drop a column, the query looks like this:

$ ALTER TABLE <table_name> DROP COLUMN <column>;

To add a new column, we can use the following query:

$ ALTER TABLE <table_name> ADD COLUMN <column> <data_type>;

We can also set the compression for a specific column:

$ ALTER COLUMN <column_name> SET COMPRESSION <compression_method>;

Deleting a Table

To delete a table from a schema, we can use the DROP TABLE query:

$ DROP TABLE <table_name>;

Note that unlike schemas, the DROP TABLE query won’t produce an error whether the table is empty or not.

Conclusion

In this guide, we demonstrated how to create the tables in a schema in PostgreSQL. We created a dummy schema within a dummy database and created a table within the schema. This guide also showcased on how to manage the various properties of schemas and tables.

For better data integrity, you can configure a logical PostgreSQL replication. To keep the PostgreSQL database healthy, you can configure the autovacuum to clean the dead tuples that are left by the deleted records.

For more PostgreSQL guides, check out the PostgreSQL sub-category.

Share Button

Source: linuxhint.com

Leave a Reply