More Related Content Similar to RDBMS with MySQL Similar to RDBMS with MySQL (20) More from People Strategists More from People Strategists (14) RDBMS with MySQL2. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Overview of Database Models
Basic Definitions:
Data: Known facts that can be recorded and have an implicit meaning.
Table: A collection of data elements organized in terms of rows and columns.
Record/Tuple: A single entry in a table is called a record or a tuple.
Field/Attributes: A table consists of several records and each record can be broken into
various smaller entities known as fields.
Database: A collection of related data.
Database Management System (DBMS): A software system that facilitates the creation
and maintenance of a computerized database.
Database System: The DBMS software together with the data itself. Sometimes, the
applications are also included.
3. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Overview of Database Models
Database Models:
Define how the logical structure of a database is modeled.
Are fundamental entities to introduce abstraction in a DBMS.
Define how different parts of data are connected to each other and how these are
processed and stored inside the system.
4. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Overview of Database Models
Types of Database Models
Object-oriented Model
Relational Model
Network Model
Hierarchical Model
5. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Overview of Database Models (Contd.)
Hierarchical Model:
The data is organized in a tree structure.
There is a hierarchy of parent and child data segments.
A parent can have many children, but a child can have a single parent.
This structure allows one-to-many relationship between two types of data.
6. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Overview of Database Models (Contd.)
Example of Hierarchical Model:
7. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Overview of Database Models (Contd.)
Network Model:
Entities are organized in a graph, in which some entities can be accessed through
several path.
A parent can have multiple children and a child can also have multiple parents.
This structure allows many-to-many relationship between two types of data.
8. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Overview of Database Models (Contd.)
Example of Network Model:
9. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Overview of Database Models (Contd.)
Relational Model:
All data is represented in terms of tuples, grouped into relations.
The tables or relations are related to each other.
A database organized in terms of the relational model is a relational database.
The purpose of the relational model is to provide a declarative method for
specifying data and queries.
10. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Overview of Database Models (Contd.)
Example of Relational Model:
11. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Overview of Database Models (Contd.)
Object-Oriented Model:
Both data and their relationship are contained in a single structure known as an
object.
An object includes information about relationship between the facts within the
object, as well as information about its relationship with other objects.
An object is the abstraction of the real-word entity. An object represents only one
occurrence of an entity.
Attributes describe the property of an object.
Objects that are similar in characteristics are grouped in a class.
12. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Overview of Database Models (Contd.)
Example of Object-Oriented Model :
Employee
Name
ID
Salary
13. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Introduction to RDBMS
A Relational Database Management System (RDBMS):
Is a database management system based on relational model introduced by E.F
Codd.
Represents data in terms of tuples(rows).
Is used to manage Relational database.
Relational Database:
Is a collection of organized set of tables from which data can be accessed easily.
Consists of number of tables and each table has its own primary key.
14. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Keys
Super Key is defined as a set of attributes within a table that uniquely identifies
each record within a table. Super Key is a superset of Candidate key.
A Candidate Key:
o Is a subset of a super key.
o Is a single field or the least combination of fields that uniquely identifies each record in
the table. The least combination of fields distinguishes a candidate key from a super
key.
o Must contain unique values.
o Must not contain null values.
o Contains the minimum number of fields to ensure uniqueness.
o Must uniquely identify each record in the table.
15. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Keys
Example of Candidate Key:
16. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Keys (Contd.)
Primary Key:
Is a candidate key that is most appropriate to be the main reference key for the
table.
Is used throughout the database to help establish relationships with other tables.
Must contain unique values, must never be null and should uniquely identify each
record in the table.
17. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Keys (Contd.)
Example of Primary Key:
18. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Keys (Contd.)
A foreign Key is generally a primary key from one table that appears as a field in
another table, where the first table has a relationship to the second.
For example, if we had a table A with a primary key X that linked to a table B where
X was a field in B, then X would be a foreign key in B.
19. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Keys (Contd.)
Example of Foreign Key:
20. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Keys (Contd.)
Alternate key is any candidate key which is not selected to be the primary key.
Compound key (also called a composite key or concatenated key) is a key that
consists of 2 or more attributes.
21. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Normalization
The main goal of Database Normalization is to restructure the logical data model of a
database to:
Eliminate redundancy
Organize data efficiently
Reduce the potential for data anomalies
Data Anomalies:
Are inconsistencies in the data stored in a database as a result of an operation, such as
update, insertion, and/or deletion.
May arise when have a particular record stored in multiple locations and not all of the
copies are updated.
Can be prevented by implementing normalization.
22. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Normalization (Contd.)
Dependencies:
Multivalued Attributes (or repeating groups): Non-key attributes or groups of non-
key attributes, the values of which are not uniquely identified by (directly or
indirectly) (not functionally dependent on) the value of the Primary Key (or its
part).
Example:
STUDENT
Stud_ID Name Course_ID Units
101 Lennon MSI 250 3.00
101 Lennon MSI 415 3.00
125 Johnson MSI 331 3.00
23. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Normalization (Contd.)
Partial Dependency: When a non-key attribute is determined by a part, but not the
whole, of a composite primary key.
Example:
24. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Normalization (Contd.)
Transitive Dependency: When a non-key attribute determines another non-key
attribute.
Example:
25. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Normalization (Contd.)
Normalization rules are divided into the following normal forms:
First Normal Form (1NF)
Second Normal Form (2NF)
Third Normal Form (3NF)
Boyce and Codd Normal Form (BCNF)
26. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Normalization (Contd.)
Requirements to satisfy 1NF:
Each table has a primary key.
The values in each column of a table are atomic (No multi-value attributes
allowed).
There are no repeating groups: two columns do not store similar information in the
same table.
27. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Normalization (Contd.)
Example of 1NF:
The Student Table
28. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Normalization (Contd.)
Requirements to satisfy 2NF:
All requirements for 1NF must be met.
Redundant data across multiple rows of a table must be moved to a separate table.
o The resulting tables must be related to each other by use of foreign key.
29. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Normalization (Contd.)
Example of 2NF:
New Student Table
New Subject Table
30. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Normalization (Contd.)
Requirements to satisfy 3NF:
All requirements for 2NF must be met.
Eliminate fields that do not depend on the primary key;
o That is, any field that is dependent not only on the primary key but also on another
field must be moved to another table.
31. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Normalization (Contd.)
Example of 3NF:
Student_Detail Table
New Student_Detail Table
Address Table
32. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Normalization (Contd.)
Requirements to satisfy BCNF:
All requirements for 3NF must be met.
For each functional dependency ( X -> Y ), X should be a super Key.
Example:
Consider the relationship, R(E, F, G, H) and the dependencies E->FGH, FG->EH, and
H->F. This relationship is already in 3NF. Keys are E and FG. Thus, in FD E->FGH, E is the
super key. In second relation, FG->EH, FG is also a key. But, in H->F, H is not a key.
Thus, we can break R into R1 and R2 as shown below:
R1(E,H,G) and R2(H,F)
33. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
ER Diagrams
ER Diagrams:
Were proposed by Peter Chen in 1976.
Are widely used in database design.
Represent conceptual level of a database system.
Describe entities and their relationships in high level.
34. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
ER Diagrams (Contd.)
Basic Concepts Required for ER Diagrams:
Entity – An abstraction of similar things, e.g. cars, students, and employees.
o An entity set contains many entities.
Attributes: Common properties of the entities in entity sets.
Relationship: Specifies the relations among entities from two or more entity sets.
35. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
ER Diagrams (Contd.)
Symbols and Notations:
Symbols Notations
Entity
Relationship
Attribute
36. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
ER Diagrams (Contd.)
Symbols Notations
Weak Entity
Weak Entity Relationship
Multivalued Attribute
37. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
ER Diagrams (Contd.)
Symbols Notations
Key Attribute
Composite Attribute
38. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
ER Diagrams (Contd.)
Types of relationship that exist between Entities:
Binary Relationship: Means relation between two entities.
Recursive Relationship: An Entity is related to itself.
Ternary Relationship: Relationship of degree three.
39. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
ER Diagrams (Contd.)
Binary relationship is further divided into three types:
1. One-to-one
40. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
ER Diagrams (Contd.)
2. One-to-many
3. Many-to-one
41. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
ER Diagrams (Contd.)
An ER Diagram:
42. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Features of MySQL
Some of the MySQL features are:
Open source: MySQL source code is available on Internet that can be modified by
anyone.
Portable: It is compatible with various operating systems, such as Windows, Linux,
and Mac OS. It can also run on different types of system architectures.
Scalable: It is capable of managing small as well as large databases.
Reliable: It can deliver high performance under varying conditions.
43. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Features of MySQL
Easy to use: MySQL provides Graphical User Interface (GUI) as well as Command
line User Interface (CUI). Database Developers can choose the most appropriate
interface for interacting with database.
Secure: Only authorized users can access the database. This is possible by creating
dedicated accounts for users.
High availability: MySQL supports replication. Various copies of server are available
on the same computer or on different computers. Replication ensures 24*7
availability of the database server across different locations. A large number of
client requests can be handled uninterruptedly.
44. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
MySQL Data Types
MySQL uses many different data types broken into three categories:
Numeric
Date and time
String
45. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
MySQL Data Types (Contd.)
Numeric Data Types
Data type Description Range for signed
integers
Range for
unsigned
integers
Storage in
bytes
INT A normal-sized integer
that can be signed or
unsigned. You can
specify a width of up to
11 digits.
–2,147,483,648 to
2,147,483,647
0 to
4294967295
4
TINYINT A very small integer that
can be signed or
unsigned. You can
specify a width of up to 4
digits.
–128 to 127 0 to 255 1
46. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
MySQL Data Types (Contd.)
Data type Description Range for signed
integers
Range for
unsigned
integers
Storage
in bytes
SMALLINT A small integer that can
be signed or unsigned.
You can specify a width of
up to 5 digits.
–32,768 to 32,767 0 to 65535 2
MEDIUMINT A medium-sized integer
that can be signed or
unsigned. You can specify
a width of up to 9 digits.
–83,88,608 to 83,88,607 0 to 16777215 3
BIGINT A large integer that can
be signed or unsigned.
You can specify a width of
up to 20 digits.
–9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
0 to
1844674407370
9551615
8
47. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
MySQL Data Types (Contd.)
Data type Description Range Stores Storage
in bytes
FLOAT(M,D)
A floating-point number
that cannot be unsigned.
You can define the
display length (M) and
the number of decimals
(D).
–3.402823466E+38 to –
1.175494351E–38, 0 and
1.175494351E–38 to
3.402823466E+38
Fractional value
with floating
single-precision
4
DOUBLE(M,D) A double precision
floating-point number
that cannot be unsigned.
You can define the
display length (M) and
the number of decimals
(D).
–
1.7976931348623157E+308
to –2.2250738585072014E–
308, 0 and
2.2250738585072014E–308
to
1.7976931348623157E+308
Fractional value
floating
double-
precision and
scale
8
48. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
MySQL Data Types (Contd.)
Date and Time Types:
DATE: A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12-31.
DATETIME: A date and time combination in YYYY-MM-DD HH:MM:SS format,
between 1000-01-01 00:00:00 and 9999-12-31 23:59:59.
TIMESTAMP: A timestamp between midnight, January 1, 1970 and sometime in
2037.
TIME: Stores the time in HH:MM:SS format.
YEAR(M): Stores a year in 2-digit or 4-digit format.
49. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
MySQL Data Types (Contd.)
String Types:
CHAR(M): A fixed-length string between 1 and 255 characters in length. Defining a
length is not required, default is 1.
VARCHAR(M): A variable-length string between 1 and 255 characters in length. You
must define a length when creating a VARCHAR field.
BLOB or TEXT: A field with a maximum length of 65535 characters. Binary Large
Objects used to store large amounts of binary data, such as images or other types
of files.
TINYBLOB or TINYTEXT: A BLOB or TEXT column with a maximum length of 255
characters.
50. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
MySQL Data Types (Contd.)
MEDIUMBLOB or MEDIUMTEXT: A BLOB or TEXT column with a maximum length
of 16777215 characters.
LONGBLOB or LONGTEXT: A BLOB or TEXT column with a maximum length of
4294967295 characters.
ENUM: Creates a list of items from which the value must be selected.
51. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Introduction to DQL, DDL, DML, and DCL
DQL:
Stands for Data Query Language.
Is used to display the data in a table or tables.
Supports the SQL command, SELECT.
52. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Introduction to DQL, DDL, DML, and DCL
DDL:
Stands for Data Definition Language.
Statements are used to define the database structure or schemas.
Supports statements, such as CRATE, ALTER, DROP, TRUNCATE, COMMENT, and
RENAME.
53. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Introduction to DQL, DDL, DML, and DCL
DML:
Stands for Data Manipulation Language.
Is used for managing data within database objects.
Supports statements, such as INSERT, UPDATE, DELETE, MERGE, CALL, EXPLAIN
PLAN, and LOCK TABLE.
54. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Introduction to DQL, DDL, DML, and DCL
DCL:
Stands for Data Control Language.
Is used to create roles, permissions, and referential integrity.
Controls access to database by securing it.
Supports statements, such as GRANT and REVOKE.
55. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
DDL
Creating Database
CREATE DATABASE statement is used to create databases or schemas.
Syntax:
CREATE {DATABASE|SCHEMA} [IF NOT EXISTS] <db_name>;
Examples:
CREATE DATABASE IF NOT EXISTS Hotels_Chain;
CREATE DATABASE IF NOT EXISTS Sample_db;
56. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
DDL
Accessing Database
A database acts as a container for related database objects.
To perform any operation on a database object, you first need to access the
database.
USE statement is used to access databases or schemas.
Syntax:
USE <db_name>;
Example:
USE Hotels_Chain;
57. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
DDL
Accessing Database
SHOW DATABASES statement is used to view a list of all the databases in the
MySQL server.
Usage:
SHOW DATABASES;
Output:
58. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
DDL
Deleting Database
DROP DATABASE Statement is used to drop all the tables in the database and then,
deleting the database.
Syntax:
DROP {DATABASE|SCHEMA} [IF EXISTS] <db_name>;
Example:
DROP DATABASE IF EXISTS Sample_db;
SHOW DATABASES;
59. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
DDL
Output:
60. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
DDL (Contd.)
CREATE TABLE Statement:
Is used to create tables.
Syntax:
CREATE TABLE [IF NOT EXISTS] <table_name>
(
col1_name datatype [NOT NULL|NULL] [DEFAULT value]
[AUTO_INCREMENT] [UNIQUE] [PRIMARY KEY],
col2_name datatype [NOT NULL|NULL] [DEFAULT value]
[AUTO_INCREMENT] [UNIQUE] [PRIMARY KEY],
....
)
61. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
DDL (Contd.)
Example of CREATE TABLE Statement:
Products Table
CREATE TABLE IF NOT EXISTS Products
(
Product_ID int NOT NULL,
Product_Name varchar(45) NOT NULL,
Quantity_In_Hand int NOT NULL,
Re_Order_Quantity INT NULL,
Re_Order_Level INT NULL,
Price INT NULL
);
62. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
DDL (Contd.)
Customers Table
CREATE TABLE IF NOT EXISTS Customers
(
Customer_ID INT NOT NULL,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
Address VARCHAR(80),
City VARCHAR(30),
Postal_Code INT
);
63. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
DDL (Contd.)
Viewing Data about Tables
DESCRIBE/DESC statement is used to view the detailed data about all the columns
of the table, such as name of the column, data type, and default value.
Syntax:
DESCRIBE table_name;
or
DESC table_name;
64. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
DDL (Contd.)
For example, you can view the detailed column data of Products and Customers
table, as shown follows:
DESCRIBE Products;
Output:
65. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
DDL (Contd.)
DESC Customers;
Output:
66. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
DDL (Contd.)
Altering a Table
The structure of a table is defined while creation.
Later, you may often need to alter its structure.
ALTER TABLE is used to alter a table.
This statement can be used to add a new column, change the name or data type of
an existing column, drop a column, add or remove constraints on existing columns,
and much more.
67. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
DDL (Contd.)
Adding a Column to Table:
Use of ADD clause.
Example:
ALTER TABLE Customers ADD Gender VARCHAR(30);
You can view the structure of Customers table using DESC statement:
DESC Customers;
68. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
DDL (Contd.)
Output:
69. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
DDL (Contd.)
Changing Column Name:
Use of CHANGE COLUMN clause.
Example:
ALTER TABLE Customers CHANGE COLUMN Gender Sex
VARCHAR(30);
DESC Customers;
70. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
DDL (Contd.)
Output:
71. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
DDL (Contd.)
Dropping a Column from Table:
Use of DROP COLUMN clause.
Example:
ALTER TABLE Customers DROP COLUMN Sex;
DESC Customers;
72. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
DDL (Contd.)
Output:
73. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
DDL (Contd.)
Adding a PRIMARY KEY Constraint to Table:
Syntax:
ALTER TABLE <table_name>
ADD PRIMARY KEY(primary_key_column);
Example:
ALTER TABLE Customers ADD PRIMARY KEY (Customer_ID);
DESC Customers;
74. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
DDL (Contd.)
Output:
75. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Working with Keys
PRIMARY KEY constraint can be added to a table:
While creating the table.
After creating the table.
76. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Working with Keys
Example for adding PRIMARY KEY constraint while creation of a table:
DROP TABLE Products;
CREATE TABLE IF NOT EXISTS Products
(
Product_ID int NOT NULL,
Product_name varchar(45) NOT NULL,
Quantity_in_hand int NOT NULL,
Re_order_quantity INT NULL,
Re_order_level INT NULL,
Price INT NULL,
PRIMARY KEY(Product_ID)
);
DESC Products;
77. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Working with Keys
Output:
78. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Working with Keys (Contd.)
Example of PRIMARY Key Constraint on Multiple Columns (Composite key):
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
);
DESC Persons;
79. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Working with Keys (Contd.)
Output:
80. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Working with Keys (Contd.)
Example for dropping a PRIMARY Key Constraint:
ALTER TABLE Persons
DROP PRIMARY KEY;
DESC Persons;
Output:
81. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Working with Keys (Contd.)
FOREIGN KEY Constraint can be added to a table using :
CREATE TABLE statement
ALTER TABLE statement
82. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Working with Keys (Contd.)
Example using CREATE TABLE statement:
CREATE TABLE IF NOT EXISTS Customer_Order (
Order_ID INT NOT NULL,
Product_ID INT NOT NULL,
Customer_ID INT NOT NULL,
Quantity_Ordered INT NOT NULL,
CONSTRAINT fk1 FOREIGN KEY (Product_ID)
REFERENCES Products(Product_ID),
CONSTRAINT fk2 FOREIGN KEY (Customer_ID)
REFERENCES Customers(Customer_ID) );
DESC Customer_Order;
83. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Working with Keys (Contd.)
Output
84. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Working with Keys (Contd.)
Example to create FOREIGN KEY constraints using ALTER TABLE statement:
CREATE TABLE IF NOT EXISTS Categories (
Cat_ID INT NOT NULL PRIMARY KEY,
Cat_Name VARCHAR(50) NOT NULL,
Cat_Desc TEXT );
CREATE TABLE ProductsDemo (
PID INT NOT NULL PRIMARY KEY,
PName VARCHAR(50) NOT NULL,
PPrice DECIMAL NOT NULL,
CatID INT NOT NULL );
85. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Working with Keys (Contd.)
ALTER TABLE ProductsDemo
ADD CONSTRAINT fk_ProductsDemo
FOREIGN KEY (CatID)REFERENCES Categories(Cat_ID);
DESC ProductsDemo;
Output:
86. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Working with Keys (Contd.)
Removing a FOREIGN KEY Constraint
Syntax of ALTER statement to drop a foreign key:
ALTER TABLE table_name
DROP FOREIGN KEY constraint_name
To identify the constraint name of the foreign key the SHOW CREATE TABLE statement
can be used.
Example:
SHOW CREATE TABLE Products_Demo;
87. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Working with Keys (Contd.)
Output:
The name of the foreign key constraint in ProductsDemo table is,
fk_ProductsDemo.
88. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Working with Keys (Contd.)
Example to drop the constraint using Alter Table statement:
ALTER TABLE ProductsDemo
DROP FOREIGN KEY fk_ProductsDemo;
desc ProductsDemo;
Output:
89. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
DDL (Contd.)
DROP TABLE Statement:
Removes one or more tables including indexes and privileges.
Cannot be rolled back.
Syntax:
DROP TABLE [IF EXISTS] <table_name>
Example:
DROP TABLE IF EXISTS ProductsDemo;
90. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Truncating Table
TRUNCATE TABLE Statement:
Removes all records from a table.
Operation cannot be rolled back.
Syntax:
TRUNCATE TABLE <table_name>;
91. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
CRUD Operations with Database
INSERT Statement:
Inserts records into a table.
Syntax:
INSERT INTO <table_name> ( col1, col2,...colN )
VALUES( value1, value2,...valueN );
92. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
CRUD Operations with Database (Contd.)
Example:
INSERT INTO
Products(Product_ID,Product_Name,Quantity_in_hand,Re_or
der_quantity,Re_order_level,Price) VALUES(1,'Red Rugs
Carpets',400,500,400,800);INSERT INTO
Products(Product_ID,Product_Name,Quantity_in_hand,Re_or
der_quantity,Re_order_level,Price) VALUES(2,'Soft Silk
carpets',300,600,700,5000);INSERT INTO
Products(Product_ID,Product_Name,Quantity_in_hand,Re_or
der_quantity,Re_order_level,Price) VALUES(3,'Black Rugs
Carpets',500,400,500,7000);
Inserting data into Products table
93. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
CRUD Operations with Database (Contd.)
INSERT INTO
Products(Product_ID,Product_Name,Quantity_in_hand,Re_or
der_quantity,Re_order_level,Price) VALUES(4,'Black Silk
Sofa',100,600,700,7000);
INSERT INTO
Products(Product_ID,Product_Name,Quantity_in_hand,Re_or
der_quantity,Re_order_level,Price) VALUES(5,'Red Velvet
Sofa',120,500,700,10000);
INSERT INTO
Products(Product_ID,Product_Name,Quantity_in_hand,Re_or
der_quantity,Re_order_level,Price) VALUES(6,'Pink Rugs
Carpets',400,200,500,2000);
94. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
CRUD Operations with Database (Contd.)
INSERT INTO
Products(Product_ID,Product_Name,Quantity_in_hand,Re_order
_quantity,Re_order_level,Price) VALUES(7,'Black Silk
carpets',300,500,600,4000);INSERT INTO
Products(Product_ID,Product_Name,Quantity_in_hand,Re_order
_quantity,Re_order_level,Price) VALUES(8,'Hard Rugs
Carpets',500,600,700,5000);
INSERT INTO
Products(Product_ID,Product_Name,Quantity_in_hand,Re_order
_quantity,Re_order_level,Price) VALUES(7,'Black Silk
carpets',300,500,600,4000);
95. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
CRUD Operations with Database (Contd.)
INSERT INTO
Products(Product_ID,Product_Name,Quantity_in_hand,Re_or
der_quantity,Re_order_level,Price) VALUES(8,'Hard Rugs
Carpets',500,600,700,5000);INSERT INTO
Products(Product_ID,Product_Name,Quantity_in_hand,Re_or
der_quantity,Re_order_level,Price) VALUES(9,'Pink Silk
Sofa',100,400,500,6000);INSERT INTO
Products(Product_ID,Product_Name,Quantity_in_hand,Re_or
der_quantity,Re_order_level,Price) VALUES(10,'Black
Velvet Sofa',120,600,700,5000);
96. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
CRUD Operations with Database (Contd.)
INSERT INTO
Customers(Customer_ID,FirstName,LastName,Address,City,Post
al_Code) VALUES(1,'Peter','James','Torikatu
46','Oulu',90110);INSERT INTO
Customers(Customer_ID,FirstName,LastName,Address,City,Post
al_Code) VALUES(2,'Wellington','Importadora','rua do
Mercado 12','Resende',8737);INSERT INTO
Customers(Customer_ID,FirstName,LastName,Address,City,Post
al_Code) VALUES(3,'White','Markets','305 Ave
Suite','Resende',8737);INSERT INTO
Customers(Customer_ID,FirstName,LastName,Address,City,Post
al_Code) VALUES(4,'Andrew','Louise','67
Mercado','Resende',8737);INSERT INTO
Customers(Customer_ID,FirstName,LastName,Address,City,Post
al_Code) VALUES(5,'Harry','James','Torikatu
59','Oulu',90110);
Inserting data into Customers table
97. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
CRUD Operations with Database (Contd.)
INSERT INTO
Customers(Customer_ID,FirstName,LastName,Address,City,Postal_Code
) VALUES(6,'Wilman','Kala','Keskuskatu
45','Helsinki',21240);INSERT INTO
Customers(Customer_ID,FirstName,LastName,Address,City,Postal_Code
) VALUES(7,'Wolski','Zbyszek','ul. Filtrowa
68','Poland',1012);INSERT INTO
Customers(Customer_ID,FirstName,LastName,Address,City,Postal_Code
) VALUES(8,'Andy','James','607 Ave Suite','Poland',1012);INSERT
INTO
Customers(Customer_ID,FirstName,LastName,Address,City,Postal_Code
) VALUES(9,'Nisha','Mathew','407 ','Resende',8737);INSERT INTO
Customers(Customer_ID,FirstName,LastName,Address,City,Postal_Code
) VALUES(10,'Harry','James','Torikatu 79','Helsinki',21240);
98. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
CRUD Operations with Database (Contd.)
Insert into customer_order
(Order_ID,Product_ID,Customer_ID,Quantity_Ordered)
values(1,1,1,10);Insert into customer_order
(Order_ID,Product_ID,Customer_ID,Quantity_Ordered)
values(2,1,1,20);Insert into customer_order
(Order_ID,Product_ID,Customer_ID,Quantity_Ordered)
values(3,2,1,10);Insert into customer_order
(Order_ID,Product_ID,Customer_ID,Quantity_Ordered)
values(4,2,2,30);Insert into customer_order
(Order_ID,Product_ID,Customer_ID,Quantity_Ordered)
values(5,3,2,10);
Inserting data into Customer_Order table
99. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
CRUD Operations with Database (Contd.)
Insert into customer_order
(Order_ID,Product_ID,Customer_ID,Quantity_Ordered)
values(6,3,3,50);Insert into customer_order
(Order_ID,Product_ID,Customer_ID,Quantity_Ordered)
values(7,4,3,60);Insert into customer_order
(Order_ID,Product_ID,Customer_ID,Quantity_Ordered)
values(8,4,4,70);Insert into customer_order
(Order_ID,Product_ID,Customer_ID,Quantity_Ordered)
values(9,5,4,80);Insert into customer_order
(Order_ID,Product_ID,Customer_ID,Quantity_Ordered)
values(10,5,5,60);
100. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
SelectionProjection
Table 1 Table 2
Table 1Table 1
Join
CRUD Operations with Database (Contd.)
Capabilities of SELECT Statement
101. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
CRUD Operations with Database (Contd.)
SELECT Statement:
Can fetch records from a one or more tables at a time.
Uses any condition with WHERE clause.
Syntax:
SELECT field1, field2,...fieldN table_name1,
table_name2...
[WHERE Clause]
[LIMIT N]
LIMIT attribute can limit the number of returned records.
102. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
CRUD Operations with Database (Contd.)
Example 1: Retrieving all the records from Products table.
select * from Products;
Output:
103. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
CRUD Operations with Database (Contd.)
Example 2: Retrieving details of the product having ID as 1.
select * from products where Product_ID=1;
Output:
104. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
CRUD Operations with Database (Contd.)
Example 3: Retrieving details of Black Velvet Sofa.
select * from products where Product_name='Black Velvet
Sofa';
Output:
105. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
CRUD Operations with Database (Contd.)
Example 4: Retrieving price of Black Velvet Sofa.
select Product_ID,Product_name,Price from products where
Product_name='Black Velvet Sofa';
Output:
106. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
CRUD Operations with Database (Contd.)
Example 5: Retrieving all records of Customers table.
select * from Customers;
Output:
107. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
CRUD Operations with Database (Contd.)
Example 6: Retrieving details of customers residing in Poland.
select * from customers where city='Poland';
Output:
108. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
CRUD Operations with Database (Contd.)
UPDATE Statement:
Can update one or more field altogether.
Can specify any condition using WHERE clause.
Can update values in a single table at a time.
Syntax:
UPDATE <table_name> SET col1=new_value1,
col2=new_value2
[WHERE Clause]
109. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
CRUD Operations with Database (Contd.)
Example 1: Updating price of Black Silk Sofa to 9000.
UPDATE Products
SET Price=9000
WHERE Product_name='Black Silk Sofa';
select * from products WHERE Product_name='Black Silk Sofa';
Output:
110. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
CRUD Operations with Database (Contd.)
Example 2: Updating address of Andrew Louise to 56 Ave Suite.
update customers
set Address='56 Ave Suite'
where firstname='Andrew' and lastname='louise';
select * from customers
where firstname='Andrew' and lastname='louise';
Output:
111. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
CRUD Operations with Database (Contd.)
DELETE FROM Statement:
Deletes records from a table.
Can specify any condition using WHERE clause.
Can delete records from a single table at a time.
If no WHERE condition is specified, all rows will be removed. After performing a DELETE
operation you need to COMMIT or ROLLBACK the transaction to make the change
permanent or to undo it.
Syntax:
DELETE FROM <table_name>
[WHERE Clause]
112. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
CRUD Operations with Database (Contd.)
Example: Removing record for the customer with ID “7”.
DELETE FROM Customers WHERE Customer_ID=7;
select * from customers;
Output:
113. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Aggregate Functions
MySQL supports various aggregate functions. Some of these are:
Function Description Example
AVG() Returns the average value of the
argument.
SELECT AVG(Price)
average_buy_price
FROM products;
COUNT() Returns a count of the number of rows
returned.
SELECT COUNT(*) AS Total
FROM products;
MAX() Returns the maximum value in a set of
values.
SELECT MAX(Price)
highest_price
FROM Products;
114. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Aggregate Functions (Contd.)
Function Description Example
MIN() Returns the minimum value in a set of
values.
SELECT MIN(Price)
lowest_price
FROM Products;
SUM() Returns the sum of a set of values.. SELECT sum(10+20+30)
DemoSum;
CONCAT() Returns the concatenated string. SELECT concat('James','
Peter') Name;
115. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Aggregate Functions (Contd.)
GROUP BY Clause:
Is used with the SELECT statement to group rows into subgroups by the one or
more values of columns or expressions.
Can be used with aggregate functions to provide means of grouping the result
dataset by certain database table column(s).
116. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Aggregate Functions (Contd.)
Example 1: Retrieving the cities and total number of customers belonging to those
cities and having IDs less than 8.
select Count(Customer_ID) Total_Customers,City from Customers
Group by city;
Output:
117. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Aggregate Functions (Contd.)
Example 2: Retrieving total quantities ordered for different products.
select Product_ID, sum(Quantity_Ordered) from customer_order
group by Product_ID;
Output:
118. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Aggregate Functions (Contd.)
ORDER BY Clause:
Is used to sort the records in result set either in ascending or descending order .
Syntax:
SELECT expressions
FROM tables
WHERE conditions
ORDER BY expression [ ASC | DESC ];
119. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Aggregate Functions (Contd.)
Example: Display full customer names in ascending order.
select Customer_ID, concat(FirstName,' ',LastName) Customer_Name
from customers order by Customer_Name ASC;
Output:
120. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Aggregate Functions (Contd.)
HAVING Clause is used in the SELECT statement to specify filter conditions for
group of rows or aggregates.
Example: Retrieving total quantities ordered for different products where total
quantities order for each product is less than 100.
select Product_ID, sum(Quantity_Ordered) TotalQuantityoOrdered
from customer_order group by Product_ID having
TotalQuantityoOrdered<100;
121. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Aggregate Functions (Contd.)
Output:
122. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Aggregate Functions (Contd.)
LIKE Clause:
Is used to search for a specified pattern in a column.
Uses % sign to define wildcards (missing letters) both before and after the pattern.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;
123. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Aggregate Functions (Contd.)
Example 1: Retrieving products those contain the word “Silk” in names.
SELECT Product_ID,Product_name FROM products WHERE
Product_name LIKE '%Silk%';
Output:
124. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Aggregate Functions (Contd.)
Example 2: Retrieving customers whose names start with alphabet w.
SELECT Customer_ID,FirstName FROM customers WHERE
FirstName LIKE 'w%';
Output:
125. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Joins in MySQL
Joins are used to combine the data from two tables, with the result being a new,
temporary table.
Joins are performed based on something called a predicate, which specifies the
condition to use in order to perform a join.
126. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Joins in MySQL (Contd.)
Join types:
o Outer Join:
• Left Outer Join
• Right Outer Join
o Inner Join
o Self Join
127. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Joins in MySQL (Contd.)
Lets take two tables to understand joins:
Employee Location
128. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Joins in MySQL (Contd.)
Left Outer Join:
Retains all of the rows of the left table, regardless of whether there is a row that
matches on the right table.
Example:
SELECT * FROM employee LEFT OUTER JOIN location
ON employee.empID = location.empID;
129. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Joins in MySQL (Contd.)
Output:
130. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Joins in MySQL (Contd.)
Right Outer Join:
Retains all of the rows of the right table, regardless of whether there is a row that
matches on the left table.
Example:
SELECT * FROM employee RIGHT OUTER JOIN location
ON employee.empID = location.empID;
131. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Joins in MySQL (Contd.)
Output:
132. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Joins in MySQL (Contd.)
Inner Join:
Returns only the rows that actually match based on the join predicate.
Example:
SELECT * FROM employee INNER JOIN location ON
employee.empID = location.empID;
133. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Joins in MySQL (Contd.)
Output:
134. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Joins in MySQL (Contd.)
Self Join:
Uses a different alias for same table.
Used to compare records within one table.
Treats one table as two separate tables by using alias.
135. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Joins in MySQL (Contd.)
Example: Retrieving names of the customers who stay in the city in which customer
named White stays.
SELECT c1.FirstName
FROM customers c1, customers c2
WHERE c1.city = c2.City AND c2.FirstName='White';
136. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Joins in MySQL (Contd.)
Output:
137. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Nested Queries
A MySQL subquery is a query that is nested inside another query, such
as SELECT, INSERT, UPDATE or DELETE.
A subquery returns values that are used to execute an outer query. A subquery can
return one or more values.
If a subquery returns a single value, you can use comparison operators to compare it
with the expression in the WHERE clause.
If a subquery returns multiple values, the following keywords can be used to cater the
requirements:
IN or Not IN
EXISTS or NOT EXISTS
138. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Nested Queries (Contd.)
Example 1: Displaying the customer ID, first name, and last name of the customer
whose order ID is 1.
SELECT Customer_ID, FirstName, LastName Inner Query
FROM Customers
WHERE Customer_ID= (SELECT Customer_Order.Customer_iD FROM
Customer_Order WHERE Order_ID=1);
Outer Query
139. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Nested Queries (Contd.)
Output:
140. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Nested Queries (Contd.)
Example 2: Retrieving order ID, product ID, customer ID, price of each product, and
total amount for each order.
Select Order_ID, Product_ID, Customer_ID,
(select price from products where
products.product_ID=customer_order.Product_ID)Price,
Quantity_Ordered,
(Quantity_Ordered*(select price from products where
products.product_ID=customer_order.Product_ID)) Amount
from customer_order;
141. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Nested Queries (Contd.)
The output of the preceding query will be:
142. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Nested Queries (Contd.)
Example 3: Retrieving product name and price records of the products that have an
above average price:
SELECT Product_Name, Price FROM ProductsWHERE
Price>(SELECT AVG(Price) FROM Products);
143. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Nested Queries (Contd.)
The output of the preceding query will be:
144. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Security and Privileges (Contd.)
MySQL ensures security by allowing authorized users to access the database.
MySQL provides various commands to create and delete user accounts.
Creating Users:
The CREATE USER statement is used to create MySQL accounts for users.
Syntax:
CREATE USER user_specification IDENTIFIED BY password;
Example:
CREATE USER'smithj'@'localhost' IDENTIFIED BY 'smith123';
145. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Security and Privileges (Contd.)
Verify the creation of user accounts using the following query:
SELECT * FROM mysql.user;
Output:
146. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Security and Privileges (Contd.)
Renaming a user account:
Using the RENAME USER statement.
Syntax:
RENAME USER old_account_name TO new_account_name;
Example:
RENAME USER 'smithj'@'localhost' TO
'smith_louise'@'localhost';
SELECT * FROM mysql.user;
147. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Security and Privileges (Contd.)
Output:
148. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Security and Privileges (Contd.)
Changing user account password :
Using the SET PASSWORD statement.
Syntax:
SET PASSWORD [FOR account_name]=
{
PASSWORD('text_password')
|'encrypted_password'
}
Example:
SET PASSWORD FOR 'smith_louise'@'localhost'
=PASSWORD('pwd_smith_l_123');
SELECT * FROM mysql.user;
149. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Security and Privileges (Contd.)
Output:
150. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Security and Privileges (Contd.)
GRANT Statement:
Grants users various privileges to database objects to ensure security.
Syntax:
GRANT privileges ON object TO user;
151. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Security and Privileges (Contd.)
Privileges can be of following types:
Privilege Description
SELECT
Ability to perform SELECT statements on
the table.
INSERT
Ability to perform INSERT statements on
the table.
UPDATE
Ability to perform UPDATE statements
on the table.
DELETE
Ability to perform DELETE statements
on the table.
INDEX
Ability to create an index on an existing
table.
152. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Security and Privileges (Contd.)
Privilege Description
CREATE
Ability to perform CREATE TABLE
statements.
ALTER
Ability to perform ALTER TABLE
statements to change the table
definition.
DROP
Ability to perform DROP TABLE
statements.
ALL
Grants all permissions except GRANT
OPTION.
153. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Security and Privileges (Contd.)
In the syntax, object specifies the name of the database object that you are
granting permissions for. It can be a table, a function, or a stored procedure.
In the case of granting privileges on a table, this would be the table name.
User specifies the name of the user who will be granted specified privileges.
Viewing grant information:
SHOW GRANTS statement can be used. T
Syntax:
SHOW GRANTS FOR account_name;
154. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Security and Privileges (Contd.)
Example 1:
GRANT SELECT, INSERT, UPDATE, DELETE ON hotels_chain.* TO
'smith_louise'@'localhost';
SHOW GRANTS FOR 'smith_louise'@'localhost';
Output:
155. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Security and Privileges (Contd.)
Example 2:
GRANT ALL ON *.* TO 'smith_louise'@'localhost';
The above example grants all permissions on all databases to the user
account, smithj@localhost.
SHOW GRANTS FOR 'smith_louise'@'localhost';
Output:
156. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Security and Privileges (Contd.)
REVOKE Statement:
Revokes privileges from users to ensure security.
Syntax:
REVOKE privileges ON object FROM user;
157. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Security and Privileges (Contd.)
Example:
REVOKE ALL ON *.* FROM 'smith_louise'@'localhost';
SHOW GRANTS FOR 'smith_louise'@'localhost';
Output:
158. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Security and Privileges (Contd.)
Deleting Users:
The DROP USER statement is used to delete MySQL user accounts.
Syntax:
DROP USER user_specification;
Example:
DROP USER 'smith_louise'@'localhost';
SELECT * FROM mysql.user;
159. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Security and Privileges (Contd.)
Output:
160. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Security and Privileges (Contd.)
Transaction:
Is a logical unit of work requested by a user to be applied to the database objects.
Groups one or more SQL statements into a single logical unit.
Works on tables that use transaction-safe storage engines, like InnoDB and BDB.
Syntax for creating a transaction:
START TRANSACTION;
Statements
COMMIT|ROLLBACK;
161. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Security and Privileges (Contd.)
Running the COMMIT command will explicitly end the current transaction. Changes will
be committed.
Running the ROLLBACK command will explicitly end the current transaction. Changes
will be rolled back.
Example:
START TRANSACTION;
INSERT INTO Products VALUES(11,'Red Soft
Carpets',500,300,400,4000);
COMMIT;
select * from products;
162. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Security and Privileges (Contd.)
Output:
163. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Security and Privileges (Contd.)
SAVEPOINT Statement:
Sets a named transaction savepoint with a name of identifier. If the current
transaction has a savepoint with the same name, the old savepoint is deleted and a
new one is set.
Syntax:
SAVEPOINT identifier
164. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Security and Privileges (Contd.)
ROLLBACK TO SAVEPOINT Statement:
Rolls back a transaction to the named savepoint without terminating the
transaction.
Syntax:
ROLLBACK TO [SAVEPOINT] identifier
165. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Security and Privileges (Contd.)
Example:
START TRANSACTION;
INSERT INTO Customers VALUES(11,'Paul','Symonds','Bin Day -23,4','Texas ',9902345);
INSERT INTO Customer_Order VALUES(14,1,5,5);
SAVEPOINT sav1;
INSERT INTO Customers VALUES(12,'Ren','Dreamer', 'Green Street-97,3','LA', 8802399);
INSERT INTO Customer_Order VALUES(15,10,10,3);
ROLLBACK TO SAVEPOINT sav1;
INSERT INTO Customers VALUES(13,'Jen', 'Dreamer','Green Street-97,3','LA',8802399);
insert into Customer_Order values(16,1,6,3);
COMMIT;
166. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Controlling Transactions
SAVEPOINT B
SAVEPOINT A
DELETE
INSERT
UPDATE
INSERT
COMMITTime
Transaction
ROLLBACK
to SAVEPOINT B
ROLLBACK
to SAVEPOINT A
ROLLBACK
167. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Quiz
1. Which model organizes data in a tree structure?
Ans Hierarchical model
168. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Quiz (Contd.)
2. What does symbol represents in an ER
diagram?
Ans Entity
169. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Quiz (Contd.)
3. Which language has statements, such as CRATE, ALTER, DROP,
TRUNCATE, COMMENT, and RENAME?
Ans DDL
170. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Quiz (Contd.)
4. Which command removes tables including indexes and privileges
and cannot be rolled back?
Ans DROP TABLE Statement
171. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Quiz (Contd.)
5. Which command explicitly ends the current transaction without
saving the changes made to the database?
Ans ROLLBACK
172. Case Study
• Mike is a database programmer. He needs to save the following
details about the employees working for an organization in the
Employee database:
• Employee ID
• Employee Name
• Employee Category and
• Basic Salary
• In addition, Mike also needs to store the names of various
departments belonging to the organization in the database while
ensuring that every department is identified by using a unique ID. He
also needs to ensure that there is minimal data redundancy.
173. Case Study (Contd.)
• Question 1
• How can Mike ensure that he creates the required table/s inside the
Employee database only?
174. Case Study (Contd.)
• Solution 1:
• Before writing any Create Table statement, Mike should activate the
Employee database by using the use statement.
• Use employee;
175. Case Study (Contd.)
• Question 2
• Mike has decided to create the Emp_Details table with the following fields to store
the employee details:
• Dept_No int
• Dept_Name varchar
• Emp_ID int
• Emp_Name varchar
• Emp_Category varchar
• Basic_Sal int
• The Basic_Sal depends on the Emp_Category, which has only I, II, or III as its allowed
values. The Basic_Sal for employees of category, I, II, and III is 25000, 18000, and
12000, respectively.
• Analyse the preceding scenario and determine if the table structure proposed by
Mike is appropriate or not. If not, suggest reasons for the same and the technique
that should be implemented to resolve the problems with the table.
176. Case Study (Contd.)
• Solution 2
• The table structure is not appropriate. The table is not normalized which will
result in redundancy of data. For example, if there are 10 employees working
in the Sales department, for every record inserted in the table, Dept_No and
Dept_Name will be inserted again and again.
177. Case Study (Contd.)
• Question 3
• Consider the preceding Emp_Details table. Identify the primary key in the
table. Write the SQL statement that Mike should use to create the table and
also define the primary key in the table.
178. Case Study (Contd.)
• Solution 3
• Mike should create a composite primary key on the columns, Dept_No and
Emp_ID
• Create table Emp_Details(Dept_No int, Dept_Name
varchar(20),Emp_ID int, Emp_Name varchar(30),Emp_Category
varchar(5),Basic_Sal int, primary key(Dept_No , Emp_ID)
179. Case Study (Contd.)
• Question 4
• Analyse the Emp_Details table and identify its current normal form. Also
provide the reason for the same.
180. Case Study (Contd.)
• Solution 4
• The table is in 1NF, because all the non key attributes do not depend on the
entire primary key. If Dept_No and Emp_ID make up the primary key in the
table, all the remaining fields should depend on the entire primary key. But
Dept_Name depends only on Dept_No, which is a part of the primary key ,
thus table is not in 2NF.
181. Case Study (Contd.)
• Question 5
• To attain normalization, Mike has decided to split the Emp_Details table into
the following tables:
• Emp_Department (Dept_No, Emp_ID)
• Employee (Emp_ID, Emp_Name, Emp_Category)
• Department (Dept_No, Dept_Name)
• Wages(Emp_Category, Basic_Sal)
• Identify the primary keys in all the preceding tables. Write the SQL statements
for creating the preceding tables and define the primary keys in all the tables.
182. Case Study (Contd.)
• Solution 5
• create table emp_department(Dept_No int, Emp_ID int, primary
key(D_No,E_ID);
• create table employee(Emp_ID int primary key,
• Emp_Name varchar(20),Emp_Category varchar(5));
• create table department(Dept_No int primary key,Dept_Name varchar(30));
• create table Wages(Emp_Category varchar(4) primary key,Basic_Sal int);
183. Case Study (Contd.)
• Question 6
• Mike needs to define a relationship between the Employee table and Wages
table. Identify the field on the basis of which this relationship can be defined.
In addition, identify the parent and the child table in the relationship. Write
the SQL statement to create the relationship between these tables.
184. Case Study (Contd.)
• Solution
• A relationship can be defined between the tables by using a foreign key. This
relationship can be defined between the tables on the basis of the common
column, Emp_Category. Wages is the parent table and Employee is the child
table.
• create table employee(Emp_ID int primary key,
• Emp_Name varchar(20),Emp_Category varchar(5),
• Foreign key(Emp_Category) references Wages(Emp_Category))Engine=InnoDB
;
185. Case Study (Contd.)
• Question 7
• Write the SQL statements to insert the records in the Wages table as specified
in the preceding scenario.
187. Case Study (Contd.)
• Question 8
• The Employee table contains the following records inside it:
• Write the SQL statement to update the Emp_Category of Vanya to I.
Emp_ID Emp_Name Emp_Categor
y
101 Sam I
102 Peter I
89 Sammy III
78 Vanya II
189. Case Study (Contd.)
• Question 9
• Mike needs to retrieve and display the Emp_ID, Emp_Name, Emp_Category,
and Wages of all the employees. Write the SQL statement that he needs to
use for the same.
190. Case Study (Contd.)
• Solution 9
• select Emp_ID, Emp_Name, Employee.Emp_Category, Basic_Sal from
Employee Join Wages
on Employee.Emp_Category=Wages.Emp_Category;
191. Case Study (Contd.)
• Question 10
• Write the SQL statement to remove the record for Employee with ID 78 from
the Employee table.
193. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Summary
In the session learned that:
Database models defines the logical structure of a database is modeled.
Some of the types of Database Models are:
Hierarchical model
Network model
Relational model
Object-oriented model
194. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Summary (Contd.)
RDBMS is a database management system represents data in terms of tuples(rows)
and is used to manage relational databases.
Database normalization is to restructure the logical data model of a database to:
Eliminate redundancy
Organize data efficiently
Reduce the potential for data anomalies
ER Diagrams represent conceptual level of a database system.
195. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Summary (Contd.)
MySQL uses many different data types broken into three categories:
Numeric
Date and time
String
CREATE TABLE statement is used to create tables.
ALTER TABLE statement changes the structure of an existing table.
DROP TABLE statement removes one or more tables including indexes and
privileges.
196. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Summary (Contd.)
INSERT statement inserts records into a table.
UPDATE statement can update one or more field altogether.
DELETE FROM statement deletes records from a table.
SELECT statement can fetch records from a one or more tables at a time.
Joins are used to combine the data from two tables, with the result being a new,
temporary table.
The CREATE USER statement is used to create MySQL accounts for users.
197. © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Summary (Contd.)
The DROP USER statement is used to delete MySQL user accounts.
GRANT Statement grants users various privileges to database objects to ensure
security.
REVOKE Statement revokes privileges from users to ensure security.
Transaction is a logical unit of work requested by a user to be applied to the
database objects.