PostgreSQL Create Table

Learn how to define new tables in PostgreSQL using the CREATE TABLE statement, along with data types and constraints.

The CREATE TABLE Statement

Tables are the fundamental storage structure in PostgreSQL. A table is defined by giving it a name and a list of columns, where each column has a data type and, optionally, one or more constraints. The basic syntax looks like this: CREATE TABLE table_name (column1 datatype constraints, column2 datatype constraints, ...);

Create a customers table

CREATE TABLE customers (
    customer_id SERIAL PRIMARY KEY,
    full_name VARCHAR(100) NOT NULL,
    email VARCHAR(150) UNIQUE NOT NULL,
    signup_date DATE DEFAULT CURRENT_DATE
);

Common Data Types

PostgreSQL supports a wide range of data types. Choosing the right type keeps your data accurate and your storage efficient.

Data TypeDescription
INTEGER / SERIALWhole numbers; SERIAL auto-increments
VARCHAR(n)Variable-length text up to n characters
TEXTVariable-length text with no length limit
BOOLEANTRUE or FALSE values
DATE / TIMESTAMPCalendar dates or date-and-time values
NUMERIC(p,s)Exact fixed-point numbers, ideal for currency
JSONBBinary JSON, indexable and query-optimized

Constraints Keep Data Valid

Constraints are rules enforced on column data. They prevent invalid data from ever being stored, which is far more reliable than validating data only in application code.

  • PRIMARY KEY: uniquely identifies each row in the table
  • NOT NULL: requires a column to always have a value
  • UNIQUE: ensures no two rows share the same value in a column
  • DEFAULT: supplies a value automatically when none is given
  • FOREIGN KEY: links a column to a primary key in another table
  • CHECK: enforces a custom condition on column values

Create a table with a foreign key and a check constraint

CREATE TABLE orders (
    order_id SERIAL PRIMARY KEY,
    customer_id INTEGER REFERENCES customers(customer_id),
    quantity INTEGER CHECK (quantity > 0),
    order_total NUMERIC(10, 2) NOT NULL
);
Note: SERIAL is a shorthand PostgreSQL provides for creating an auto-incrementing INTEGER column backed by a sequence. It is commonly used for primary keys.

View a table's structure

SELECT column_name, data_type
FROM information_schema.columns
WHERE table_name = 'orders';
Note: Once a table contains data, changing a column's type or adding a NOT NULL constraint may fail if existing rows violate the new rule. Always review your data before altering a live table.

Exercise: PostgreSQL Create Table

What does the SERIAL pseudo-type actually do in PostgreSQL?