Schema

SQL Constraints

Enforce data rules using NOT NULL, UNIQUE, CHECK, PRIMARY KEY and FOREIGN KEY constraints.

Availability: Common SQL with references for SQL standard, MySQL/MariaDB, PostgreSQL, SQL Server, SQLite and Oracle Database; syntax and feature support vary by engine and version.中文

Syntax

CREATE TABLE ... (column type NOT NULL, UNIQUE (...), CHECK (...), FOREIGN KEY (...) REFERENCES ...);

Examples

Enforce data rules using NOT NULL, UNIQUE, CHECK, PRIMARY KEY and FOREIGN KEY constraints.

CREATE TABLE team_members (team_id INTEGER, user_id INTEGER, PRIMARY KEY (team_id, user_id));

SQLite-oriented example; consult the relevant dialect manual.

CREATE TABLE team_members (team_id INTEGER, user_id INTEGER, PRIMARY KEY (team_id, user_id));

Parameters, options and clauses

Option / clauseDescription
Object nameName a table, view, index, schema or database.
Column definitionSpecify column name, data type and default value.
ConstraintsUse NOT NULL, UNIQUE, CHECK, PRIMARY KEY or FOREIGN KEY as needed.
IF EXISTS / IF NOT EXISTSMake create/drop operations conditional where supported.
CASCADE / RESTRICTControl dependent-object handling where supported; verify before destructive changes.

Dialect references

Safety note

Review a command and its target before running it. Commands that alter files, services, accounts, disks, permissions or databases may be difficult to reverse. Test in a safe environment and keep backups.

Official reference ↗Back to directory