In this lab, we will look at Data Definition.
So far we have performed SELECT statements on existing tables in the Library and Movie databases. We have also executed INSERT, UPDATE, and DELETE statements.
The above 4 statements are DATA MANIPULATION statements.
We are now going to create a new database and create tables within it. The commands we will look at are DATA DEFINITION commands (statements):
To create a database (also known in MySQL as a schema) we can either of the following commands:
CREATE DATABASE IF NOT EXISTS database_name;
CREATE SCHEMA IF NOT EXISTS schema_name;
Whether we enter CREATE DATABASE or CREATE SCHEMA here, the result is the same. CREATE SCHEMA is a synonym for CREATE DATABASE as of MySQL 5.0.2.
The IF NOT EXISTS part of the statement is optional, and checks whether the database you are creating already exists. If this is the case,
MySQL will ignore the whole statement and it will not create any new object (database or schema or table). The database name you choose must be unique
on your system.
To drop a database, execute either of the following commands:
DROP DATABASE database_name;
DROP SCHEMA schema_name;
The following illustrates the syntax of the CREATE TABLE statement:
CREATE TABLE [IF NOT EXISTS] table_name(
column_list
) engine=table_type;
Let's examine the syntax in greater detail:
unique
within the database.
As before, the IF NOT EXISTS part of the statement checks if the table already exists, and if so, no new table will be created. InnoDB became the default storage engine since MySQL version 5.5. InnoDB brings many benefits of relational database management system such as ACID transaction, referential integrity and crash recovery. In the previous versions, MySQL used MyISAM as the default storage engine.
For more information, see: Alternative Storage Engines
To define a column for the table in the CREATE TABLE statement, you use the following syntax:
column_name data_type[size] [NOT NULL|NULL] [DEFAULT value]
[AUTO_INCREMENT]
[] denotes optional.
The most important components of the syntax above are:
MySQL data types can be grouped into three main categories; text, number and date/time.
create table foo
(
id int auto_increment primary key,
bar smallint(4) unsigned zerofill not null default 0
);
insert into foo (bar) values (781);
select * from foo;
This will return:
ENUM is a data type in MySQL. An ENUM is a string object with a value chosen from a list of permitted values that are enumerated explicitly in the column specification at table creation time.
CREATE TABLE Foo
( color ENUM('red', 'green', 'blue', 'yellow')
);
This column allows you to store one of the values in the enum list, but no other value.
If you want to set particular columns of the table as the primary key, you use the following syntax:
PRIMARY KEY (col1,col2,...)
To set a foreign key, we explicitly link an attribute in one table with the primary key value of another table.
For Example: From our library script
create table Book (
ISBN varchar(15) not null,
title varchar(50) not null,
publisher varchar(30),
publishedDate date,
category varchar(30),
price decimal(5,2),
primary key (ISBN)
);
create table BookCopy(
copyId int auto_increment not null,
ISBN varchar(15) not null,
dateAcquired date not null,
dateDestroyed date,
primary key (copyId),
constraint fk_book foreign key(ISBN) references Book(ISBN)
on update cascade
on delete no action
);
In the foreign key clause you may specify what is to happen to the foreign key value if the primary key is updated or deleted. The options are:
To check what tables (if any) exist in a database, enter the following command:
SHOW tables;
You should see tables MANUFACTURER and CAR. To see a description of the table, CAR, enter:
DESCRIBE car;
or
DESC car;
To alter a table, you can use the any of the following commands:
Add a column:
ALTER TABLE table_name
ADD column_name datatype
Delete a column:
ALTER TABLE table_name
DROP COLUMN column_name
Modify a column:
ALTER TABLE table_name
CHANGE COLUMN old_column_name new_column_name datatype
or
ALTER TABLE table_name
MODIFY COLUMN column_name datatype
To drop a table, you can use the following command:
DROP TABLE table_name;
Note that if you try to delete a table that has related records in another table, you will receive an error message.
The following example demonstrates the creation of a database called Car_Sales
and a table called Manufacturer
.
auto increment
meaning that each manufacturer will automatically be assigned
a unique number by the system. The primary key constraint itself means that the field cannot be blank and the value it contains must be unique within that table. not null
meaning that those fields cannot be blank. Enter the following commands:
CREATE DATABASE IF NOT EXISTS CAR_SALES;
USE CAR_SALES;
CREATE TABLE IF NOT EXISTS MANUFACTURER
(
MCODE INT AUTO_INCREMENT,
MNAME ENUM('Audi', 'BMW', 'Opel', 'Volkswagen', 'Peugeot', 'Renault', 'Alfa Romeo', 'Ford', 'Hyundai', 'Kia',
'Saab', 'SsangYong', 'Honda', 'Lexus', 'Mazda', 'Mitsubishi', 'Nissan', 'Suzuki', 'Toyota') NOT NULL,
MCOUNTRY VARCHAR(20),
PRIMARY KEY(MCODE)
);
We will now create a second table called Car
, which is related to the Manufacturer table. We will add a foreign key constraint that means that we
cannot place a manufacturer code in the car table, unless a related code exists in the manufacturer table.
Note that the field names (primary key field and related foreign key field) do not need to be the
same, but the data type (and size, if relevant) must be the same.
CREATE TABLE IF NOT EXISTS CAR
(
REG VARCHAR(15),
MODEL VARCHAR(10) NOT NULL,
COST DOUBLE(8,2),
MCODE INT,
PRIMARY KEY(REG),
CONSTRAINT FK_MCODE FOREIGN KEY(MCODE)
REFERENCES MANUFACTURER(MCODE)
ON UPDATE CASCADE ON DELETE SET NULL
);
We will now alter a column (cost
) in the car
table:
ALTER TABLE car MODIFY COLUMN cost DECIMAL(8,2);
Insert the following records into the MANUFACTURER table:
INSERT INTO MANUFACTURER (MNAME, MCOUNTRY) VALUES
('Audi','Germany'),
('BMW','Germany'),
('Opel','Germany'),
('Volkswagen','Germany'),
('Peugeot','France'),
('Renault','France'),
('Alfa Romeo','Italy'),
('Ford','USA'),
('Hyundai','South Korea'),
('Kia','South Korea'),
('Saab','Swedan'),
('SsangYong','Swedan'),
('Honda','Japan'),
('Lexus','Japan'),
('Mazda','Japan'),
('Mitsubishi','Japan'),
('Nissan','Japan'),
('Suzuki','Japan'),
('Toyota', 'Japan');
Insert the following records into the CAR table:
INSERT INTO CAR VALUES
('141-KK-345','i30',20760, 9),
('11-WD-1876','i35',14500, 9),
('151-KK-100','Astra',24800, 3),
('12-WX-222','Corolla',19870, 19),
('142-WD-7811','Vectra',28900, 3),
('08-KK-1234','Polo',6500, 4),
('10-WX-9875','Golf',9500, 4);
;
Create a new table called CUSTOMER, with the following attributes:
emailAddress (variable character, size 40)
Primary key: customerId
Create a new table called VIEWINGS, with the following attributes:
comments (variable character, size 250)
Primary key: customerId, reg
Foreign key: customerId (related to CUSTOMER table)
Foreign key: reg (related to CAR table)
Add cascade update and delete constraints for both of the foreign key values.
Insert 2 CUSTOMER records and 5 VIEWINGS records. Remember when inserting records into the VIEWINGS table, the customerId value must match a value from the CUSTOMER table and the reg value must match a value from the CAR table.
Write select statements for each of the following:
Solutions for the exercises in this lab are available here: Week6.zip