Up to now you read tables that exist. Now you make your own.
The statement
sql
CREATE TABLE suppliers (
id integer,
name text,
country text
);CREATE TABLEmake a new tablesuppliersits name(id integer, name text, country text)each column: a name, then a type;end
- Put the columns in parentheses. Write a comma between each two columns.
- Each column is a name followed by a data type: the types from Chapter 1 (
integer,text,numeric,date,boolean). The next lesson shows more types. - The columns of the table are in the order you write them.
The new table has its columns and no rows:
suppliers
| id | name | country |
|---|
A statement that changes the database returns no rows. The Result tab shows the statement and done. The new table also gets its own tab.
Names
- Use letters, digits and
_. Start with a letter. Do not use spaces. - PostgreSQL changes a name to lower case.
CREATE TABLE Suppliersmakes the tablesuppliers. - Write names in lower case, with
_between words:order_items,signup_date. - A keyword such as
orderoruseris not a valid name.CREATE TABLE order (…)gives a syntax error. Use another name, such asorders.
A name that is already used
Two tables cannot have the same name. When you run the statement a second time, PostgreSQL stops:
text
ERROR: relation "suppliers" already existsIF NOT EXISTS tells PostgreSQL to skip the statement when the table exists:
sql
CREATE TABLE IF NOT EXISTS suppliers (
id integer,
name text,
country text
);text
NOTICE: relation "suppliers" already exists, skippingIF NOT EXISTS looks only at the name. It does not compare the columns. When the old table has other columns, it keeps them.