Creating a Table
The CREATE TABLE command is used to create a table in SQL.
Tables are created within databases. To create a table you will need to list out the column names, and specify their data types.
Common data types
| Data type | Description |
|---|---|
| int / integer | whole numbers (-2147483648 to +2147483647) |
| real / float | decimal values (6 decimal digits precision) |
| char(n) | text of fixed length, blank padded |
| varchar(n) | text of varying length up to 'n' characters |
| text | text of unlimited length |
| date | 'yyyy-mm-dd' (ex. '2021-11-25') |
| time | 'hh:mm:ss' (ex. '15:30:02.5' - 2.5s after 3:30p.m.) |
Note that values can be set to NULL.
To ensure a value is not null, use the NOT NULL constraint.
Syntax
CREATE TABLE <table-name> (
<column-name> <data-type> NOT NULL,
<column-name> <data-type>,
<column-name> <data-type>,
...
);
Example
CREATE TABLE Companies (
name TEXT,
type TEXT,
founded INT,
hq TEXT
);
Useful psql commands
| Command | Description |
|---|---|
| \d [table] | Describes a table |