Skip to content

MySQL DDL API

MySQL Data Definition Language for creating and altering tables, indexes and constraints.

1 class · 4 methods

DDL

4 methods

Statements that define or modify the database schema.

CREATE TABLE [IF NOT EXISTS] tbl (col type [constraints], ...)

Creates a new table with the given columns and table-level constraints.

Parameters

NameTypeDescription
tblidentifierTable name.
typedatatypeINT, VARCHAR(n), DATETIME, DECIMAL(p,s), etc.
constraintsconstraintNOT NULL, DEFAULT, AUTO_INCREMENT, PRIMARY KEY.

Returns

void

Example

mysql
CREATE TABLE users (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  email VARCHAR(255) NOT NULL UNIQUE,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
ALTER TABLE tbl ADD [COLUMN] col type | DROP COLUMN col | MODIFY col type

Adds, removes or modifies columns and constraints on an existing table.

Parameters

NameTypeDescription
tblidentifierTable to alter.
colidentifierColumn to add, drop or modify.

Returns

void

Example

mysql
ALTER TABLE users
  ADD COLUMN last_login DATETIME NULL,
  MODIFY email VARCHAR(320) NOT NULL;
CREATE [UNIQUE] INDEX name ON tbl (col, ...) [USING BTREE]

Creates a secondary index on one or more columns to speed up lookups; UNIQUE enforces uniqueness.

Parameters

NameTypeDescription
nameidentifierIndex name.
tblidentifierTable to index.
colcolumn-listIndexed columns.

Returns

void

Example

mysql
CREATE UNIQUE INDEX idx_users_email ON users (email);
CONSTRAINT name PRIMARY KEY|FOREIGN KEY|UNIQUE|CHECK (cols)

Table-level constraint clause enforcing integrity rules on one or more columns.

Parameters

NameTypeDescription
nameidentifierOptional constraint name.
colscolumn-listColumns the constraint applies to.

Returns

void

Example

mysql
CONSTRAINT fk_orders_user
  FOREIGN KEY (user_id) REFERENCES users(id)
  ON DELETE CASCADE ON UPDATE RESTRICT