create table postgres
create table postgres is the CREATE TABLE statement. It creates an empty table in the database you are connected to, and you own that table. One connection sees one database. psql, pgAdmin, and DBeaver all send the same SQL. The statement also creates a composite type of the same name, so the table cannot share its name with an existing type in that schema.
CREATE TABLE users (
id integer,
name text,
email text,
created_at timestamptz
);
psql prints CREATE TABLE. The table has four columns and no rows. SELECT * FROM users; returns zero rows. \d users lists the columns, types, indexes, and constraints. \dt lists tables on your search path.
The table is created in the schema you name, or in the current schema if you name none. The current schema is the first existing schema on search_path. A new database starts with search_path set to "$user", public, so an unqualified name lands in public when you have no schema of your own. Creating a table there takes the CREATE privilege on that schema. On a database created by PostgreSQL 15 or later, PUBLIC does not have CREATE on public. A role without the privilege gets this error:
ERROR: permission denied for schema public
The schema owner grants it with GRANT CREATE ON SCHEMA public TO app_user;. You also need USAGE on each column type. Built-in types already grant that to PUBLIC. A database upgraded from PostgreSQL 14 or earlier still has CREATE on public for everyone until somebody revokes it.
CREATE TABLE syntax
The shape is CREATE TABLE table_name (column_name data_type, ...);.
Unquoted names are folded to lower case. PostgreSQL keeps at most 63 bytes of an identifier. Users and users are the same table. "Users" is a different name. A reserved word has to be quoted, so a table named user is written "user".
Commas separate column definitions. There is no comma after the last column. psql holds the statement until it sees a semicolon, then sends it.
IF NOT EXISTS
A second CREATE TABLE users fails with ERROR: relation "users" already exists. The name has to be distinct from every relation in that schema: tables, views, indexes, sequences, materialized views, and foreign tables.
CREATE TABLE IF NOT EXISTS users (
id integer,
name text
);
When users is already there, psql prints a notice and then the usual command tag. The existing table is left as it was.
NOTICE: relation "users" already exists, skipping
CREATE TABLE
The notice does not mean the existing columns match this statement. The clause is for a script you are willing to run twice. It will not update a table that was created with a different shape.
Numeric types
integer, also spelled int and int4, is 4 bytes and holds -2147483648 through 2147483647. bigint (int8) is 8 bytes and holds -9223372036854775808 through 9223372036854775807. smallint (int2) is 2 bytes and holds -32768 through 32767. A value outside the range is an error. integer is the usual choice. smallint is for when the disk space matters. bigint is for when integer is too small.
numeric and decimal are the same type. numeric(precision, scale) stores an exact decimal. The precision is the total number of digits, and the scale is how many of those digits sit after the decimal point. numeric(10, 2) rounds to two fractional digits and rejects a magnitude past 99999999.99. Use it for money. real is a 4-byte floating-point value with at least 6 decimal digits of precision. double precision is 8 bytes with at least 15. Both are approximate, so a value you store can come back slightly different, and they are a poor fit for money.
serial is not a type of its own. This statement:
CREATE TABLE ids (
id serial
);
is an integer column, a sequence, NOT NULL, and a default of nextval on that sequence. It does not add a primary key or a unique constraint. The sequence can skip values when an insert rolls back. bigserial does the same thing with bigint. For a new table, an identity column is the standard form of the same idea, and it is below with primary keys.
Text types
varchar(n) stores up to n characters. A longer value is an error, except that extra spaces are truncated. char(n) is padded with spaces to n characters, and those trailing spaces are ignored when two char values are compared. text stores a string of any length, up to about 1 GB. There is no performance difference among the three, apart from the padding and the length check. char(n) is usually the slowest because of that padding. In most situations, use text or varchar. Use varchar(n) when a longer string should be rejected. varchar with no length accepts any length, the same as text.
Date and time types
date stores a calendar date and no time of day. time stores a time of day and no date. Writing timestamp means timestamp without time zone. The clock reading is stored as written, with no zone conversion.
timestamptz is timestamp with time zone. An input that includes a zone is converted to UTC. An input with no zone is read as the session TimeZone, then converted to UTC. The original zone is not stored. On output, the value is converted from UTC into the session TimeZone. interval stores a duration. interval '3 days' and interval '2 hours' are both valid inputs.
Boolean, UUID, JSONB, arrays, and bytea
boolean uses 1 byte and holds true, false, or null. TRUE and FALSE are the SQL constants. psql prints t and f.
uuid stores a 128-bit identifier. gen_random_uuid() is built in on PostgreSQL 13 and later and returns a version 4 UUID. A sequence is unique inside one database. A random UUID is for an id that is created in more than one place. The column is 16 bytes, against 4 bytes for an integer.
jsonb stores JSON in a decomposed binary form. json stores the input text exactly, including whitespace and the order of keys. jsonb does not keep whitespace, key order, or duplicate keys. The JSON types page says most applications should store JSON as jsonb, unless they depend on key order. jsonb has a default GIN operator class. json has no default operator class for btree or GIN.
An array column holds several values of one type. text[] is a list of strings, and integer[] is a list of integers. bytea stores binary bytes.
NOT NULL
A column accepts null unless the definition says otherwise. Null means unknown. It is not the same value as an empty string.
CREATE TABLE accounts (
email text NOT NULL
);
INSERT INTO accounts (email) VALUES (NULL); fails the NOT NULL constraint. INSERT INTO accounts (email) VALUES (''); stores a zero-length string, and email IS NULL is false for that row.
Primary keys
A primary key is unique and not null. PostgreSQL creates a unique B-tree index for it.
CREATE TABLE accounts (
id integer PRIMARY KEY,
email text
);
A key of more than one column is a table constraint:
CREATE TABLE memberships (
user_id integer,
group_id integer,
PRIMARY KEY (user_id, group_id)
);
Two rows can share a user_id, and two rows can share a group_id. They cannot share both.
An identity column draws the key from a sequence. The column is implicitly NOT NULL.
CREATE TABLE accounts (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text
);
INSERT INTO accounts (email) VALUES ('ada@example.com'); omits id, so the sequence supplies it. INSERT INTO accounts (id, email) VALUES (1, 'ada@example.com'); is rejected, because ALWAYS refuses an explicit value unless the insert says OVERRIDING SYSTEM VALUE. GENERATED BY DEFAULT AS IDENTITY keeps the value you supply, and uses the sequence when the column is omitted or written as DEFAULT.
A natural key is a column you already store, such as an email address, used as the primary key. It works when that value is unique and will not change. An email address usually fails the second test, so the usual shape is a surrogate id plus UNIQUE on the email.
UNIQUE
CREATE TABLE accounts (
id integer PRIMARY KEY,
email text UNIQUE
);
PostgreSQL creates a unique B-tree index on email. Two rows cannot store the same email. Nulls are not equal in a unique constraint, so two rows can both store a null email. UNIQUE NULLS NOT DISTINCT makes those nulls conflict. Several columns are written at table level: UNIQUE (tenant_id, email).
CHECK
CREATE TABLE products (
id integer PRIMARY KEY,
price numeric CHECK (price > 0),
status text CONSTRAINT status_known CHECK (status IN ('active', 'inactive'))
);
An insert with price of 0 fails products_price_check, which is the name PostgreSQL chose. An insert with status of 'paused' fails status_known, the name in the statement. A check that returns unknown succeeds, so a null price passes price > 0. Add NOT NULL when null is not a valid price. A check on two columns is a table constraint: CHECK (discounted_price <= price). The expression sees the new row only. It cannot query other rows.
DEFAULT
CREATE TABLE products (
stock_quantity integer DEFAULT 0,
is_active boolean DEFAULT true,
created_at timestamptz DEFAULT now()
);
An INSERT that omits a column stores that column’s default. Writing the keyword DEFAULT does the same. Writing NULL stores null, and the default is not used. With no DEFAULT clause, the default is null. now() returns the start time of the current transaction, as timestamptz. A uuid column can default to gen_random_uuid(). The function is volatile, so each inserted row gets its own value.
Foreign keys
CREATE TABLE orders (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_id integer REFERENCES users (id)
);
user_id has to equal some users.id, or be null. The referenced columns have to be a primary key, a unique constraint, or a non-partial unique index. If they are not, the statement fails with ERROR: there is no unique constraint matching given keys for referenced table "users". users has to exist already. REFERENCES users, with no column list, uses the primary key of users.
ON DELETE controls a delete of the referenced row. The default is NO ACTION. The delete is attempted, then the foreign key is checked, and a leftover reference is an error. If the constraint is deferrable, that check can wait until the end of the transaction. RESTRICT raises the error as well, and it does not wait. CASCADE deletes the referencing rows. SET NULL writes null into the foreign key columns. SET DEFAULT writes their defaults, and those defaults still have to satisfy the foreign key. ON UPDATE offers the same five actions. CASCADE on update copies the new referenced value into the referencing rows.
A foreign key does not create an index on the referencing columns. A delete or update of the referenced row has to find those rows, so an index there is worth adding when the referenced key changes.
A junction table is how one order holds many products:
CREATE TABLE order_items (
order_id integer REFERENCES orders (id) ON DELETE CASCADE,
product_id integer REFERENCES products (id) ON DELETE RESTRICT,
quantity integer NOT NULL,
PRIMARY KEY (order_id, product_id)
);
DELETE FROM orders WHERE id = 1; also deletes order_items rows whose order_id is 1. DELETE FROM products WHERE id = 7; fails while any order_items row still has product_id 7.
A users table
This is the same pieces in one account table. bigint leaves room for more than about two billion accounts. varchar(50) rejects a longer username. email is text because the limit you care about is uniqueness, not a character count.
CREATE TABLE users (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
username varchar(50) NOT NULL UNIQUE,
email text NOT NULL UNIQUE,
password_hash text NOT NULL,
is_active boolean NOT NULL DEFAULT true,
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO users (username, email, password_hash)
VALUES ('ada', 'ada@example.com', 'hash');
The insert names three columns. id comes from the identity sequence. is_active is true. created_at is the transaction start time. A second insert with the same email fails the unique constraint on email.
A products table
CREATE TABLE products (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
description text,
price numeric(12, 2) NOT NULL CONSTRAINT price_positive CHECK (price > 0),
stock_quantity integer NOT NULL DEFAULT 0,
category text NOT NULL
);
price is an exact decimal with two fractional digits, it cannot be null, and it has to be greater than 0. The constraint name price_positive is what the error quotes. description can be null. stock_quantity is 0 when the insert omits it. name and category have to be supplied.
An orders table
orders points at users. ON DELETE RESTRICT keeps a user row from disappearing while an order still names that user. The line items live in order_items, from the foreign key section, because one order can name many products.
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_id bigint NOT NULL REFERENCES users (id) ON DELETE RESTRICT,
ordered_at timestamptz NOT NULL DEFAULT now()
);
user_id is NOT NULL, so every order matches a user. The parent tables have to be created first.
A JSONB column
CREATE TABLE product_meta (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
metadata jsonb
);
CREATE INDEX product_meta_metadata_idx ON product_meta USING gin (metadata);
metadata holds attributes that differ from row to row, such as '{"color": "red"}'. A column is the better fit when every row has the same field and you want a type and a check on it. The default GIN operator class on jsonb supports the containment operator @> and the key-exists operators ?, ?|, and ?&.
Schemas
A schema is a namespace inside the database. It cannot be nested. This puts the table in app instead of public:
CREATE SCHEMA app;
CREATE TABLE app.users (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY
);
SET search_path TO app, public;
SHOW search_path; prints the list. After that SET, an unqualified users means app.users, and a new unqualified table is created in app. Names that begin with pg_ are reserved for the system.
Temporary tables
CREATE TEMP TABLE staging (
id integer,
payload text
);
CREATE TEMPORARY TABLE is the same statement. The table is visible in this session only, and it is dropped when the session ends. Other sessions can create their own staging with a different shape. With no ON COMMIT clause, the behavior is ON COMMIT PRESERVE ROWS, so a commit keeps the rows. ON COMMIT DELETE ROWS empties the table at commit and keeps the definition. ON COMMIT DROP drops the table at commit. Autovacuum cannot see a temporary table, so a large one needs VACUUM and ANALYZE from this session. Indexes on it are temporary. A schema name is not allowed. While it exists, an unqualified staging means the temporary table, not a permanent table of the same name.
Unlogged tables
CREATE UNLOGGED TABLE cache (
key text PRIMARY KEY,
value text
);
Rows written here are not written to the write-ahead log, so the writes are faster than writes to an ordinary table. The table is not crash-safe. After a crash or an unclean shutdown, PostgreSQL truncates it. The contents are not replicated to standby servers. Indexes created on it are unlogged, and so is an identity or serial sequence created with it. UNLOGGED cannot be used on a partitioned table.
Inheritance
CREATE TABLE cities (
name text,
population integer
);
CREATE TABLE capitals (
state text
) INHERITS (cities);
capitals has name, population, and state. SELECT * FROM cities; returns rows from cities and from capitals. SELECT * FROM ONLY cities; returns rows from cities alone. A later ALTER TABLE cities ADD COLUMN founded date; adds founded to capitals as well. An identity property on a parent column is not inherited. An INSERT into cities stays in cities. It is not routed to capitals.
Declarative partitioning, next, does route rows. Inheritance is the older tool. A child table can have columns the parent does not, and a child can inherit from more than one parent. Splitting rows that way needs triggers or rules if the application inserts only into the parent. The partitioning chapter describes that as the flexible case, and declarative partitioning as the one with the performance features for range, list, and hash splits.
LIKE
CREATE TABLE users_copy (LIKE users INCLUDING ALL);
LIKE copies column names, types, and NOT NULL constraints. INCLUDING ALL also copies comments, compression, check constraints, defaults, generated columns, identity (each with a new sequence), indexes (including primary key and unique constraints), extended statistics, and storage settings. Foreign keys are not in that list. After this statement, users and users_copy are separate. A later change to users does not change users_copy, and a query on users does not see rows in users_copy.
Partitioning
Partitioning splits one logical table into smaller physical tables. The parent holds no rows. An insert into the parent is routed to a partition, and an insert that matches no partition is an error. The partitioning chapter says the benefit usually shows up when the table would otherwise be very large, and the rule of thumb there is a table larger than the database server’s physical memory. Indexes still matter inside each partition.
A range partition uses an inclusive start and an exclusive end:
CREATE TABLE measurements (
city_id integer NOT NULL,
logdate date NOT NULL,
temp numeric
) PARTITION BY RANGE (logdate);
CREATE TABLE measurements_2026_01 PARTITION OF measurements
FOR VALUES FROM ('2026-01-01') TO ('2026-02-01');
INSERT INTO measurements (city_id, logdate, temp) VALUES (1, '2026-01-31', 3.5); lands in measurements_2026_01. The same insert with logdate of 2026-02-01 does not match that partition, because TO is exclusive. With no other partition, the insert fails with no partition of relation "measurements" found for row.
A list partition names the key values it accepts:
CREATE TABLE cities_by_region (
city_id integer NOT NULL,
name text NOT NULL,
region text
) PARTITION BY LIST (region);
CREATE TABLE cities_west PARTITION OF cities_by_region
FOR VALUES IN ('west', 'northwest');
INSERT INTO cities_by_region (city_id, name, region) VALUES (1, 'Portland', 'west'); lands in cities_west. 'east' does not.
A hash partition spreads rows when you have no range or list to split on. The modulus is a positive integer, and each remainder is smaller than that modulus:
CREATE TABLE orders_hashed (
order_id bigint NOT NULL,
total numeric
) PARTITION BY HASH (order_id);
CREATE TABLE orders_hashed_0 PARTITION OF orders_hashed
FOR VALUES WITH (MODULUS 4, REMAINDER 0);
CREATE TABLE orders_hashed_1 PARTITION OF orders_hashed
FOR VALUES WITH (MODULUS 4, REMAINDER 1);
CREATE TABLE orders_hashed_2 PARTITION OF orders_hashed
FOR VALUES WITH (MODULUS 4, REMAINDER 2);
CREATE TABLE orders_hashed_3 PARTITION OF orders_hashed
FOR VALUES WITH (MODULUS 4, REMAINDER 3);
Every order_id matches one remainder from 0, 1, 2, or 3, so every insert has a partition. CREATE TABLE ... PARTITION OF takes an ACCESS EXCLUSIVE lock on the parent. ALTER TABLE ... ATTACH PARTITION can take a weaker lock.
Naming
Unquoted names are stored in lower case, so snake_case does not fight the folding. Plural table names, such as users and orders, are a convention. A constraint with no name gets one generated from the table and column names. CONSTRAINT price_positive CHECK (price > 0) puts price_positive in the error. Prefixes such as pk_, fk_, uq_, and chk_ are a naming habit, not syntax. Avoid a name that starts with pg_, because unqualified references can land on a system catalog of the same name.
Indexes
A primary key and a unique constraint each create an index. Add an index on a foreign key column when the referenced row is deleted or its key is updated. Other indexes can wait until a query plan needs them. Each extra index is maintained on every write.
Comments
COMMENT ON TABLE users IS 'Accounts that can sign in';
COMMENT ON COLUMN users.email IS 'Login address, one per account';
\d+ users shows the comment on email. \dt+ users shows the comment on the table. Keep the CREATE TABLE script in version control and apply it with a migration tool such as Flyway, Liquibase, or Alembic, so the next database is created from the same statement.
Errors
ERROR: relation "users" already exists means the name is taken. IF NOT EXISTS skips the create. DROP TABLE users removes the table and its rows, which is the right fix only when that data can go.
type "string" does not exist means the type name is not a PostgreSQL type. integer, int, and int4 are the same integer type. text is the unlimited string. A missing comma between two columns is a syntax error at the next column.
permission denied for schema public is the privilege error from the start of this article. GRANT CREATE ON SCHEMA public TO app_user; fixes it for that role.
there is no unique constraint matching given keys for referenced table "users" means the foreign key does not point at a primary key or a unique constraint. Create the referenced table first, with that constraint, then create the table that names it.
Inspecting a table
\d users shows columns, types, defaults, indexes, and constraints. \dt lists tables. This query reads the same column list from the SQL-standard catalog:
SELECT column_name, data_type, is_nullable, column_default
FROM information_schema.columns
WHERE table_schema = 'public'
AND table_name = 'users'
ORDER BY ordinal_position;
For the account table in the users section, that query reports bigint for id, character varying for username, text for email, boolean for is_active, and timestamp with time zone for created_at. An integer column is reported as integer. pg_catalog.pg_tables has one row per table, with schemaname, tablename, and tableowner:
SELECT schemaname, tablename, tableowner
FROM pg_catalog.pg_tables
WHERE tablename = 'users';
ALTER TABLE
These statements start from the first users table in this article, the one with id, name, email, and created_at:
ALTER TABLE users ADD COLUMN last_login timestamptz;
ALTER TABLE users ADD CONSTRAINT users_email_key UNIQUE (email);
ALTER TABLE users RENAME COLUMN name TO full_name;
ALTER TABLE users RENAME TO accounts;
The first statement adds last_login. Existing rows get null in that column, because no default is given. The second adds a unique constraint and its index. The third renames name to full_name. The fourth renames the table to accounts. ALTER TABLE takes an ACCESS EXCLUSIVE lock unless the form you use documents a weaker one. That lock waits for other use of the table and blocks new use. ADD FOREIGN KEY takes SHARE ROW EXCLUSIVE on the table you alter and on the table you reference.
DROP TABLE
DROP TABLE users;
Only the table owner, the schema owner, or a superuser can drop it. The rows are removed, and so are the indexes, rules, triggers, and constraints of that table. To delete the rows and keep the table, use DELETE or TRUNCATE.
DROP TABLE IF EXISTS users;
If users is missing, this issues NOTICE: table "users" does not exist, skipping instead of ERROR: table "users" does not exist.
A view, or a foreign key in another table, counts as a dependent object. Plain DROP TABLE uses RESTRICT, which refuses the drop while a dependent object exists. DROP TABLE users CASCADE; drops a dependent view entirely. In the foreign key case it drops the constraint and leaves the other table in place.