About table
Create table
Syntax
Creating a table that already exists will result in a error. The
IF NOT EXISTS
option allows you to create the new table only if it does not exist. When you use theIF NOT EXISTS option
and the table already exists, PostgreSQL issues a notice instead of the error and skips creating the new table.The *column constraints include
not null
,unique
,primary key
,check
,foreign key
constraints.Table constraints are similar to column constraints except that they are applied to more than one column. Table constraints can be defined as column constraints like
primary key
,foreign key
,check
,unique constraints
.Primary key column uniquely identify rows in a table. A table can have one and only one primary key. The primary key constraint allows you to define the primary key of a table.
Example of creating table with column constraint,
Example of creating table with table constraint,
Delete table
Syntax
If you remove a table that does not exist, PostgreSQL issues an error. To avoid this situation, you can use the IF EXISTS option.
In case the table that you want to remove is used in other objects such as views, triggers, functions, and stored procedures, the DROP TABLE cannot remove the table. In this case, you have two options:
The
CASCADE
option allows you to remove the table and its dependent objects.The
RESTRICT
option rejects the removal if there is any object depends on the table. TheRESTRICT
option is the default if you don’t explicitly specify it in the DROP TABLE statement.
Note: You need to have the roles of the superuser, schema owner, or table owner in order to drop tables.
To remove multiple tables at once, you can place a comma-separated list of tables after the DROP TABLE keywords.
Alter table
Syntax
Actions can be,
Add or drop a column
Change the datatype of a column
Rename a column
Set a default value of a column
Add a constraint for the column
Rename a table
Syntax for above actions to alter table
Add a column
Drop a column
Rename a column
Change a default value of a column
Add a check constraint to a column
Add a constraint to a table
Rename a table
Last updated