3. MySQL
DELETE
• To delete data from a table, you use the MySQL DELETE
statement. The following illustrates the syntax of the DELETE
statement:
DELETE FROM table_name
WHERE condition;
• In this statement:
• First, specify the table from which you delete data.
• Second, use a condition to specify which rows to delete in
the WHERE clause. If the row matches the condition, it
will be deleted.
• Notice that the WHERE clause is optional. If you omit the
WHERE clause, the DELETE statement will delete all rows in
the table.
• Besides deleting data from a table, the DELETE statement
returns the number of rows deleted.
4. MySQL
DELETE
• To delete data from multiple tables using a single DELETE
statement, you use the DELETE JOIN statement which we will
cover in the next tutorial.
• To delete all rows in a table without the need of knowing how
many rows deleted, you should use the TRUNCATE TABLE
statement to get better performance.
• For a table that has a foreign key constraint, when you delete
rows from the parent table, the rows in the child table will be
deleted automatically by using the ON DELETE CASCADE
option.
5. MySQL
DELETE
examples
• Suppose you want to delete employees whose the
officeNumber are4, you use the DELETE statement with the
WHERE clause as shown in the following query:
DELETE FROM employees
WHERE
officeCode = 4;
• To delete all rows from the employees table, you use the
DELETE statement without the WHERE clause as follows:
DELETE FROM employees;
6. MySQL
DELETE
and
LIMIT
clause
• If you want to limit the number of rows to be deleted, you use
the LIMIT clause as follows:
• Note that the order of rows in a table is unspecified,
therefore, when you use the LIMIT clause, you should always
use the ORDER BY clause.
DELETE FROM table
LIMIT row_count;
DELETE FROM table_name
ORDER BY c1, c2, ...
LIMIT row_count;
7. MySQL
DELETE
and
LIMIT
clause
• For example, the following statement sorts customers by
customer’s names alphabetically and deletes the first 10
customers:
• Similarly, the following DELETE statement selects customers in
France, sorts them by credit limit in from low to high, and
deletes the first 5 customers:
DELETE FROM customers
ORDER BY customerName
LIMIT 10;
DELETE FROM customers
WHERE country = 'France'
ORDER BY creditLimit
LIMIT 5;
8. MySQL
ON
DELETE
CASCADE
• MySQL ON DELETE CASCADE: Deleting Data From Multiple
Related Tables
• MySQL provides a more effective way called ON DELETE
CASCADE referential action for a foreign key that allows you
to delete data from child tables automatically when you
delete the data from the parent table.
• Example:
• Suppose we have two tables: buildings and rooms . In this
database model, each building has one or more rooms.
However, each room belongs to one only one building. A room
would not exist without a building.
• The relationship between the buildings and rooms tables is
one-to-many (1:N) as illustrated in the following database
diagram:
9. MySQL
ON
DELETE
CASCADE
• When we delete a row from the buildings table, we also want
to delete the rows in the rooms table that references to the
rows in the buildings table. For example, when we delete a
row with building no. 2 in the buildings table as the following
query:
DELETE FROM buildings
WHERE
building_no = 2;
• We want the rows in the rooms table that refers to building
number 2 will be also removed.
10. MySQL
ON
DELETE
CASCADE
• Create the buildings table:
CREATE TABLE buildings (
building_no INT PRIMARY KEY AUTO_INCREMENT,
building_name VARCHAR(255) NOT NULL,
address VARCHAR(255) NOT NULL
);
• Create the rooms table:
CREATE TABLE rooms (
room_no INT PRIMARY KEY AUTO_INCREMENT,
room_name VARCHAR(255) NOT NULL,
building_no INT NOT NULL,
FOREIGN KEY (building_no)
REFERENCES buildings (building_no)
ON DELETE CASCADE
);
• Notice that we add the ON DELETE CASCADE clause at the
end of the foreign key constraint definition.
11. MySQL
ON
DELETE
CASCADE
• Insert data into the buildings table:
• Query data from the buildings table:
INSERT INTO buildings(building_name,address)
VALUES('ACME Headquaters','3950 North 1st Street CA
95134'),
('ACME Sales','5000 North 1st Street CA 95134');
SELECT * FROM buildings;
12. MySQL
ON
DELETE
CASCADE
• Insert data into the rooms table:
• Query data from the rooms table:
INSERT INTO rooms(room_name,building_no)
VALUES('Amazon',1),
('War Room',1),
('Office of CEO',1),
('Marketing',2),
('Showroom',2);
SELECT * FROM rooms;
13. MySQL
ON
DELETE
CASCADE
• Delete the building with building no. 2:
• Query data from rooms table:
DELETE FROM buildings
WHERE
building_no = 2;
SELECT * FROM rooms;
15. Creating
Databases
• Before doing anything else with the data, you need to create a
database. A database is a container of data. It stores
contacts, vendors, customers or any kind of data that you can
think of.
• In MySQL, a database is a collection of objects that are used
to store and manipulate data such as tables, database views.
• To create a database in MySQL, you use the CREATE
DATABASE statement as follows:
CREATE DATABASE [IF NOT EXISTS] database_name;
• For example, to create classicmodels database, you can
execute the CREATE DATABASE statement as follows:
CREATE DATABASE classicmodels;
16. Displaying
Databases
• The SHOW DATABASES statement lists all databases in the
MySQL database server. You can use the SHOW DATABASES
statement to check the database that you’ve created or to see
all the databases on the database server before you create a
new database, for example:
• As clearly shown in the output, we have three databases in
the MySQL database server. The information_schema and
mysql are the default databases that are available when we
install MySQL, and the classicmodels is the new database that
we have created.
SHOW DATABASES;
17. Selecting a
database
to work
with
• Before working with a particular database, you must tell
MySQL which database you want to work with by using the
USE statement.
• You can select the classicmodels sample database using the
USE statement as follows:
USE database_name;
USE classicmodels;
• From now, all operations such as querying data, create new
tables or calling stored procedures which you perform, will
take effects on the current database i.e., classicmodels .
18. Removing
Databases
• Removing database means deleting all the tables contained in
the database and the database itself permanently. Therefore,
it is very important to execute this query with extra cautions.
• To delete a database, you use the DROP DATABASE statement
as follows:
DROP DATABASE [IF EXISTS] database_name;
19. Removing
Databases
• If you want to practice with the DROP DATABASE statement,
you can create a new database, make sure that it is created,
and remove it.
• Let’s look at the following queries:
CREATE DATABASE IF NOT EXISTS tempdb;
SHOW DATABASES;
DROP DATABASE IF EXISTS temp_database;
• The sequence of three statements is as follows:
1. First, we created a database named tempdb using the
CREATE DATABASE statement.
2. Second, we displayed all databases using the SHOW
DATABASES statement.
3. Third, we removed the tempdb using the DROP
DATABASE statement.
40. MySQL
Data Types
• A database table contains multiple columns with specific data
types such as numeric or string.
• MySQL provides more data types other than just numeric or
string. Each data type in MySQL can be determined by the
following characteristics:
1. The kind of values it represents.
2. The space that takes up and whether the values is a
fixed-length or variable length.
43. CREATE
TABLE
• To create a new table within a database, you use the MySQL
CREATE TABLE statement.
• The following illustrates the syntax of the simplified version of
the CREATE TABLE statement:
• First, you specify the name of the table that you want to create
after the CREATE TABLE clause. The table name must be unique
within a database. The IF NOT EXISTS is an optional clause that
allows you to check if the table that you are creating already
exists in the database. If this is the case, MySQL will ignore the
whole statement and will not create any new table.
• Second, you specify a list of columns for the table in the
column_list section, columns are separated by commas.
• Third, you can optionally specify the storage engine for the table
in the ENGINE clause. You can use any storage engine such as
InnoDB and MyISAM. If you don’t explicitly declare the storage
engine, MySQL will use InnoDB by default.
CREATE TABLE [IF NOT EXISTS] table_name(
column_list
) ENGINE=storage_engine
44. CREATE
TABLE
• InnoDB became the default storage engine since MySQL
version 5.5. The InnoDB storage engine brings many benefits
of a 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.
45. CREATE
TABLE
• To define a column for the table in the CREATE TABLE
statement, you use the following syntax:
column_name data_type(length) [NOT NULL] [DEFAULT
value] [AUTO_INCREMENT]
• The most important components of the syntax above are:
• The column_name specifies the name of the column.
Each column has a specific data type and maximum
length e.g.,VARCHAR(255)
• The NOT NULL indicates that the column does not allow
NULL.
• The DEFAULT value is used to specify the default value of
the column.
• The AUTO_INCREMENT indicates that the value of the
column is generated by one automatically whenever a
new row is inserted into the table. Each table has one and
only one AUTO_INCREMENT column.
46. CREATE
TABLE
• If you want to set a column or a set of columns as the primary
key, you use the following syntax:
PRIMARY KEY (col1,col2,...)
47. Example
• The following statement creates a new table named tasks:
CREATE TABLE IF NOT EXISTS t
asks (
task_id INT AUTO_INCREMENT
,
title VARCHAR(255) NOT NULL,
start_date DATE,
due_date DATE,
status TINYINT NOT NULL,
priority TINYINT NOT NULL,
description TEXT,
PRIMARY KEY (task_id)
) ENGINE=INNODB;
49. MySQL
Primary
Key
• A primary key is a column or a set of columns that uniquely
identifies each row in the table. You must follow the rules
below when you define a primary key for a table:
• A primary key must contain unique values. If the primary
key consists of multiple columns, the combination of
values in these columns must be unique.
• A primary key column cannot contain NULL values. It
means that you have to declare the primary key column
with the NOT NULL attribute. If you don’t, MySQL will
force the primary key column as NOT NULL implicitly.
• A table has only one primary key.
50. MySQL
Primary
Key
CREATE TABLE users(
user_id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(40),
password VARCHAR(255),
email VARCHAR(255)
);
CREATE TABLE roles(
role_id INT AUTO_INCREMENT,
role_name VARCHAR(50),
PRIMARY KEY(role_id)
);
CREATE TABLE user_roles(
user_id INT NOT NULL,
role_id INT NOT NULL,
PRIMARY KEY(user_id,role_id),
FOREIGN KEY(user_id) REFERENCES users(user_id),
FOREIGN KEY(role_id) REFERENCES roles(role_id)
);
51. MySQL
Primary
Key
• If a table, for some reasons, does not have a primary key, you
can use the ALTER TABLEstatement to define the primary key
of the table as shown in the following statement:
ALTER TABLE table_name
ADD PRIMARY KEY(primary_key_column);
CREATE TABLE t1(
id INT,
title VARCHAR(255) NOT NULL
);
ALTER TABLE t1
ADD PRIMARY KEY(id);
• The following example adds the id column to the primary key.
53. MySQL
Foreign
Key
• A foreign key is a field in a table that matches another field of
another table. A foreign key places constraints on data in the
related tables, which enables MySQL to maintain referential
integrity.
• Let’s take a look at the following database diagram in the
sample database.
54. MySQL
Foreign
Key
• We have two tables: customers and orders. Each customer
has zero or more orders and each order belongs to only one
customer. The relationship between customers table and
orders table is one-to-many, and it is established by a foreign
key in the orders table specified by the customerNumber
field. The customerNumber field in the orders table relates to
the customerNumber primary key field in the customers
table.
• The customers table is called parent table or referenced
table, and the orders table is known as child table or
referencing table.
• A foreign key can be a column or a set of columns. The
columns in the child table often refer to the primary key
columns in the parent table.
55. MySQL
Foreign
Key
• A table may have more than one foreign key, and each
foreign key in the child table may refer to a different parent
table.
• A row in the child table must contain values that exist in the
parent table e.g., each order record in the orders table must
have a customerNumber that exists in the customers table.
Multiple orders can refer to the same customer therefore, this
relationship is called one (customer) to many (orders), or one-
to-many.
56. MySQL
Foreign
Key
• Sometimes, the child and parent tables are the same. The
foreign key refers back to the primary key of the table e.g., the
following employees table:
• The reportTo column is a foreign key that refers to the
employeeNumber column which is the primary key of the
employees table to reflect the reporting structure between
employees i.e., each employee reports to another employee
and an employee can have zero or more direct reports. We
have a specific tutorial on the self-join to help you query data
against this kind of table.
• The reportTo foreign key is also known as recursive or self-
referencing foreign key.
57. MySQL
Foreign
Key
• In addition, you can set up a cascade on delete action for the
customerNumber foreign key so that when you delete a
customer in the customers table, all the orders associated
with the customer are also deleted. This saves you time and
efforts of using multiple DELETE statements statement.
• The same as deletion, you can also define a cascade on
update action for the customerNumber foreign key to
perform the cross-table update without using multiple
UPDATE statements statement.
58. MySQL
Foreign
Key
• The following syntax illustrates how to define a foreign key in
a child table in CREATE TABLE statement.
CONSTRAINT constraint_name
FOREIGN KEY foreign_key_name (columns)
REFERENCES parent_table(columns)
ON DELETE action
ON UPDATE action
59. Examples
• The following example creates a dbdemo database and two
tables: categories and products. Each category has one or
more products and each product belongs to only one
category. The cat_id field in the products table is defined as a
foreign key with UPDATE ON CASCADE and DELETE ON
RESTRICT actions.
CREATE DATABASE IF NOT EXISTS d
bdemo;
USE dbdemo;CREATE TABLE categories(
cat_id int not null auto_increment primary k
ey,
cat_name varchar(255) not null,
cat_description text
) ENGINE=InnoDB;
CREATE TABLE products(
prd_id int not null auto_increment primary k
ey,
prd_name varchar(355) not null,
prd_price decimal,
cat_id int not null,
FOREIGN KEY fk_cat(cat_id)
REFERENCES categories(cat_id)
ON UPDATE CASCADE
ON DELETE RESTRICT
60. MySQL
Foreign
Key
• You also use the ALTER TABLE statement to drop foreign key
as the following statement:
ALTER TABLE table_name
DROP FOREIGN KEY constraint_name;
61. MySQL
Foreign
Key
CREATE TABLE products (
prd_id int(11) NOT NULL AUTO_INCREMENT,
prd_name varchar(355) NOT NULL,
prd_price decimal(10,0) DEFAULT NULL,
cat_id int(11) NOT NULL,
vdr_id int(11) NOT NULL,
PRIMARY KEY (prd_id),
KEY fk_cat (cat_id),
KEY fk_vendor(vdr_id),
CONSTRAINT products_ibfk_2
FOREIGN KEY (vdr_id)
REFERENCES vendors (vdr_id)
ON DELETE NO ACTION
ON UPDATE CASCADE,
CONSTRAINT products_ibfk_1
FOREIGN KEY (cat_id)
REFERENCES categories (cat_id)
ON UPDATE CASCADE
) ENGINE=InnoDB;
62. MySQL
Foreign
Key
• You can drop the foreign keys of the products table by using
the following statement:
ALTER TABLE products
DROP FOREIGN KEY products_ibfk_1;
ALTER TABLE products
DROP FOREIGN KEY products_ibfk_2;
64. MySQL
UNIQUE
Constraint
• Sometimes, you want to enforce the uniqueness value in a
column e.g., the phones of the suppliers in the suppliers table
must be unique, or the combination of the supplier name and
address must not be duplicate.
• To enforce this rule, you need to use the UNIQUE constraint.
• The UNIQUE constraint is either column constraint or table
constraint that defines a rule that constrains values in a
column or a group of columns to be unique.
CREATE TABLE table_1(
column_name_1 data_type UNIQUE,
);
CREATE TABLE table_1(
...
column_name_1 data_type,
...
UNIQUE(column_name_1)
);
66. MySQL
UNIQUE
Constraint
CREATE TABLE IF NOT EXISTS suppliers (
supplier_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
phone VARCHAR(12) NOT NULL UNIQUE,
address VARCHAR(255) NOT NULL,
CONSTRAINT uc_name_address UNIQUE (name , ad
dress)
);
ALTER TABLE table_name
ADD CONSTRAINT constraint_name UNIQUE (column_li
st);
ALTER TABLE suppliers
ADD CONSTRAINT uc_name_address UNIQUE (name,a
ddress);
68. MySQL
UNIQUE
Constraint
• SQL standard provides you with CHECK constraints that allow
you to validate data for a column or a group of columns
before insert and update. For example, you can define a
CHECK constraint to enforce the cost of a part to be positive
as follows:
CREATE TABLE IF NOT EXISTS parts (
part_no VARCHAR(18) PRIMARY KEY,
description VARCHAR(40),
cost DECIMAL(10 , 2 ) NOT NULL CHECK(cost > 0),
price DECIMAL (10,2) NOT NULL
);
69. MySQL
UNIQUE
Constraint
• SQL standard also allows you to apply multiple CHECK
constraints to a column or a code CHECK constraint across
multiple columns. For example, to make sure that the price is
always greater or equal to cost, you use the following CHECK
constraint:
CREATE TABLE IF NOT EXISTS parts (
part_no VARCHAR(18) PRIMARY KEY,
description VARCHAR(40),
cost DECIMAL(10 , 2 ) NOT NULL CHECK (cost > 0),
price DECIMAL(10 , 2 ) NOT NULL CHECK (price > 0),
CHECK (price >= cost)
);
71. MySQL
UNIQUE
Constraint
• The NOT NULL constraint is a column constraint that forces
the values of a column to non-NULL values only.
CREATE TABLE tasks (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
start_date DATE NOT NULL,
end_date DATE
);
ALTER TABLE table_name
CHANGE old_column_name new_column_name new_col
umn_definition;
ALTER TABLE tasks
CHANGE end_date end_date DATE NOT NULL;
73. Database
View
• A database view is a virtual table or logical table which is
defined as a SQL SELECT query with joins. Because a database
view is similar to a database table, which consists of rows and
columns, so you can query data against it. Most database
management systems, including MySQL, allow you to update
data in the underlying tables through the database view with
some prerequisites.
74. Database
View
• A database view is dynamic because it is not related to the
physical schema. The database system stores views as a SQL
SELECT statement with joins. When the data of the tables
changes, the view reflects that changes as well.
75. Database
View
• Advantages of database view:
• A database view helps limit data access to specific users.
• A database view provides extra security layer (The
database view allows you to create the read-only view to
expose read-only data to specific users.).
• A database view enables backward compatibility.
Suppose you have a central database, which many
applications are using it. One day, you decide to redesign
the database to adapt to the new business requirements.
You remove some tables and create new tables, and you
don’t want the changes to affect other applications. In
this scenario, you can create database views with the
same schema as the legacy tables that you will remove.
76. Database
View
• Advantages of database view:
• A database view helps limit data access to specific users.
• A database view provides extra security layer (The
database view allows you to create the read-only view to
expose read-only data to specific users.).
• A database view enables backward compatibility.
Suppose you have a central database, which many
applications are using it. One day, you decide to redesign
the database to adapt to the new business requirements.
You remove some tables and create new tables, and you
don’t want the changes to affect other applications. In
this scenario, you can create database views with the
same schema as the legacy tables that you will remove.
77. Database
View
• Disadvantages of database view
• Performance: querying data from a database view can be
slow especially if the view is created based on other
views.
• Tables dependency: you create a view based on
underlying tables of the database. Whenever you change
the structure of these tables that view associated with,
you have to change the view as well.
79. Creating
Views in
MySQL
• To create a new view in MySQL, you use the CREATE VIEW
statement. The syntax of creating a view in MySQL is as
follows:
CREATE
[ALGORITHM = {MERGE | TEMPTABLE | UNDEFINED
}]
VIEW view_name [(column_list)]
AS
select-statement;
CREATE VIEW SalePerOrder AS
SELECT
orderNumber, SUM(quantityOrdered * priceEach) tot
al
FROM
orderDetails
GROUP by orderNumber
ORDER BY total DESC;
80. Creating
Views in
MySQL
• The following is an example of creating a view with
INNER JOIN . The view contains the order number,
customer name, and total sales per order.
CREATE VIEW customerOrders AS
SELECT
d.orderNumber,
customerName,
SUM(quantityOrdered * priceEach) total
FROM
orderDetails d
INNER JOIN
orders o ON o.orderNumber = d.orderNumber
INNER JOIN
customers c ON c.customerNumber = c.customerNu
mber
GROUP BY d.orderNumber
ORDER BY total DESC;
81. Creating
Views in
MySQL
• The following illustrates how to create a view with a
subquery. The view contains products whose buy prices
are higher than the average price of all products.
CREATE VIEW aboveAvgProducts AS
SELECT
productCode, productName, buyPrice
FROM
products
WHERE
buyPrice >
(SELECT
AVG(buyPrice)
FROM
products)
ORDER BY buyPrice DESC;