Creating and deleting tables

Creating a table

Before creating the table, you need to select the database to which the table will be written. This is done using the USE statement:

MySQL 8.4
USE database_name;
database_name
The database where tables will be created.

The CREATE TABLE statement is used to create the table. Its simplest use is as follows:

MySQL 8.4
CREATE TABLE [IF NOT EXISTS] table_name (
    column data_type [, ...]
);
  • [ ]optional part
  • ...can be repeated
IF NOT EXISTS

Skip creating the table if a table with this name already exists. Without it, the query fails in that case.

KeywordOptional
table_name
The name of the new table.
column

The column name. You can list several column data_type pairs separated by commas.

data_type

What values the column stores, for example INTEGER for numbers or VARCHAR(255) for strings.

For example, let's create a table of users.

MySQL 8.4
CREATE TABLE Users (
    id INTEGER,
    name VARCHAR(255),
    age INTEGER
);

INTEGER, VARCHAR(255) - data types: numeric and string, respectively. More details about them can be found in the following articles.

MySQL 8.4
CREATE TABLE Users (
    id INTEGER,
    name VARCHAR(255),
    age INTEGER
);

INTEGER, VARCHAR(255) - data types: numeric and string, respectively. More details about them can be found in the following articles.

Additional column definition options

The above definition of columns in a table is simplified. In addition to the name of the column and its type, it is sometimes necessary to add the following optional parameters to the definition:

  • PRIMARY KEY

    Specifies a column or set of columns as the primary key.

  • AUTO_INCREMENT

    Indicates that the value of this column will be automatically increased when new records are added to the table. Each table has a maximum of one AUTO_INCREMENT column. It is worth noting that this parameter can only be applied to integer and floating point types.

  • SERIAL or GENERATED ALWAYS AS IDENTITY

    Indicates that the value of this column will be automatically increased when new records are added to the table. SERIAL is a shorthand for creating an auto-incrementing field.

  • UNIQUE

    Indicates that the values in this column for all records must be different from each other.

  • NOT NULL

    Indicates that the values in this column must be different from NULL.

  • DEFAULT

    Specifies the default value.

This parameter does not apply to the BLOB, TEXT, GEOMETRY and JSON types.

For our table of users, you can specify the following parameters:

MySQL 8.4
CREATE TABLE Users (
    id INTEGER PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL,
    age INTEGER NOT NULL DEFAULT 18
);
MySQL 8.4
CREATE TABLE Users (
    id SERIAL PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    age INTEGER NOT NULL DEFAULT 18
);

So, in this example:

  • id - a numeric field that is the primary key with auto-increment;
  • id - a SERIAL type field (auto-incrementing integer), which is the primary key;
  • name - a string type field with a maximum length of 255 characters, which is mandatory;
  • age - a numeric field with a default value of 18.

CURRENT_TIMESTAMP as a default value

CURRENT_TIMESTAMP is useful when you want the database to automatically store the row creation time. For example, it can be used together with the TIMESTAMP type.

MySQL 8.4
CREATE TABLE Users (
    id INTEGER PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
MySQL 8.4
CREATE TABLE Users (
    id SERIAL PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Description of the table

To view the description of the created table, you can use the operator DESCRIBE.

MySQL 8.4
DESCRIBE Users;
FieldTypeNullKeyDefaultExtra
idintNOPRINULLauto_increment
namevarchar(255)NONULL
ageintNO18

To view the description of the created table, you can use an SQL query to the information schema:

MySQL 8.4
SELECT column_name, data_type, is_nullable, column_default
FROM information_schema.columns
WHERE table_schema = current_schema() AND table_name = lower('Users');
column_namedata_typeis_nullablecolumn_default
idintegerNOnextval('users_id_seq'::regclass)
namecharacter varyingNO<NULL>
ageintegerNO18

Additional table definition options

In addition to the description of the columns, when creating a table, you can additionally specify the following parameters:

Primary key

If you have not defined the primary key using the column parameters, then you can do this using additional table parameters by adding the entry PRIMARY KEY (column [, ...]) after enumerating the columns:

MySQL 8.4
CREATE TABLE Users (
    id INTEGER,
    name VARCHAR(255) NOT NULL,
    age INTEGER NOT NULL DEFAULT 18,
    PRIMARY KEY (id)
);

Primary key

If you have not defined the primary key using the column parameters, then you can do this using additional table parameters by adding the entry PRIMARY KEY (column [, ...]) after enumerating the columns:

MySQL 8.4
CREATE TABLE Users (
    id INTEGER,
    name VARCHAR(255) NOT NULL,
    age INTEGER NOT NULL DEFAULT 18,
    PRIMARY KEY (id)
);

Foreign keys

Suppose we want to store data about the company our users work for. Let's create a small table Companies in which we will store a unique identifier and the name of the company:

MySQL 8.4
CREATE TABLE Companies (
    id INTEGER,
    name VARCHAR(255) NOT NULL,
    PRIMARY KEY (id)
);

Next, you need to add the company field to the Users table – the place of work of our user, which will refer to the entry in the Companies table. The full query for creating a table will look like this:

MySQL 8.4
CREATE TABLE Users (
    id INTEGER,
    name VARCHAR(255) NOT NULL,
    age INTEGER NOT NULL DEFAULT 18,
    company INTEGER,
    PRIMARY KEY (id)
);

A foreign key is used to ensure that the company column contains an identifier that exists in the Companies table when new entries are added to the Users table. It has the following syntax:

MySQL 8.4
FOREIGN KEY (column [, ...])
REFERENCES external_table (external_table_column [, ...])
[ON DELETE action]
[ON UPDATE action]
  • [ ]optional part
  • ...can be repeated
column

The column of this table that refers to another table. For a composite key, list the columns separated by commas.

external_table
The table whose records the foreign key refers to.
external_table_column

The column of the external table that values are checked against, usually its primary key. List as many columns, in the same order, as in FOREIGN KEY.

ON DELETE action

What happens to the records of this table when the record they refer to is deleted.

Optional
RESTRICTCASCADESET NULLNO ACTION
ON UPDATE action

What happens to the records of this table when the value they refer to changes.

Optional
RESTRICTCASCADESET NULLNO ACTION

The full query for creating a table with a foreign key will be as follows:

MySQL 8.4
CREATE TABLE Users (
    id INTEGER,
    name VARCHAR(255) NOT NULL,
    age INTEGER NOT NULL DEFAULT 18,
    company INTEGER,
    PRIMARY KEY (id),
    FOREIGN KEY (company) REFERENCES Companies (id)
);

If you have foreign keys, you can determine the behavior of the current record when changing or deleting the record to which it refers.

MySQL 8.4
CREATE TABLE Users (
    id INTEGER,
    name VARCHAR(255) NOT NULL,
    age INTEGER NOT NULL DEFAULT 18,
    company INTEGER,
    PRIMARY KEY (id),
    FOREIGN KEY (company) REFERENCES Companies (id)
    ON DELETE RESTRICT ON UPDATE CASCADE
);

ON DELETE RESTRICT means that if you try to delete a company that has data in the Users table, the database won't let you do this:

MySQL 8.4
Cannot delete or update a parent row: a foreign key constraint fails

If ON DELETE CASCADE was specified, then when deleting the company, all users would be deleted, referring to this company.

There is one more option - ON DELETE SET NULL. When used, the database will write NULL as the value of the company field for all users who worked at the remote company.

ON UPDATE CASCADE means that if a company changes its ID, then all Users will get a new ID in the company field.

Foreign keys

Suppose we want to store data about the company our users work for. Let's create a small table Companies in which we will store a unique identifier and the name of the company:

MySQL 8.4
CREATE TABLE Companies (
    id INTEGER,
    name VARCHAR(255) NOT NULL,
    PRIMARY KEY (id)
);

Next, you need to add the company field to the Users table – the place of work of our user, which will refer to the entry in the Companies table. The full query for creating a table will look like this:

MySQL 8.4
CREATE TABLE Users (
    id INTEGER,
    name VARCHAR(255) NOT NULL,
    age INTEGER NOT NULL DEFAULT 18,
    company INTEGER,
    PRIMARY KEY (id)
);

A foreign key is used to ensure that the company column contains an identifier that exists in the Companies table when new entries are added to the Users table. It has the following syntax:

MySQL 8.4
FOREIGN KEY (column [, ...])
REFERENCES external_table (external_table_column [, ...])
[ON DELETE action]
[ON UPDATE action]
  • [ ]optional part
  • ...can be repeated
column

The column of this table that refers to another table. For a composite key, list the columns separated by commas.

external_table
The table whose records the foreign key refers to.
external_table_column

The column of the external table that values are checked against, usually its primary key. List as many columns, in the same order, as in FOREIGN KEY.

ON DELETE action

What happens to the records of this table when the record they refer to is deleted.

Optional
RESTRICTCASCADESET NULLSET DEFAULTNO ACTION
ON UPDATE action

What happens to the records of this table when the value they refer to changes.

Optional
RESTRICTCASCADESET NULLSET DEFAULTNO ACTION

The full query for creating a table with a foreign key will be as follows:

MySQL 8.4
CREATE TABLE Users (
    id INTEGER,
    name VARCHAR(255) NOT NULL,
    age INTEGER NOT NULL DEFAULT 18,
    company INTEGER,
    PRIMARY KEY (id),
    FOREIGN KEY (company) REFERENCES Companies (id)
);

If you have foreign keys, you can determine the behavior of the current record when changing or deleting the record to which it refers.

MySQL 8.4
CREATE TABLE Users (
    id INTEGER,
    name VARCHAR(255) NOT NULL,
    age INTEGER NOT NULL DEFAULT 18,
    company INTEGER,
    PRIMARY KEY (id),
    FOREIGN KEY (company) REFERENCES Companies (id)
    ON DELETE RESTRICT ON UPDATE CASCADE
);

ON DELETE RESTRICT means that if you try to delete a company that has data in the Users table, the database won't let you do this:

MySQL 8.4
ERROR:  update or delete on table "companies" violates foreign key constraint "users_company_fkey" on table "users"
DETAIL:  Key (id)=(1) is still referenced from table "users".

If ON DELETE CASCADE was specified, then when deleting the company, all users would be deleted, referring to this company.

There is one more option - ON DELETE SET NULL. When used, the database will write NULL as the value of the company field for all users who worked at the remote company.

ON UPDATE CASCADE means that if a company changes its ID, then all Users will get a new ID in the company field.

Deleting a table

Deleting a table is done using the DROP TABLE operator.

MySQL 8.4
DROP TABLE [IF EXISTS] table_name;
  • [ ]optional part
IF EXISTS

Don't raise an error if there is no table with this name.

KeywordOptional
table_name
The table to delete together with all its data.

Interactive exercise

Now that you've learned the basics of creating tables, try to reinforce the material with an interactive task:

Interactive exercise unavailable

To use the interactive exercise, a screen width of at least 600 pixels is required. Try opening this page on a computer or tablet.

Drag elements from the right panel into the SQL query gaps to create the correct Users table

CREATE TABLE Users (
field 1
type 1
key
field 2
type 2
constraint 2
field 3
type 3
constraint 3
);
Field names:
id
name
age
email
created_at
Data types:
INTEGER
VARCHAR(255)
INTEGER AUTO_INCREMENT
TEXT
TIMESTAMP
Constraints:
PRIMARY KEY
NOT NULL
NOT NULL DEFAULT 18
UNIQUE
DEFAULT CURRENT_TIMESTAMP

Table requirements:

  • Field id: auto-increment integer, primary key
  • Field name: string up to 255 characters, required
  • Field age: integer, required, default value 18