How to Create a Table in PostgreSQL
Basic Example
This example shows how to create a users
table:
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email TEXT
);
The resulting table has two columns:
id
, which is defined to be an auto-incrementing integer and the table’s primary keyemail
How to Create a Non-Nullable Columns
You can create non-nullable columns by adding a NOT NULL
constraint:
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email TEXT NOT NULL
);
The PRIMARY KEY
column has the NOT NULL
constraint added automatically, without specifying it explicitly.
How to Create Columns With Default Values
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email TEXT NOT NULL,
credits_used INTEGER DEFAULT 0,
subscribed_to_newsletter BOOLEAN NOT NULL DEFAULT false
);
Here the following columns specify default values:
credits_used
with default value0
subscribed_to_newsletter
with default valuefalse
. This column is furthermore defined to be non-nullable