CREATE TABLE (Create Table)
Last updated: 2026-11-04
CREATE TABLE (Create Table)
CREATE TABLE creates a new table and defines its columns, types, and constraints. PostgreSQL lets you declare constraints inline: PRIMARY KEY, NOT NULL, UNIQUE, DEFAULT, CHECK, and REFERENCES (foreign keys) may be written at either column or table level, and the database enforces them from that moment on.
| Kind | command |
|---|---|
| Example Language | SQL |
📝 Syntax
CREATE TABLE <table> (
<column> <data type> [NOT NULL] [DEFAULT <expression>] [UNIQUE] [CHECK (<condition>)]
[REFERENCES <parent table>(<parent column>) [ON DELETE <action>]],
...,
PRIMARY KEY (<column>, ...),
UNIQUE (<column>, ...),
CHECK (<condition>),
FOREIGN KEY (<column>) REFERENCES <parent table>(<parent column>)
)
⚙️ Parameters
| PRIMARY KEY | Primary key: unique and non-null, with an automatic index |
|---|---|
| NOT NULL | Forbids NULL in the column |
| DEFAULT | Expression used when no value is supplied |
| CHECK | Condition every row must satisfy |
| REFERENCES | Foreign key pointing at a parent table column |
| GENERATED ... AS IDENTITY | Auto-generated identity column |
Returns:No return value. On success the table and its constraints and indexes exist in the system catalogs.
▶ Example
Runs real PostgreSQL 18 right in your browser (PGlite WASM, nothing to install). Press ▶ Run and the result appears in the panel below.
Output:
DROP TABLE
DROP TABLE
CREATE TABLE
CREATE TABLE
INSERT 0 2
INSERT 0 2
id | customer_id | amount | status
---+-------------+--------+-------
1 | 1 | 120.00 | new
2 | 2 | 80.50 | new
📌 Key Points
- PRIMARY KEY implies uniqueness and non-nullity and automatically creates an index named
_pkey.
- DEFAULT expressions are evaluated when a row is inserted, so DEFAULT now() and DEFAULT nextval('seq') both work.
- CHECK constraints only cover rows written or updated afterwards; add NOT VALID first to skip validating history.
- REFERENCES declares a foreign key: ON DELETE CASCADE removes children with the parent, RESTRICT blocks the delete.
- A UNIQUE constraint also creates an index, so its backing index cannot be dropped with DROP INDEX.
- GENERATED ALWAYS AS IDENTITY is the standard way to write a generated column — clearer than SERIAL and easy to ALTER later.
💡 Related Cases
More case studies coming soon.📚 Related Reference
❓ FAQ
QWhat is the difference between SERIAL and IDENTITY?ASERIAL is shorthand for int + sequence + DEFAULT nextval. IDENTITY is the SQL-standard spelling with clearer semantics, and you can add it to an existing table with ALTER TABLE ... ADD GENERATED ... AS IDENTITY.QWhy does adding NOT NULL to an existing table fail?ABecause rows with NULL already exist. Backfill them with UPDATE first, or add a DEFAULT and fill the table, then add the NOT NULL constraint.🙏 帮我们做得更好
我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……
如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏