SlideShare a Scribd company logo
1 of 81
SQL
Ahmed Farag
Information Systems Dept.
Faculty of Computers and Information
Menoufia University, Egypt.
MySQL DELETE
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.
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.
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;
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;
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;
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:
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.
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.
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;
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;
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;
Manage Database in MySQL
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;
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;
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 .
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;
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.
Creating a new database using MySQL
Workbench
setup new
connection
Connection
password of
the root user
List of
Connections
Navigator,
Query,
Information,
and Output.
create a new
schema in
the
connected
server
create a new
schema in
the
connected
server
create a new
schema in
the
connected
server
Navigator
section
Set as
Default
Schema
Components
MySQL DROP DATABASE using MySQL
Workbench
DROP
DATABASE
DROP
DATABASE
DROP
DATABASE
DROP
DATABASE
DROP
DATABASE
DROP
DATABASE
MySQL Data Types
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.
MySQL Data Types
MySQL CREATE TABLE Statement By
Examples
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
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.
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.
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,...)
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;
MySQL Primary Key
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.
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)
);
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.
MySQL Foreign Key
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.
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.
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.
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.
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.
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
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
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;
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;
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;
MySQL UNIQUE Constraint
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)
);
MySQL
UNIQUE
Constraint
CREATE TABLE table_1(
...
column_name_1 data_type,
column_name_2 data type,
...
UNIQUE(column_name_1,column_name_2)
);
CREATE TABLE table_1(
...
column_name_1 data_type,
column_name_2 data type,
...
CONSTRAINT constraint_name UNIQUE(column_name
_1,column_name_2)
);
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);
MySQL CHECK Constraint
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
);
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)
);
MySQL NOT NULL Constraint
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;
Introduction to Database View
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.
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.
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.
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.
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.
Creating Views in MySQL
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;
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;
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;

More Related Content

What's hot

Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Trainingbixxman
 
SQL select statement and functions
SQL select statement and functionsSQL select statement and functions
SQL select statement and functionsVikas Gupta
 
Introduction To Oracle Sql
Introduction To Oracle SqlIntroduction To Oracle Sql
Introduction To Oracle SqlAhmed Yaseen
 
Retrieving data using the sql select statement
Retrieving data using the sql select statementRetrieving data using the sql select statement
Retrieving data using the sql select statementSyed Zaid Irshad
 
1. dml select statement reterive data
1. dml select statement reterive data1. dml select statement reterive data
1. dml select statement reterive dataAmrit Kaur
 
Assg2 b 19121033-converted
Assg2 b 19121033-convertedAssg2 b 19121033-converted
Assg2 b 19121033-convertedSUSHANTPHALKE2
 
Using single row functions to customize output
Using single row functions to customize outputUsing single row functions to customize output
Using single row functions to customize outputSyed Zaid Irshad
 
Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)Achmad Solichin
 
Introduction to oracle functions
Introduction to oracle functionsIntroduction to oracle functions
Introduction to oracle functionsNitesh Singh
 
Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007paulguerin
 

What's hot (18)

Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Training
 
Lab1 select statement
Lab1 select statementLab1 select statement
Lab1 select statement
 
SQL select statement and functions
SQL select statement and functionsSQL select statement and functions
SQL select statement and functions
 
Oracle: Basic SQL
Oracle: Basic SQLOracle: Basic SQL
Oracle: Basic SQL
 
Introduction To Oracle Sql
Introduction To Oracle SqlIntroduction To Oracle Sql
Introduction To Oracle Sql
 
Retrieving data using the sql select statement
Retrieving data using the sql select statementRetrieving data using the sql select statement
Retrieving data using the sql select statement
 
1. dml select statement reterive data
1. dml select statement reterive data1. dml select statement reterive data
1. dml select statement reterive data
 
Sql select
Sql select Sql select
Sql select
 
View & index in SQL
View & index in SQLView & index in SQL
View & index in SQL
 
SQL JOINS
SQL JOINSSQL JOINS
SQL JOINS
 
Assg2 b 19121033-converted
Assg2 b 19121033-convertedAssg2 b 19121033-converted
Assg2 b 19121033-converted
 
Using single row functions to customize output
Using single row functions to customize outputUsing single row functions to customize output
Using single row functions to customize output
 
Sql operator
Sql operatorSql operator
Sql operator
 
Oracle: Joins
Oracle: JoinsOracle: Joins
Oracle: Joins
 
Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)
 
Introduction to oracle functions
Introduction to oracle functionsIntroduction to oracle functions
Introduction to oracle functions
 
Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007
 
SQL Tunning
SQL TunningSQL Tunning
SQL Tunning
 

Similar to MYSql manage db

SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowPavithSingh
 
working with database using mysql
working with database using mysql working with database using mysql
working with database using mysql Subhasis Nayak
 
Php, mysq lpart5(mysql)
Php, mysq lpart5(mysql)Php, mysq lpart5(mysql)
Php, mysq lpart5(mysql)Subhasis Nayak
 
Getting Started with MySQL I
Getting Started with MySQL IGetting Started with MySQL I
Getting Started with MySQL ISankhya_Analytics
 
Creating database using sql commands
Creating database using sql commandsCreating database using sql commands
Creating database using sql commandsBelle Wx
 
mysqlanditsbasiccommands-150226033905-conversion-gate02.pdf
mysqlanditsbasiccommands-150226033905-conversion-gate02.pdfmysqlanditsbasiccommands-150226033905-conversion-gate02.pdf
mysqlanditsbasiccommands-150226033905-conversion-gate02.pdfpradnyamulay
 
SQL Database Performance Tuning for Developers
SQL Database Performance Tuning for DevelopersSQL Database Performance Tuning for Developers
SQL Database Performance Tuning for DevelopersBRIJESH KUMAR
 
Chapter – 6 SQL Lab Tutorial.pdf
Chapter – 6 SQL Lab Tutorial.pdfChapter – 6 SQL Lab Tutorial.pdf
Chapter – 6 SQL Lab Tutorial.pdfTamiratDejene1
 
Amazon Redshift: Performance Tuning and Optimization
Amazon Redshift: Performance Tuning and OptimizationAmazon Redshift: Performance Tuning and Optimization
Amazon Redshift: Performance Tuning and OptimizationAmazon Web Services
 
02 database oprimization - improving sql performance - ent-db
02  database oprimization - improving sql performance - ent-db02  database oprimization - improving sql performance - ent-db
02 database oprimization - improving sql performance - ent-dbuncleRhyme
 
Getting Started with MySQL II
Getting Started with MySQL IIGetting Started with MySQL II
Getting Started with MySQL IISankhya_Analytics
 

Similar to MYSql manage db (20)

Using Mysql.pptx
Using Mysql.pptxUsing Mysql.pptx
Using Mysql.pptx
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
 
Sql tables
Sql tablesSql tables
Sql tables
 
MySQL Essential Training
MySQL Essential TrainingMySQL Essential Training
MySQL Essential Training
 
working with database using mysql
working with database using mysql working with database using mysql
working with database using mysql
 
Php, mysq lpart5(mysql)
Php, mysq lpart5(mysql)Php, mysq lpart5(mysql)
Php, mysq lpart5(mysql)
 
Getting Started with MySQL I
Getting Started with MySQL IGetting Started with MySQL I
Getting Started with MySQL I
 
Creating database using sql commands
Creating database using sql commandsCreating database using sql commands
Creating database using sql commands
 
chapter 8 SQL.ppt
chapter 8 SQL.pptchapter 8 SQL.ppt
chapter 8 SQL.ppt
 
MySQL and its basic commands
MySQL and its basic commandsMySQL and its basic commands
MySQL and its basic commands
 
mysqlanditsbasiccommands-150226033905-conversion-gate02.pdf
mysqlanditsbasiccommands-150226033905-conversion-gate02.pdfmysqlanditsbasiccommands-150226033905-conversion-gate02.pdf
mysqlanditsbasiccommands-150226033905-conversion-gate02.pdf
 
Oraclesql
OraclesqlOraclesql
Oraclesql
 
SQL Database Performance Tuning for Developers
SQL Database Performance Tuning for DevelopersSQL Database Performance Tuning for Developers
SQL Database Performance Tuning for Developers
 
Chapter – 6 SQL Lab Tutorial.pdf
Chapter – 6 SQL Lab Tutorial.pdfChapter – 6 SQL Lab Tutorial.pdf
Chapter – 6 SQL Lab Tutorial.pdf
 
Amazon Redshift: Performance Tuning and Optimization
Amazon Redshift: Performance Tuning and OptimizationAmazon Redshift: Performance Tuning and Optimization
Amazon Redshift: Performance Tuning and Optimization
 
SQL
SQLSQL
SQL
 
02 database oprimization - improving sql performance - ent-db
02  database oprimization - improving sql performance - ent-db02  database oprimization - improving sql performance - ent-db
02 database oprimization - improving sql performance - ent-db
 
create database.pptx
create database.pptxcreate database.pptx
create database.pptx
 
UNIT2.ppt
UNIT2.pptUNIT2.ppt
UNIT2.ppt
 
Getting Started with MySQL II
Getting Started with MySQL IIGetting Started with MySQL II
Getting Started with MySQL II
 

More from Ahmed Farag

Introduction to NoSQL and MongoDB
Introduction to NoSQL and MongoDBIntroduction to NoSQL and MongoDB
Introduction to NoSQL and MongoDBAhmed Farag
 
Introduction to OOP concepts
Introduction to OOP conceptsIntroduction to OOP concepts
Introduction to OOP conceptsAhmed Farag
 
Introduction to object-oriented analysis and design (OOA/D)
Introduction to object-oriented analysis and design (OOA/D)Introduction to object-oriented analysis and design (OOA/D)
Introduction to object-oriented analysis and design (OOA/D)Ahmed Farag
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams Ahmed Farag
 
intro to pointer C++
intro to  pointer C++intro to  pointer C++
intro to pointer C++Ahmed Farag
 

More from Ahmed Farag (10)

Intro to php
Intro to phpIntro to php
Intro to php
 
Normalization
NormalizationNormalization
Normalization
 
Introduction to NoSQL and MongoDB
Introduction to NoSQL and MongoDBIntroduction to NoSQL and MongoDB
Introduction to NoSQL and MongoDB
 
Introduction to OOP concepts
Introduction to OOP conceptsIntroduction to OOP concepts
Introduction to OOP concepts
 
Introduction to object-oriented analysis and design (OOA/D)
Introduction to object-oriented analysis and design (OOA/D)Introduction to object-oriented analysis and design (OOA/D)
Introduction to object-oriented analysis and design (OOA/D)
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
 
OOP C++
OOP C++OOP C++
OOP C++
 
Functions C++
Functions C++Functions C++
Functions C++
 
intro to pointer C++
intro to  pointer C++intro to  pointer C++
intro to pointer C++
 
Intro to C++
Intro to C++Intro to C++
Intro to C++
 

Recently uploaded

How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 

Recently uploaded (20)

How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 

MYSql manage db

  • 1. SQL Ahmed Farag Information Systems Dept. Faculty of Computers and Information Menoufia University, Egypt.
  • 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.
  • 20. Creating a new database using MySQL Workbench
  • 26. create a new schema in the connected server
  • 27. create a new schema in the connected server
  • 28. create a new schema in the connected server
  • 32. MySQL DROP DATABASE using MySQL Workbench
  • 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.
  • 42. MySQL CREATE TABLE Statement By Examples
  • 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) );
  • 65. MySQL UNIQUE Constraint CREATE TABLE table_1( ... column_name_1 data_type, column_name_2 data type, ... UNIQUE(column_name_1,column_name_2) ); CREATE TABLE table_1( ... column_name_1 data_type, column_name_2 data type, ... CONSTRAINT constraint_name UNIQUE(column_name _1,column_name_2) );
  • 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) );
  • 70. MySQL NOT NULL Constraint
  • 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;