This tutorial will see how to create tables using MySQL in both the command line and the MySQL Workbench.
To create tables in MySQL, we use the CREATE TABLE statement.
The basic syntax of Create Table as per MySQL documentation is as follows:
CREATE TABLE [IF NOT EXISTS] <table_name>(
<column names> <datatype> <conditions>
<table constraints>
)
The conditions we can mention are as follows:
CREATE
Privileges.CREATE
privileges) credentials.
USE somedb;
CREATE TABLE EMPLOYEES(
EMP_ID INT AUTO_INCREMENT PRIMARY KEY,
FIRST_NAME VARCHAR(20) NOT NULL,
LAST_NAME VARCHAR(20),
BIRTH_DATE DATE DEFAULT '1900-00-00',
HIRE_DATE DATE DEFAULT (CURRENT_DATE())
);
The command above creates a table with only the Primary Key constraint and InnoDB as the storage engine and all visible columns.
show tables;
desc employees;
We can add the following conditions to Foreign key constraints
By default, if we do not mention any conditions, both the CASCADE
options are set to "Restrict." In such a case, we cannot update or delete records from the main table unless all the tables that reference the foreign key are updated or deleted.
CREATE TABLE DEPT_LOCATIONS(
LOCATION_ID INT AUTO_INCREMENT PRIMARY KEY,
DEPT_ID INT,
LOCATION_NAME VARCHAR(40),
FOREIGN KEY (DEPT_ID) REFERENCES DEPARTMENTS(DEPT_ID)
);
The table DEPARTMENTS does not exist yet.
After creating the Departments table, we can trigger the creation script for the DEPT_LOCATIONS
table.
CREATE TABLE EMPLOYEE_DEPT(
RECORD_ID INT AUTO_INCREMENT PRIMARY KEY,
EMP_ID INT,
DEPT_ID INT,
FROM_DATE DATE,
TO_DATE DATE,
FOREIGN KEY (EMP_ID) REFERENCES EMPLOYEES(EMP_ID) On UPDATE cascade ON DELETE CASCADE,
FOREIGN KEY (DEPT_ID) REFERENCES DEPARTMENTS(DEPT_ID) On UPDATE restrict ON DELETE CASCADE
);
We can also create a table that is a replica of another table by using the Like clause. For example, we will create a new Employees2 table exactly like the Employees table using LIKE
CREATE TABLE EMPLOYEES2 LIKE EMPLOYEES;