---
title: "CREATE, ALTER, DROP and RENAME TABLE"
description: "Define and change CoraDB tables: CREATE TABLE, constraints, AUTO_INCREMENT, vertex and edge tables, ALTER, DROP and RENAME TABLE."
url: "https://www.coradb.ai/manual/sql/schema/table_stmt.html"
markdown_url: "https://www.coradb.ai/manual/markdown/sql/schema/table_stmt.md"
product: "CoraDB"
version: "1.0"
keywords: "create table, alter table, drop table, rename table, create vertex table, create edge table, primary key, foreign key, unique constraint, not null, auto_increment, default value, on update, create table as select, create table like, add column, modify column, change column, coradb ddl"
---

# CREATE, ALTER, DROP and RENAME TABLE

This page covers the statements that create and change tables: [CREATE TABLE](https://www.coradb.ai/manual/sql/schema/table_stmt.html#create-table), [graph (vertex and edge) tables](https://www.coradb.ai/manual/sql/schema/table_stmt.html#graph-tables-vertex-and-edge), [ALTER TABLE](https://www.coradb.ai/manual/sql/schema/table_stmt.html#alter-table), [DROP TABLE](https://www.coradb.ai/manual/sql/schema/table_stmt.html#drop-table) and [RENAME TABLE](https://www.coradb.ai/manual/sql/schema/table_stmt.html#rename-table). Indexes, views and serials have their own pages: [CREATE INDEX](https://www.coradb.ai/manual/sql/schema/index_stmt.html), [CREATE VIEW](https://www.coradb.ai/manual/sql/schema/view_stmt.html) and [CREATE SERIAL](https://www.coradb.ai/manual/sql/schema/serial_stmt.html).

> **Try it yourself:**
> The examples create small tables next to the [e-commerce sample database](https://www.coradb.ai/manual/sample-database.html) and show the real results. In CoraDB, table definitions are part of the transaction: start corasql with `corasql --no-auto-commit -u dba e-commerce` and finish with `ROLLBACK;` to remove everything again.


## CREATE TABLE

```text
CREATE {TABLE | CLASS} [IF NOT EXISTS] table_name
    [(<column_definition>, ... [, <table_constraint>, ...])]
    [AUTO_INCREMENT = initial_value]
    [<table_option> [[,] <table_option> ...]]
    [[REPLACE] AS <select_statement>]

<column_definition> ::=
    column_name <data_type>
        [DEFAULT <value> | SHARED <value> | AUTO_INCREMENT [(seed, increment)]]
        [ON UPDATE <value>]
        [<column_constraint> ...]
        [COMMENT 'comment']

<data_type> ::= <column_type> [{CHARACTER_SET | CHARSET} charset_name] [COLLATE collation_name]

<column_constraint> ::=
    [CONSTRAINT constraint_name]
    {NOT NULL | UNIQUE | PRIMARY KEY | FOREIGN KEY <referential_definition>}

<table_constraint> ::=
    [CONSTRAINT [constraint_name]]
    { PRIMARY KEY (column_name [ASC | DESC], ...)
    | UNIQUE [KEY | INDEX] [index_name] (column_name [ASC | DESC], ...)
    | {KEY | INDEX} index_name (column_name [ASC | DESC], ...)
    | FOREIGN KEY [foreign_key_name] (column_name, ...) <referential_definition>
    } [COMMENT 'comment']

<referential_definition> ::=
    REFERENCES referenced_table_name [(column_name, ...)]
    [ON DELETE {CASCADE | RESTRICT | NO ACTION | SET NULL}]
    [ON UPDATE {RESTRICT | NO ACTION | SET NULL}]

<table_option> ::=
      REUSE_OID | DONT_REUSE_OID
    | COMMENT [=] 'comment'
    | [CHARSET charset_name] [COLLATE collation_name]
    | ENCRYPT [=] [AES | ARIA]
```

- **IF NOT EXISTS**: do nothing, without an error, if a table with the same name already exists.
- *table_name*, *column_name*: the names of the table and its columns; see [Identifiers](https://www.coradb.ai/manual/sql/identifier.html).
- *column_type*: the [data type](https://www.coradb.ai/manual/sql/datatype.html) of the column.
- `TABLE` and `CLASS` are synonyms. CoraDB also supports class inheritance (`UNDER`, `INHERIT`, `CLASS ATTRIBUTE`); see [Class inheritance](https://www.coradb.ai/manual/sql/oodb.html).

The following table stores discount coupons:

```sql
CREATE TABLE coupon (
    code         VARCHAR(16) PRIMARY KEY,
    description  VARCHAR(100),
    discount_pct SMALLINT NOT NULL DEFAULT 10,
    valid_from   DATE NOT NULL DEFAULT SYS_DATE,
    valid_to     DATE,
    created_by   VARCHAR(32) DEFAULT USER,
    INDEX idx_coupon_valid_to (valid_to)
) COMMENT = 'Discount codes';

INSERT INTO coupon (code, description) VALUES ('WELCOME10', 'First order');

SELECT code, description, discount_pct, valid_to, created_by FROM coupon;
```

| code | description | discount_pct | valid_to | created_by |
|---|---|---:|---|---|
| WELCOME10 | First order | 10 | NULL | DBA |

`valid_from` received today's date. The table comment is stored in the catalog and shown by [SHOW CREATE TABLE](https://www.coradb.ai/manual/sql/query/show.html#show-create-table).

> **CHECK constraints are ignored:**
> A `CHECK (...)` constraint in a table definition is accepted, so that scripts from other databases run unchanged, but it is not enforced. With `CHECK (discount_pct BETWEEN 1 AND 90)` in the definition above, inserting `discount_pct = 150` still succeeds. Use a [trigger](https://www.coradb.ai/manual/sql/trigger.html) to enforce such rules.



### Column definition

Each column has a name and a data type, optionally followed by a default value, an `ON UPDATE` value, constraints and a comment. Column names must be unique within the table. To rename a column later, use [RENAME COLUMN](https://www.coradb.ai/manual/sql/schema/table_stmt.html#rename-column-clause).

#### DEFAULT and SHARED

- **DEFAULT** *value*: the value stored when an `INSERT` does not give one for the column.
- **SHARED** *value*: one value shared by all rows. Inserting a row with a different value changes it for **every** row.

Only one of `DEFAULT`, `SHARED` and `AUTO_INCREMENT` can be used on a column.

```sql
CREATE TABLE store_setting (id INT, currency CHAR(3) SHARED 'EUR', vat_pct SMALLINT DEFAULT 19);
INSERT INTO store_setting (id) VALUES (1), (2);
INSERT INTO store_setting (id, currency) VALUES (3, 'RON');
INSERT INTO store_setting (id) VALUES (4);

SELECT * FROM store_setting ORDER BY id;
```

| id | currency | vat_pct |
|---:|---|---:|
| 1 | RON | 19 |
| 2 | RON | 19 |
| 3 | RON | 19 |
| 4 | RON | 19 |

Besides constants, a default value can be one of these expressions. They are evaluated when the row is inserted:

| Default value | Type |
|---|---|
| `SYS_DATE`, `CURRENT_DATE`, `SYSDATE` | DATE |
| `SYS_TIME`, `CURRENT_TIME` | TIME |
| `SYS_DATETIME`, `CURRENT_DATETIME`, `SYSDATETIME` | DATETIME |
| `SYS_TIMESTAMP`, `CURRENT_TIMESTAMP` | TIMESTAMP |
| `UNIX_TIMESTAMP()` | INTEGER |
| `USER`, `USER()` | VARCHAR |
| `TO_CHAR(date_time [, format])`, `TO_CHAR(number [, format])` | VARCHAR |

```sql
CREATE TABLE invoice_no (
    id           INT,
    invoice_code VARCHAR(20) DEFAULT TO_CHAR(12345, 'S999999'),
    issued_on    VARCHAR(10) DEFAULT TO_CHAR(SYS_DATE, 'YYYY-MM-DD')
);
INSERT INTO invoice_no (id) VALUES (1);
```

The row gets `invoice_code = ' +12345'` and today's date in `issued_on`.


#### AUTO_INCREMENT

`AUTO_INCREMENT` numbers the rows automatically. It can be defined on `SMALLINT`, `INTEGER`, `BIGINT` and `NUMERIC(p, 0)` columns.

```text
column_name INT AUTO_INCREMENT [(seed, increment)]
CREATE TABLE ... (column_name INT AUTO_INCREMENT, ...) AUTO_INCREMENT = seed
```

- *seed*: the first value (default 1). Any integer is allowed.
- *increment*: the step (default 1). Only positive integers are allowed.

A value is generated when the column is left out of the `INSERT` or set to `NULL`:

```sql
CREATE TABLE gift_card (id INT AUTO_INCREMENT(1000, 10), holder VARCHAR(40));
INSERT INTO gift_card (holder) VALUES ('Ana'), ('Mihai');
INSERT INTO gift_card VALUES (NULL, 'Ioana');

SELECT * FROM gift_card ORDER BY id;
```

| id | holder |
|---:|---|
| 1000 | Ana |
| 1010 | Mihai |
| 1020 | Ioana |

The table option `AUTO_INCREMENT = seed` sets the first value for a table with exactly one `AUTO_INCREMENT` column that has no `(seed, increment)` of its own:

```sql
CREATE TABLE return_request (id INT AUTO_INCREMENT PRIMARY KEY, order_id INT) AUTO_INCREMENT = 500;
INSERT INTO return_request (order_id) VALUES (455);   -- id = 500
```

Otherwise the statement is rejected:

```sql
CREATE TABLE t (id INT AUTO_INCREMENT, id2 INT AUTO_INCREMENT) AUTO_INCREMENT = 5;
```

```text
ERROR: To avoid ambiguity, the AUTO_INCREMENT table option requires the table to have exactly one AUTO_INCREMENT column and no seed/increment specification.
```

> **Note:**
> - `AUTO_INCREMENT` does not make a column unique. Add a `PRIMARY KEY` or `UNIQUE` constraint if you need that.
> - A value you insert yourself does not change the counter, so it can collide with a later generated value.
> - The counter does not wrap around. When it passes the maximum of the column's type (32767 for `SMALLINT`), inserts fail; choose a type large enough from the start.
> - The value generated for the last row inserted in your session is returned by [LAST_INSERT_ID](https://www.coradb.ai/manual/sql/function/information_fn.html#last_insert_id). To change the next value later, use [ALTER TABLE ... AUTO_INCREMENT](https://www.coradb.ai/manual/sql/schema/table_stmt.html#auto_increment-clause).


### ON UPDATE

`ON UPDATE` *value* sets a column automatically whenever another column of the row is updated, typically to record the time of the last change. The value can be `SYS_DATE`, `CURRENT_DATE`, `SYS_DATETIME`, `CURRENT_DATETIME`, `SYS_TIMESTAMP`, `CURRENT_TIMESTAMP` or `UNIX_TIMESTAMP()`. If the `UPDATE` sets the column itself, the value given in the statement is used.

```sql
CREATE TABLE stock_level (
    product_id INT PRIMARY KEY,
    units      INT,
    changed_at DATETIME ON UPDATE SYS_DATETIME
);
INSERT INTO stock_level VALUES (1795, 31, NULL);
UPDATE stock_level SET units = units - 1 WHERE product_id = 1795;   -- changed_at is set now
```

To remove the behavior, redefine the column without `ON UPDATE` using [MODIFY](https://www.coradb.ai/manual/sql/schema/table_stmt.html#changemodify-clauses).

### Constraints

Constraints can be written after a column (column constraints) or as separate items in the column list (table constraints). Constraints on several columns must be table constraints. If you do not name a constraint, CoraDB names it `pk_<table>_<columns>`, `fk_<table>_<columns>` or `u_<table>_<columns>`.

#### NOT NULL constraint

The column must always have a value:

```sql
CREATE TABLE wishlist (customer_id INT NOT NULL, product_id INT NOT NULL, note VARCHAR(100));
INSERT INTO wishlist VALUES (NULL, 1795, 'gift');
```

```text
ERROR: SQL statement violated NOT NULL constraint.
```

#### UNIQUE constraint

No two rows can have the same value in the column, or the same combination of values in the columns. `NULL` values do not count as duplicates, so several rows can have `NULL`.

```sql
CREATE TABLE review (
    customer_id INT,
    product_id  INT,
    stars       SMALLINT,
    CONSTRAINT uq_review UNIQUE (customer_id, product_id)
);
INSERT INTO review VALUES (5, 1795, 4), (5, 123, 5), (15, 1795, 3);
INSERT INTO review VALUES (5, 1795, 1);
```

```text
ERROR: Operation would have caused one or more unique constraint violations. INDEX uq_review ... key: {5, 1795}
```

#### PRIMARY KEY constraint

The primary key identifies each row: its columns must be unique and not `NULL`. A table has at most one primary key, on one or more columns. Its index is ascending unless you write `DESC` after a column, as in `PRIMARY KEY (a, b DESC)`. The e-commerce table `order_items`, for example, has the primary key `(order_id, product_id)`.

#### FOREIGN KEY constraint

A foreign key makes the values of one or more columns refer to the primary key of another table (or of the same table). CoraDB rejects values that do not exist in the referenced table and decides what happens to the referencing rows when the referenced row is deleted or its key is updated.

```text
[CONSTRAINT constraint_name] FOREIGN KEY [foreign_key_name] (column_name, ...)
    REFERENCES referenced_table_name [(column_name, ...)]
    [ON DELETE {CASCADE | RESTRICT | NO ACTION | SET NULL}]
    [ON UPDATE {RESTRICT | NO ACTION | SET NULL}]
```

- If you omit the referenced columns, the primary key of the referenced table is used. The number and types of the columns must match.
- *foreign_key_name*, when given, takes precedence over *constraint_name*.
- **ON DELETE** (default `RESTRICT`):
  - `RESTRICT` and `NO ACTION`: the referenced row cannot be deleted while rows refer to it.
  - `CASCADE`: the referencing rows are deleted too.
  - `SET NULL`: the foreign key columns of the referencing rows are set to `NULL`.
- **ON UPDATE** (default `RESTRICT`): `RESTRICT`, `NO ACTION` or `SET NULL`, as above, when the referenced key value changes.
- Changes made by `CASCADE` and `SET NULL` do not fire triggers.

A shopping cart and its items. Deleting a cart deletes its items; changing a cart's id is not allowed while it has items. The second foreign key refers to the `product` vertex table:

```sql
CREATE TABLE cart (
    id          INT PRIMARY KEY,
    customer_id INT NOT NULL,
    CONSTRAINT fk_cart_customer FOREIGN KEY (customer_id) REFERENCES customer (id)
);
CREATE TABLE cart_item (
    cart_id    INT NOT NULL,
    product_id INT NOT NULL,
    quantity   SMALLINT NOT NULL DEFAULT 1,
    PRIMARY KEY (cart_id, product_id),
    CONSTRAINT fk_cart_item_cart FOREIGN KEY (cart_id) REFERENCES cart (id)
        ON DELETE CASCADE ON UPDATE RESTRICT,
    FOREIGN KEY (product_id) REFERENCES product (id)
);
INSERT INTO cart VALUES (1, 5), (2, 15);
INSERT INTO cart_item (cart_id, product_id) VALUES (1, 1795), (1, 123), (2, 335);

DELETE FROM cart WHERE id = 1;

SELECT cart_id, product_id, quantity FROM cart_item;
```

| cart_id | product_id | quantity |
|---:|---:|---:|
| 2 | 335 | 1 |

The two items of cart 1 were deleted with it. Other operations on these tables fail:

```sql
UPDATE cart SET id = 10 WHERE id = 2;      -- ON UPDATE RESTRICT
INSERT INTO cart VALUES (3, 99999);        -- no customer 99999
```

```text
ERROR: Update/Delete operations are restricted by the foreign key 'fk_cart_item_cart'.
ERROR: The constraint of the foreign key 'fk_cart_customer' is invalid, due to value '99999'.
```

With `ON DELETE SET NULL`, the reference is cleared instead:

```sql
CREATE TABLE coupon_use (
    coupon   VARCHAR(16),
    order_id INT,
    FOREIGN KEY (order_id) REFERENCES orders (id) ON DELETE SET NULL
);
INSERT INTO coupon_use VALUES ('WELCOME10', 455);
DELETE FROM order_items WHERE order_id = 455;
DELETE FROM orders WHERE id = 455;
SELECT * FROM coupon_use;        -- WELCOME10, NULL
```

#### KEY or INDEX

`KEY` and `INDEX` are synonyms. In a table definition they create a regular (non-unique) index; a name is required. Each column can be followed by `ASC` or `DESC` to set the order of the index:

```sql
CREATE TABLE order_note (
    order_id INT,
    note     VARCHAR(200),
    INDEX idx_order_note (order_id DESC)
);
```

For all index options, see [CREATE INDEX](https://www.coradb.ai/manual/sql/schema/index_stmt.html).

### Table options

#### REUSE_OID

Every row of a CoraDB table has an object identifier (OID), its physical address. With **REUSE_OID**, the OID of a deleted row can be reused by a new row, which keeps the table compact under heavy `DELETE`/`INSERT` traffic. Such a table cannot be referenced by OID: it cannot be the type of a column, and the OIDs of its rows cannot be read. Updatable views over it are not possible either.

`REUSE_OID` is the default for ordinary tables (the [create_table_reuseoid](https://www.coradb.ai/manual/admin/config_sql.html#statementtype-related-parameters) parameter is `yes`):

```sql
CREATE TABLE ref_test (c countries);
```

```text
ERROR: The class 'countries' is marked as REUSE_OID and is non-referable. Non-referable classes can't be the domain of an attribute and their instances' OIDs cannot be returned.
```

#### DONT_REUSE_OID

**DONT_REUSE_OID** creates a referable table, whose rows keep their OIDs. [Vertex and edge tables](https://www.coradb.ai/manual/sql/schema/table_stmt.html#graph-tables-vertex-and-edge) are always created this way.

#### Charset and collation

`CHARSET` and `COLLATE` set the default character set and collation for the character columns of the table. See [Charset and collation](https://www.coradb.ai/manual/sql/i18n_collation.html#charset-and-collation-of-string-literals).

#### Table's COMMENT

`COMMENT [=] 'text'` stores a description of the table. Read it with [SHOW CREATE TABLE](https://www.coradb.ai/manual/sql/query/show.html#show-create-table) or from the `comment` column of the `db_class` catalog view, and change it with [ALTER TABLE ... COMMENT](https://www.coradb.ai/manual/sql/schema/table_stmt.html#columns-comment).

The options can be combined, separated by commas or spaces:

```sql
CREATE TABLE order_note (order_id INT, note VARCHAR(200))
    DONT_REUSE_OID, COMMENT = 'Notes on orders', COLLATE utf8_en_ci;
```

#### Table encryption (TDE)

`ENCRYPT` stores the table's data encrypted on disk. Choose `AES` or `ARIA`; without an algorithm, the [tde_default_algorithm](https://www.coradb.ai/manual/admin/config.html) parameter decides (default `AES`). Encryption is not inherited by subclasses. See [TDE (transparent data encryption)](https://www.coradb.ai/manual/security.html#tde-transparent-data-encryption).

```sql
CREATE TABLE card_vault (customer_id INT, token VARCHAR(64)) ENCRYPT = AES;
```

### CREATE TABLE LIKE

```text
CREATE {TABLE | CLASS} new_table_name LIKE source_table_name
```

Creates an empty table with the same columns, constraints, indexes and encryption setting as an existing table. Generated constraint names follow the new table name (`pk_order_archive_id`); index names you chose yourself are copied as they are, so index hints that name them keep working on the copy. Partitioned tables, tables with an `AUTO_INCREMENT` column, and tables that use inheritance or methods cannot be copied this way.

```sql
CREATE TABLE order_archive LIKE orders;
```

### CREATE TABLE AS SELECT

```text
CREATE {TABLE | CLASS} table_name [(<column_definition>, ... [, <table_constraint>, ...])]
    [REPLACE] AS <select_statement>
```

Creates a table and fills it with the rows of a query.

- Without a column list, the columns take the names and types of the query's select list. Name computed columns with an alias. Constraints and `AUTO_INCREMENT` are not copied from the source tables.
- With a column list, columns with the same name as a select-list column receive its values (converted to the declared type if needed); other declared columns get their default value or `NULL`; select-list columns that are not declared are added to the table.
- **REPLACE**: when the new table has a `UNIQUE` column and the query returns duplicates for it, keep the last row instead of failing.

```sql
CREATE TABLE top_customer AS
    SELECT customer_id, COUNT(*) AS orders_count
    FROM orders
    GROUP BY customer_id
    HAVING COUNT(*) >= 39;

SELECT * FROM top_customer ORDER BY customer_id;
```

| customer_id | orders_count |
|---:|---:|
| 440 | 40 |
| 444 | 39 |
| 812 | 40 |

With a column list, a primary key and an extra column with a default:

```sql
CREATE TABLE vip_list (customer_id INT PRIMARY KEY, segment VARCHAR(10) DEFAULT 'gold') AS
    SELECT customer_id, COUNT(*) AS orders_count
    FROM orders
    GROUP BY customer_id
    HAVING COUNT(*) >= 39;

SELECT * FROM vip_list ORDER BY customer_id;
```

| segment | customer_id | orders_count |
|---|---:|---:|
| gold | 440 | 40 |
| gold | 444 | 39 |
| gold | 812 | 40 |

The declared columns come first, followed by the columns that exist only in the query.

With `REPLACE`, one row per customer is kept, the last one returned by the query; ordered by date, that is the latest order:

```sql
CREATE TABLE last_order (customer_id INT UNIQUE) REPLACE AS
    SELECT customer_id, order_date FROM orders
    WHERE customer_id IN (440, 444)
    ORDER BY order_date;

SELECT * FROM last_order ORDER BY customer_id;
```

| customer_id | order_date |
|---:|---|
| 440 | 2025-12-27 |
| 444 | 2025-09-06 |

You can also use a [common table expression](https://www.coradb.ai/manual/sql/query/cte.html#ctes-in-other-statements) in the query.

## Graph tables (vertex and edge)

Graph data is stored in **vertex tables** (the nodes) and **edge tables** (the connections between them). They are created and changed with the same statements as ordinary tables, with `VERTEX` or `EDGE` before `TABLE`:

```text
CREATE [GRAPH] {VERTEX | EDGE} {TABLE | LABEL} [IF NOT EXISTS] table_name [(<column_definition>, ...)] [<table_option> ...]
ALTER  [GRAPH] {VERTEX | EDGE} [TABLE | LABEL] table_name <alter_clause> [, <alter_clause> ...]
DROP   [GRAPH] {VERTEX | EDGE} [TABLE | LABEL] [IF EXISTS] table_name [, ...]
```

- `GRAPH` is optional, and `LABEL` is a synonym of `TABLE` (a vertex or edge table is the *label* of its rows in graph terms).
- A vertex table can have any columns, keys and indexes, like an ordinary table.
- An edge table holds the edge's own properties. The two vertices it connects are stored by CoraDB and are given when the edge is inserted with [INSERT EDGE](https://www.coradb.ai/manual/sql/query/insert.html#insert-edge). An edge table can also have no columns at all.
- Vertex and edge tables are always `DONT_REUSE_OID`. [SHOW FULL TABLES](https://www.coradb.ai/manual/sql/query/show.html#show-tables) lists them as `VERTEX TABLE` and `EDGE TABLE`.

A warehouse vertex table and an edge table that records how many units of a product each warehouse holds:

```sql
CREATE VERTEX TABLE warehouse (id INT PRIMARY KEY, name VARCHAR(64) NOT NULL);
CREATE EDGE TABLE stocks (quantity INT NOT NULL, updated_at DATETIME DEFAULT SYSDATETIME);

INSERT VERTEX INTO warehouse VALUES (1, 'Bucharest DC');
INSERT EDGE
    FROM (SELECT warehouse FROM warehouse WHERE id = 1)
    TO (SELECT product FROM product WHERE id = 1795)
    INTO stocks (quantity) VALUES (40);

SELECT w.name, p.name, s.quantity
FROM MATCH (w:warehouse)-[s:stocks]->(p:product);
```

| w.name | p.name | s.quantity |
|---|---|---:|
| Bucharest DC | Balboa Persistence Tee | 40 |

Change and remove graph tables with the usual clauses:

```sql
ALTER VERTEX TABLE warehouse ADD COLUMN city VARCHAR(32);
ALTER EDGE TABLE stocks ADD COLUMN bin VARCHAR(8);
DROP EDGE TABLE IF EXISTS stocks;
DROP VERTEX TABLE IF EXISTS warehouse;
```

Rows of graph tables are read with [MATCH](https://www.coradb.ai/manual/graph/match.html) and changed with `INSERT VERTEX`/`INSERT EDGE`, [UPDATE](https://www.coradb.ai/manual/sql/query/update.html#updating-vertices-and-edges) and [DELETE](https://www.coradb.ai/manual/sql/query/delete.html#deleting-vertices-and-edges). For a step-by-step introduction, see the [Graph tutorial](https://www.coradb.ai/manual/graph/graph_getting_started.html).

## ALTER TABLE

`ALTER TABLE` changes the definition of an existing table: its columns, constraints, indexes, comments, `AUTO_INCREMENT` counter and owner. Several clauses can be combined in one statement, separated by commas. `TABLE` and `CLASS`, and `COLUMN` and `ATTRIBUTE`, are synonyms.

```text
ALTER [/*+ SKIP_UPDATE_NULL */] [TABLE | CLASS] table_name <alter_clause> [, <alter_clause> ...]

<alter_clause> ::=
      ADD [COLUMN] <column_definition> [FIRST | AFTER column_name]
    | ADD [COLUMN] (<column_definition>, ...)
    | ADD [CONSTRAINT [constraint_name]] <table_constraint>
    | ADD {KEY | INDEX} index_name (column_name [(length)] [ASC | DESC], ...) [COMMENT 'comment']
    | ALTER [COLUMN] column_name SET DEFAULT <value>
    | CHANGE [COLUMN] old_column_name new_column_name <column_definition> [FIRST | AFTER column_name]
    | MODIFY [COLUMN] column_name <column_definition> [FIRST | AFTER column_name]
    | RENAME [COLUMN] old_column_name AS new_column_name
    | DROP [COLUMN] column_name [, column_name ...]
    | DROP CONSTRAINT constraint_name
    | DROP {KEY | INDEX} index_name
    | DROP PRIMARY KEY
    | DROP FOREIGN KEY constraint_name
    | AUTO_INCREMENT = initial_value
    | COMMENT [=] 'comment'
    | COMMENT ON COLUMN column_name [=] 'comment' [, column_name [=] 'comment' ...]
    | OWNER TO user_name
```

Only the owner of the table, `DBA` and members of the `DBA` group can change a table, unless the owner grants the `ALTER` permission to others (see [GRANT](https://www.coradb.ai/manual/sql/authorization.html#grant)). The clauses for class inheritance and views (`ADD SUPERCLASS`, `INHERIT`, `ADD QUERY` and so on) are described in [Class inheritance](https://www.coradb.ai/manual/sql/oodb.html) and [ALTER VIEW](https://www.coradb.ai/manual/sql/schema/view_stmt.html).

The examples below change this table of supplier contacts:

```sql
CREATE TABLE supplier_contact (
    id          INT AUTO_INCREMENT PRIMARY KEY,
    supplier_id INT,
    email       VARCHAR(64)
);
INSERT INTO supplier_contact (supplier_id, email)
VALUES (1, 'ana@acme.example'), (2, NULL);
```

### ADD COLUMN clause

Adds one or more columns, at the end of the table or at the position given by `FIRST` or `AFTER`:

```sql
ALTER TABLE supplier_contact
    ADD COLUMN phone VARCHAR(32) AFTER supplier_id,
    ADD COLUMN active SMALLINT DEFAULT 1;
ALTER TABLE supplier_contact ADD COLUMN priority INT FIRST;

SHOW COLUMNS FROM supplier_contact;
```

| Field | Type | Null | Key | Default | Extra |
|---|---|---|---|---|---|
| priority | INTEGER | YES |  | NULL |  |
| id | INTEGER | NO | PRI | NULL | auto_increment |
| supplier_id | INTEGER | YES |  | NULL |  |
| phone | VARCHAR(32) | YES |  | NULL |  |
| email | VARCHAR(64) | YES |  | NULL |  |
| active | SHORT | YES |  | 1 |  |

What the existing rows receive in the new column:

- The `DEFAULT` value, if the column has one (above, `active` is 1 in both rows);
- Otherwise `NULL`. A `NOT NULL` column without a default is therefore rejected on a table that has rows, unless the [add_column_update_hard_default](https://www.coradb.ai/manual/admin/config_sql.html#statementtype-related-parameters) parameter is `yes` (default `no`); then the rows receive the type's [hard default value](https://www.coradb.ai/manual/sql/schema/table_stmt.html#hard-default-values).

```sql
ALTER TABLE supplier_contact ADD COLUMN region VARCHAR(10) NOT NULL;
```

```text
ERROR: Cannot add NOT NULL constraint for attribute "region": there are existing NULL values for this attribute.
```

The same rules decide whether a `UNIQUE` or `PRIMARY KEY` constraint on a new column can be satisfied: a new `PRIMARY KEY` column can only be added to an empty table, and a new `UNIQUE` column with a default value fails on a table with more than one row.

### ADD CONSTRAINT clause

Adds a `PRIMARY KEY`, `UNIQUE` or `FOREIGN KEY` constraint. The existing rows must satisfy it. If you omit the name, one is generated.

```sql
ALTER TABLE supplier_contact ADD CONSTRAINT uq_supplier_contact_email UNIQUE (email);
ALTER TABLE supplier_contact
    ADD CONSTRAINT fk_supplier_contact_supplier FOREIGN KEY (supplier_id) REFERENCES supplier (id);
```

### ADD INDEX clause

Adds a regular index; `KEY` and `INDEX` are synonyms. The same can be done with [CREATE INDEX](https://www.coradb.ai/manual/sql/schema/index_stmt.html).

```sql
ALTER TABLE supplier_contact ADD INDEX idx_supplier_contact_phone (phone) COMMENT 'lookup by phone';
```

### ALTER COLUMN ... SET DEFAULT clause

Sets or changes the default value of a column without touching its other attributes:

```sql
ALTER TABLE supplier_contact ALTER COLUMN active SET DEFAULT 0;
```

### AUTO_INCREMENT clause

Sets the next value of the table's `AUTO_INCREMENT` column (the table must have exactly one):

```sql
ALTER TABLE supplier_contact AUTO_INCREMENT = 100;
INSERT INTO supplier_contact (supplier_id, email) VALUES (3, 'ion@acme.example');

SELECT id, supplier_id, active FROM supplier_contact ORDER BY id;
```

| id | supplier_id | active |
|---:|---:|---:|
| 1 | 1 | 1 |
| 2 | 2 | 1 |
| 100 | 3 | 0 |

Make sure the new values cannot collide with existing ones in a primary key or unique column. Changing the column's type (for example from `INT` to `BIGINT`) also changes the counter's maximum.

### CHANGE/MODIFY clauses

- **CHANGE** *old_name new_name* \<*column_definition*\> renames a column and redefines it. Repeat the old name to keep the name.
- **MODIFY** *column_name* \<*column_definition*\> redefines a column without renaming it.

Both can move the column with `FIRST` or `AFTER`.

```sql
ALTER TABLE supplier_contact CHANGE email contact_email VARCHAR(100);
ALTER TABLE supplier_contact MODIFY phone VARCHAR(64);
```

The new definition **replaces** the old one: a `DEFAULT`, `NOT NULL`, `AUTO_INCREMENT` or `ON UPDATE` attribute that you do not repeat is removed. Primary key, unique and regular indexes on the column are kept, and rebuilt if the type changes. Columns used in a foreign key (referencing or referenced) and partitioning columns cannot be changed.

Whether existing values may be converted is controlled by two parameters:

- [alter_table_change_type_strict](https://www.coradb.ai/manual/admin/config_sql.html#statementtype-related-parameters) (default `yes`): values that cannot be converted to the new type, or would overflow, make the statement fail. With `no`, such values are replaced by the type's minimum or maximum, or by its [hard default value](https://www.coradb.ai/manual/sql/schema/table_stmt.html#hard-default-values), and a warning is logged.
- [allow_truncated_string](https://www.coradb.ai/manual/admin/config_sql.html#statementtype-related-parameters) (default `no`): strings that would not fit in a shorter type make the statement fail.

With the defaults, shortening a column below the length of its data fails:

```sql
CREATE TABLE promo (code VARCHAR(20));
INSERT INTO promo VALUES ('WELCOME-2026-SPRING');
ALTER TABLE promo MODIFY code VARCHAR(8);
```

```text
ERROR: ALTER TABLE .. CHANGE : changing to new domain : cast failed, current configuration doesn't allow truncation or overflow.
```

Adding `NOT NULL` to a column that contains `NULL` values fails as well:

```text
ERROR: Cannot add NOT NULL constraint for attribute "phone": there are existing NULL values for this attribute.
```


The **SKIP_UPDATE_NULL** hint adds the `NOT NULL` constraint without checking or changing the existing rows. This is fast on large tables, but existing `NULL` values then remain in a column declared `NOT NULL`:

```sql
ALTER /*+ SKIP_UPDATE_NULL */ TABLE supplier_contact MODIFY phone VARCHAR(64) NOT NULL;
```

Triggers and views that use the column are not updated automatically; recreate them after changing a column's type or collation.


#### Hard default values

The hard default is the value CoraDB uses for existing rows when it needs a value of a type and none is given (see above):

| Type | Hard default |
|---|---|
| INTEGER, SMALLINT, BIGINT, NUMERIC, FLOAT, DOUBLE | `0` |
| DATE | `DATE'01/01/0001'` |
| TIME | `TIME'00:00'` |
| DATETIME | `DATETIME'01/01/0001 00:00'` |
| TIMESTAMP | `TIMESTAMP'00:00:01 AM 01/01/1970'` (GMT) |
| CHAR, VARCHAR | `''` (empty string) |
| SET, MULTISET, LIST | `{}` |
| BIT, VARBIT, BLOB, CLOB, object types | none |

### RENAME COLUMN clause

```sql
ALTER TABLE supplier_contact RENAME COLUMN priority AS rank_no;
```


### Comments

Change the table's comment, or the comments of one or more columns:

```sql
ALTER TABLE supplier_contact COMMENT = 'Contacts at our suppliers';
ALTER TABLE supplier_contact COMMENT ON COLUMN phone = 'Direct line';
```

Column comments are shown by [SHOW FULL COLUMNS](https://www.coradb.ai/manual/sql/query/show.html#show-columns) and stored in the `comment` column of the `db_attribute` catalog view. A comment can also be given in a column definition, in `CREATE TABLE`, `ADD COLUMN`, `CHANGE` or `MODIFY`.

### DROP COLUMN clause

Removes one or more columns and their data:

```sql
ALTER TABLE supplier_contact DROP COLUMN rank_no, active;
```

### DROP CONSTRAINT, DROP INDEX, DROP PRIMARY KEY and DROP FOREIGN KEY clauses

```sql
ALTER TABLE supplier_contact DROP INDEX idx_supplier_contact_phone;
ALTER TABLE supplier_contact DROP CONSTRAINT uq_supplier_contact_email;
ALTER TABLE supplier_contact DROP FOREIGN KEY fk_supplier_contact_supplier;
ALTER TABLE supplier_contact DROP PRIMARY KEY;
```

- `DROP CONSTRAINT` removes a primary key, unique or foreign key constraint by name.
- `DROP INDEX` removes a regular index. A unique index can be removed with `DROP CONSTRAINT` or [DROP INDEX](https://www.coradb.ai/manual/sql/schema/index_stmt.html).
- `DROP PRIMARY KEY` needs no name, because a table has only one primary key. It fails while a foreign key refers to it.
- Find constraint and index names with [SHOW INDEX](https://www.coradb.ai/manual/sql/query/show.html#show-index) or [SHOW CREATE TABLE](https://www.coradb.ai/manual/sql/query/show.html#show-create-table).

### OWNER TO clause

Gives the table to another user. Only `DBA` and members of the `DBA` group can do this.

```sql
CREATE USER catalog_admin;
ALTER TABLE supplier_contact OWNER TO catalog_admin;
```

Views, triggers and stored procedures change owner in the same way; see [ALTER ... OWNER](https://www.coradb.ai/manual/sql/authorization.html#alter--owner).

## DROP TABLE

```text
DROP [TABLE | CLASS] [IF EXISTS] <table_spec> [, <table_spec> ...] [CASCADE CONSTRAINTS]

<table_spec> ::= [ONLY] table_name | ALL table_name [(EXCEPT table_name, ...)]
```

Removes tables with all their rows, indexes and constraints. Several tables can be dropped at once.

- **IF EXISTS**: skip tables that do not exist instead of failing.
- **CASCADE CONSTRAINTS**: also remove the foreign keys of other tables that refer to the dropped table. The rows of those tables are kept. Without it, a table whose primary key is referenced cannot be dropped.
- `ONLY`, `ALL` and `EXCEPT` select subclasses in a class hierarchy; see [Class inheritance](https://www.coradb.ai/manual/sql/oodb.html).

```sql
CREATE TABLE parent_t (id INT PRIMARY KEY);
CREATE TABLE child_t (id INT, p INT, FOREIGN KEY (p) REFERENCES parent_t (id));

DROP TABLE parent_t;
```

```text
ERROR: The primary key 'pk_parent_t_id' referred by a foreign key 'fk_child_t_p' is not supposed to be dropped.
```

```sql
DROP TABLE IF EXISTS parent_t CASCADE CONSTRAINTS;   -- child_t loses its foreign key, keeps its rows
DROP TABLE IF EXISTS no_such_table, child_t;
```

To drop vertex and edge tables, see [Graph tables](https://www.coradb.ai/manual/sql/schema/table_stmt.html#graph-tables-vertex-and-edge).

## RENAME TABLE

```text
RENAME [TABLE | CLASS] old_table_name {AS | TO} new_table_name [, old_table_name {AS | TO} new_table_name ...]
```

Renames one or more tables. Only the owner, `DBA` and members of the `DBA` group can rename a table, unless the owner grants the permission to others.

```sql
RENAME TABLE supplier_contact TO supplier_person;
```

## See also

- [CREATE INDEX](https://www.coradb.ai/manual/sql/schema/index_stmt.html)
- [CREATE VIEW](https://www.coradb.ai/manual/sql/schema/view_stmt.html)
- [CREATE SERIAL](https://www.coradb.ai/manual/sql/schema/serial_stmt.html)
- [Data types](https://www.coradb.ai/manual/sql/datatype.html)
- [Partitioning](https://www.coradb.ai/manual/sql/partition.html)
