RienSQL
LESSON 37 / 62 · Creating and deleting tables

Creating and deleting tables

SQL create and delete tables in MySQL and PostgreSQL. Table description operators.

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

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

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

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

IF NOT EXISTS
KeywordOptional
table_name
The name of the new table.

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

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.

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:

CREATE TABLE Users (
    id INTEGER PRIMARY KEY AUTO_INCREMENT,
    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;
  • 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.

CREATE TABLE Users (
    id INTEGER PRIMARY KEY AUTO_INCREMENT,
    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.

DESCRIBE Users;
FieldTypeNullKeyDefaultExtra
idintNOPRINULLauto_increment
namevarchar(255)NONULL
ageintNO18

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:

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:

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:

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

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

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.

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

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

external_table
The table whose records the foreign key refers to.
ON DELETE action
OptionalRESTRICTCASCADESET NULLNO ACTION
ON UPDATE action
OptionalRESTRICTCASCADESET NULLNO ACTION

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

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.

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:

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.

Deleting a table

Deleting a table is done using the DROP TABLE operator.

MySQL 8.4

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

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

IF EXISTS
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 1type 1keyfield 2type 2constraint 2field 3type 3constraint 3);Field names:idnameageemailcreated_atData types:INTEGERVARCHAR(255)INTEGER AUTO_INCREMENTTEXTTIMESTAMPConstraints:PRIMARY KEYNOT NULLNOT NULL DEFAULT 18UNIQUEDEFAULT 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

Practice

Solve it in the editor. The query runs against a sample database in your browser.

Task 1Create the Classrooms table
Create the Classrooms table with the following fields:
  • id is a required field of type INTEGER that is the primary key with auto-increment
  • room_number is a required unique field of type INTEGER
  • floor is a required field of type INTEGER with the default value 1
  • building is a required field of type VARCHAR(50)
  • description is a field of type TEXT
  • created_at is a field of type TIMESTAMP with a default value equal to the current date and time
SQL editor
SQLite
Ctrl / ⌘ + ↵
Result

Write a query and run it to see the results.

Task 2Create the Homework table
Create the Homework table with the following fields:
  • id is a required field of type INTEGER that is the primary key with auto-increment
  • lesson_id is a required field of type INTEGER
  • description is a required field of type TEXT
  • due_date is a required field of type DATE
Add a foreign key for lesson_id referencing Lessons(id). Changes should cascade when the referenced row is deleted or updated.
SQL editor
SQLite
Ctrl / ⌘ + ↵
Result

Write a query and run it to see the results.

Task 3Drop the Timepair table
Drop the Timepair table from the database.
SQL editor
SQLite
Ctrl / ⌘ + ↵
Result

Write a query and run it to see the results.