Professional Documents
Culture Documents
Create Table: 5.5.1. Adding A Column
Create Table: 5.5.1. Adding A Column
To create a table, you use the aptly named CREATE TABLE command. For example:
CREATE TABLE my_first_table (
first_column text,
second_column integer );
This creates a table named my_first_table with two columns. The first column is
named first_column and has a data type of text; the second column has the
name second_column and the type integer.
CREATE TABLE products (
product_no integer,
name text,
price numeric );
If you no longer need a table, you can remove it using the DROP TABLE command. For
example:
DROP TABLE my_first_table;
DROP TABLE products;
All these actions are performed using the ALTER TABLE command,
5.5.1. Adding a Column
To add a column, use a command like:
ALTER TABLE products ADD COLUMN description text;
The new column is initially filled with whatever default value is given (null if you don't
specify a DEFAULT clause).
You can also define constraints on the column at the same time, using the usual syntax:
ALTER TABLE products ADD COLUMN description text CHECK (description <> '');
Whatever data was in the column disappears. Table constraints involving the column are
dropped, too. You can authorize dropping everything that depends on the column by
adding CASCADE:
ALTER TABLE products DROP COLUMN description CASCADE;
To add a not-null constraint, which cannot be written as a table constraint, use this syntax:
ALTER TABLE products ALTER COLUMN product_no SET NOT NULL;
The constraint will be checked immediately, so the table data must satisfy the constraint
before it can be added.
5.5.4. Removing a Constraint
To remove a constraint you need to know its name. If you gave it a name then that's easy.
Then the command is:
This works the same for all constraint types except not-null constraints. To drop a not null
constraint use:
ALTER TABLE products ALTER COLUMN product_no DROP NOT NULL;
Note that this doesn't affect any existing rows in the table, it just changes the default for
future INSERT commands.
To remove any default value, use:
ALTER TABLE products ALTER COLUMN price DROP DEFAULT;