SlideShare a Scribd company logo
1 of 197
Download to read offline
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
© 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.
© 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.
© 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
© 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.
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Overview of Database Models (Contd.)
Example of Hierarchical Model:
© 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.
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Overview of Database Models (Contd.)
Example of Network Model:
© 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.
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Overview of Database Models (Contd.)
Example of Relational Model:
© 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.
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Overview of Database Models (Contd.)
Example of Object-Oriented Model :
Employee
Name
ID
Salary
© 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.
© 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.
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Keys
Example of Candidate Key:
© 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.
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Keys (Contd.)
Example of Primary Key:
© 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.
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Keys (Contd.)
Example of Foreign Key:
© 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.
© 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.
© 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
© 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:
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Normalization (Contd.)
 Transitive Dependency: When a non-key attribute determines another non-key
attribute.
 Example:
© 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)
© 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.
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Normalization (Contd.)
Example of 1NF:
The Student Table
© 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.
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Normalization (Contd.)
Example of 2NF:
New Student Table
New Subject Table
© 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.
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Normalization (Contd.)
Example of 3NF:
Student_Detail Table
New Student_Detail Table
Address Table
© 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)
© 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.
© 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.
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
ER Diagrams (Contd.)
Symbols and Notations:
Symbols Notations
Entity
Relationship
Attribute
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
ER Diagrams (Contd.)
Symbols Notations
Weak Entity
Weak Entity Relationship
Multivalued Attribute
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
ER Diagrams (Contd.)
Symbols Notations
Key Attribute
Composite Attribute
© 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.
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
ER Diagrams (Contd.)
Binary relationship is further divided into three types:
1. One-to-one
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
ER Diagrams (Contd.)
2. One-to-many
3. Many-to-one
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
ER Diagrams (Contd.)
An ER Diagram:
© 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.
© 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.
© 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
© 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
© 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
© 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
© 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.
© 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.
© 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.
© 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.
© 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.
© 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.
© 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.
© 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;
© 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;
© 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:
© 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;
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
DDL
 Output:
© 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],
....
)
© 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
);
© 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
);
© 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;
© 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:
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
DDL (Contd.)
DESC Customers;
 Output:
© 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.
© 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;
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
DDL (Contd.)
 Output:
© 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;
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
DDL (Contd.)
 Output:
© 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;
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
DDL (Contd.)
 Output:
© 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;
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
DDL (Contd.)
Output:
© 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.
© 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;
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Working with Keys
Output:
© 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;
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Working with Keys (Contd.)
 Output:
© 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:
© 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
© 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;
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Working with Keys (Contd.)
 Output
© 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 );
© 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:
© 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;
© 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.
© 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:
© 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;
© 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>;
© 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 );
© 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
© 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);
© 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);
© 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);
© 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
© 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);
© 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
© 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);
© 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
© 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.
© 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:
© 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:
© 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:
© 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:
© 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:
© 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:
© 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]
© 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:
© 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:
© 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]
© 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:
© 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;
© 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;
© 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).
© 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:
© 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:
© 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 ];
© 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:
© 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;
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Aggregate Functions (Contd.)
Output:
© 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;
© 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:
© 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:
© 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.
© 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
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Joins in MySQL (Contd.)
 Lets take two tables to understand joins:
Employee Location
© 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;
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Joins in MySQL (Contd.)
 Output:
© 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;
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Joins in MySQL (Contd.)
 Output:
© 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;
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Joins in MySQL (Contd.)
 Output:
© 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.
© 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';
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Joins in MySQL (Contd.)
 Output:
© 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
© 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
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Nested Queries (Contd.)
Output:
© 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;
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Nested Queries (Contd.)
 The output of the preceding query will be:
© 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);
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Nested Queries (Contd.)
 The output of the preceding query will be:
© 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';
© 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:
© 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;
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Security and Privileges (Contd.)
Output:
© 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;
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Security and Privileges (Contd.)
Output:
© 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;
© 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.
© 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.
© 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;
© 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:
© 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:
© 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;
© 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:
© 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;
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Security and Privileges (Contd.)
 Output:
© 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;
© 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;
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Database Security and Privileges (Contd.)
 Output:
© 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
© 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
© 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;
© 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
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Quiz
1. Which model organizes data in a tree structure?
Ans Hierarchical model
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
Quiz (Contd.)
2. What does symbol represents in an ER
diagram?
Ans Entity
© 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
© 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
© 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
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.
Case Study (Contd.)
• Question 1
• How can Mike ensure that he creates the required table/s inside the
Employee database only?
Case Study (Contd.)
• Solution 1:
• Before writing any Create Table statement, Mike should activate the
Employee database by using the use statement.
• Use employee;
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.
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.
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.
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)
Case Study (Contd.)
• Question 4
• Analyse the Emp_Details table and identify its current normal form. Also
provide the reason for the same.
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.
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.
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);
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.
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
;
Case Study (Contd.)
• Question 7
• Write the SQL statements to insert the records in the Wages table as specified
in the preceding scenario.
Case Study (Contd.)
• Solution
• insert into Wages values('I',25000),('II',18000),('III',12000);
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
Case Study (Contd.)
• Solution 8
• Update Employee set Emp_cateory=’I’ where Emp_ID=78;
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.
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;
Case Study (Contd.)
• Question 10
• Write the SQL statement to remove the record for Employee with ID 78 from
the Employee table.
Case Study (Contd.)
• Solution 10
• Delete from Employee where Emp_ID=78;
© 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
© 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.
© 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.
© 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.
© 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.

More Related Content

What's hot

DBMS VIVA QUESTIONS_CODERS LODGE.pdf
DBMS VIVA QUESTIONS_CODERS LODGE.pdfDBMS VIVA QUESTIONS_CODERS LODGE.pdf
DBMS VIVA QUESTIONS_CODERS LODGE.pdfnofakeNews
 
Relational Database Fundamentals
Relational Database FundamentalsRelational Database Fundamentals
Relational Database FundamentalsKHALID C
 
physical and logical data independence
physical and logical data independencephysical and logical data independence
physical and logical data independenceapoorva_upadhyay
 
Normalization
NormalizationNormalization
Normalizationochesing
 
08. Object Oriented Database in DBMS
08. Object Oriented Database in DBMS08. Object Oriented Database in DBMS
08. Object Oriented Database in DBMSkoolkampus
 
Entity linking with a knowledge base issues,
Entity linking with a knowledge base issues,Entity linking with a knowledge base issues,
Entity linking with a knowledge base issues,Nexgen Technology
 
Islamic University Previous Year Question Solution 2019 (ADBMS)
Islamic University Previous Year Question Solution 2019 (ADBMS)Islamic University Previous Year Question Solution 2019 (ADBMS)
Islamic University Previous Year Question Solution 2019 (ADBMS)Rakibul Hasan Pranto
 
Chapter 7 relation database language
Chapter 7 relation database languageChapter 7 relation database language
Chapter 7 relation database languageJafar Nesargi
 
Unit 4 rdbms study_material
Unit 4  rdbms study_materialUnit 4  rdbms study_material
Unit 4 rdbms study_materialgayaramesh
 
The three level of data modeling
The three level of data modelingThe three level of data modeling
The three level of data modelingsharmila_yusof
 
Module 5 oodb systems semantic db systems
Module 5 oodb systems  semantic db systemsModule 5 oodb systems  semantic db systems
Module 5 oodb systems semantic db systemsTaher Barodawala
 
Databases and SQL - Lecture B
Databases and SQL - Lecture BDatabases and SQL - Lecture B
Databases and SQL - Lecture BCMDLearning
 

What's hot (20)

DBMS VIVA QUESTIONS_CODERS LODGE.pdf
DBMS VIVA QUESTIONS_CODERS LODGE.pdfDBMS VIVA QUESTIONS_CODERS LODGE.pdf
DBMS VIVA QUESTIONS_CODERS LODGE.pdf
 
Keerty rdbms sql
Keerty rdbms sqlKeerty rdbms sql
Keerty rdbms sql
 
RDMS AND SQL
RDMS AND SQLRDMS AND SQL
RDMS AND SQL
 
Relational Database Fundamentals
Relational Database FundamentalsRelational Database Fundamentals
Relational Database Fundamentals
 
physical and logical data independence
physical and logical data independencephysical and logical data independence
physical and logical data independence
 
Normalization
NormalizationNormalization
Normalization
 
08. Object Oriented Database in DBMS
08. Object Oriented Database in DBMS08. Object Oriented Database in DBMS
08. Object Oriented Database in DBMS
 
Fundamentals of Data Modeling and Database Design by Dr. Kamal Gulati
Fundamentals of Data Modeling and Database Design by Dr. Kamal GulatiFundamentals of Data Modeling and Database Design by Dr. Kamal Gulati
Fundamentals of Data Modeling and Database Design by Dr. Kamal Gulati
 
Entity linking with a knowledge base issues,
Entity linking with a knowledge base issues,Entity linking with a knowledge base issues,
Entity linking with a knowledge base issues,
 
Islamic University Previous Year Question Solution 2019 (ADBMS)
Islamic University Previous Year Question Solution 2019 (ADBMS)Islamic University Previous Year Question Solution 2019 (ADBMS)
Islamic University Previous Year Question Solution 2019 (ADBMS)
 
Chapter 7 relation database language
Chapter 7 relation database languageChapter 7 relation database language
Chapter 7 relation database language
 
Unit 4 rdbms study_material
Unit 4  rdbms study_materialUnit 4  rdbms study_material
Unit 4 rdbms study_material
 
The three level of data modeling
The three level of data modelingThe three level of data modeling
The three level of data modeling
 
RDBMS_Unit 01
RDBMS_Unit 01RDBMS_Unit 01
RDBMS_Unit 01
 
Types of keys in database management system by Dr. Kamal Gulati
Types of keys in database management system by Dr. Kamal GulatiTypes of keys in database management system by Dr. Kamal Gulati
Types of keys in database management system by Dr. Kamal Gulati
 
Module 5 oodb systems semantic db systems
Module 5 oodb systems  semantic db systemsModule 5 oodb systems  semantic db systems
Module 5 oodb systems semantic db systems
 
Dbms ppt
Dbms pptDbms ppt
Dbms ppt
 
Object oriented data model
Object oriented data modelObject oriented data model
Object oriented data model
 
Bt0066 dbms
Bt0066 dbmsBt0066 dbms
Bt0066 dbms
 
Databases and SQL - Lecture B
Databases and SQL - Lecture BDatabases and SQL - Lecture B
Databases and SQL - Lecture B
 

Viewers also liked (20)

JSP Technology II
JSP Technology IIJSP Technology II
JSP Technology II
 
Final Table of Content
Final Table of ContentFinal Table of Content
Final Table of Content
 
Java Day-6
Java Day-6Java Day-6
Java Day-6
 
Agile Dev. I
Agile Dev. IAgile Dev. I
Agile Dev. I
 
MongoDB Session 2
MongoDB Session 2MongoDB Session 2
MongoDB Session 2
 
Hibernate III
Hibernate IIIHibernate III
Hibernate III
 
Java Day-2
Java Day-2Java Day-2
Java Day-2
 
Working with Servlets
Working with ServletsWorking with Servlets
Working with Servlets
 
MongoDB Session 1
MongoDB Session 1MongoDB Session 1
MongoDB Session 1
 
Android - Day 2
Android - Day 2Android - Day 2
Android - Day 2
 
Agile Dev. II
Agile Dev. IIAgile Dev. II
Agile Dev. II
 
Identifing Listeners and Filters
Identifing Listeners and FiltersIdentifing Listeners and Filters
Identifing Listeners and Filters
 
Java Day-4
Java Day-4Java Day-4
Java Day-4
 
Java Day-7
Java Day-7Java Day-7
Java Day-7
 
JSP Technology I
JSP Technology IJSP Technology I
JSP Technology I
 
Spring Framework-II
Spring Framework-IISpring Framework-II
Spring Framework-II
 
Exploring Maven SVN GIT
Exploring Maven SVN GITExploring Maven SVN GIT
Exploring Maven SVN GIT
 
Hibernate I
Hibernate IHibernate I
Hibernate I
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Basic Hibernate Final
Basic Hibernate FinalBasic Hibernate Final
Basic Hibernate Final
 

Similar to RDBMS with MySQL

Similar to RDBMS with MySQL (20)

Database Concepts
Database ConceptsDatabase Concepts
Database Concepts
 
Sql interview questions and answers
Sql interview questions and  answersSql interview questions and  answers
Sql interview questions and answers
 
Unit 2 DBMS.pptx
Unit 2 DBMS.pptxUnit 2 DBMS.pptx
Unit 2 DBMS.pptx
 
Database Concepts & SQL(1).pdf
Database Concepts & SQL(1).pdfDatabase Concepts & SQL(1).pdf
Database Concepts & SQL(1).pdf
 
Bca examination 2015 dbms
Bca examination 2015 dbmsBca examination 2015 dbms
Bca examination 2015 dbms
 
Codds rules & keys
Codds rules & keysCodds rules & keys
Codds rules & keys
 
Database Systems - introduction
Database Systems - introductionDatabase Systems - introduction
Database Systems - introduction
 
Dbms 9: Relational Model
Dbms 9: Relational ModelDbms 9: Relational Model
Dbms 9: Relational Model
 
Relational Database Management System part II
Relational Database Management System part IIRelational Database Management System part II
Relational Database Management System part II
 
object oriented analysis data.pptx
object oriented analysis data.pptxobject oriented analysis data.pptx
object oriented analysis data.pptx
 
RDBMS
RDBMSRDBMS
RDBMS
 
Database management systems
Database management systemsDatabase management systems
Database management systems
 
introduction of database in DBMS
introduction of database in DBMSintroduction of database in DBMS
introduction of database in DBMS
 
Database Management System, Lecture-1
Database Management System, Lecture-1Database Management System, Lecture-1
Database Management System, Lecture-1
 
Data models
Data modelsData models
Data models
 
Data models
Data modelsData models
Data models
 
DATA BASE MODEL Rohini
DATA BASE MODEL RohiniDATA BASE MODEL Rohini
DATA BASE MODEL Rohini
 
Cse ii ii sem
Cse ii ii semCse ii ii sem
Cse ii ii sem
 
Relational Database.pptx
Relational Database.pptxRelational Database.pptx
Relational Database.pptx
 
Week 1
Week 1Week 1
Week 1
 

More from People Strategists (14)

MongoDB Session 3
MongoDB Session 3MongoDB Session 3
MongoDB Session 3
 
Android - Day 1
Android - Day 1Android - Day 1
Android - Day 1
 
Overview of web services
Overview of web servicesOverview of web services
Overview of web services
 
Spring Framework - III
Spring Framework - IIISpring Framework - III
Spring Framework - III
 
Spring Framework -I
Spring Framework -ISpring Framework -I
Spring Framework -I
 
Hibernate II
Hibernate IIHibernate II
Hibernate II
 
Overview of JEE Technology
Overview of JEE TechnologyOverview of JEE Technology
Overview of JEE Technology
 
XML Schemas
XML SchemasXML Schemas
XML Schemas
 
JSON and XML
JSON and XMLJSON and XML
JSON and XML
 
Ajax and Jquery
Ajax and JqueryAjax and Jquery
Ajax and Jquery
 
CSS
CSSCSS
CSS
 
HTML/HTML5
HTML/HTML5HTML/HTML5
HTML/HTML5
 
JDBC
JDBCJDBC
JDBC
 
Java Day-3
Java Day-3Java Day-3
Java Day-3
 

Recently uploaded

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
The Evolution of Money: Digital Transformation and CBDCs in Central Banking
The Evolution of Money: Digital Transformation and CBDCs in Central BankingThe Evolution of Money: Digital Transformation and CBDCs in Central Banking
The Evolution of Money: Digital Transformation and CBDCs in Central BankingSelcen Ozturkcan
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 

Recently uploaded (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
The Evolution of Money: Digital Transformation and CBDCs in Central Banking
The Evolution of Money: Digital Transformation and CBDCs in Central BankingThe Evolution of Money: Digital Transformation and CBDCs in Central Banking
The Evolution of Money: Digital Transformation and CBDCs in Central Banking
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 

RDBMS with MySQL

  • 1. © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com
  • 2. © 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.
  • 186. Case Study (Contd.) • Solution • insert into Wages values('I',25000),('II',18000),('III',12000);
  • 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
  • 188. Case Study (Contd.) • Solution 8 • Update Employee set Emp_cateory=’I’ where Emp_ID=78;
  • 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.
  • 192. Case Study (Contd.) • Solution 10 • Delete from Employee where Emp_ID=78;
  • 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.