0% found this document useful (0 votes)
16 views486 pages

Mysql PPT Ver8

Uploaded by

dhananjay patil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views486 pages

Mysql PPT Ver8

Uploaded by

dhananjay patil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 486

A day without new

knowledge is a lost day.


Before we start DBT module.
Which module(s) you have completed?

Database Technologies - MySQL


If A and a, B and b, C and c etc. are treated in the same way then it is case-insensitive.
MySQL is case-insensitive
iet
In this module we are going to learn SQL, PL/SQL and NoSQL(MongoDB)
Class Room

Session 1
Introduction

• If anyone who wants to develop a good application


then he should have the knowledge three major components.

• They are (3-Tier Architecture).


1. UI (Presentation Tier)
2. Middle Layer (Application Tier)
3. Database (Database Tier)

So as a programmer:
a person should understand and be able to interact with a database is must, so than the
data which is collected from the UI is processed and stored permanently. (eg. Any
management systems, set top box, washing machine, mobile application etc.).
Introduction

Why do we need databases (Use Case)?

We need databases because they organize data in a manner which allows us to store, query, sort,
and manipulate data in various ways. Databases allow us to do all this things.

Many companies collects data from different resource (like Weather data, Geographical data,
Finance data, Scientific data, Transport data, Cultural data, etc.)
What is Relation and
Relationship?
Relation and Relationship?

Relation (in Relational Algebra "R" stands for relation): In Database, a relation represents a
table or an entity than contain attributes.

Relationship: In database, relationship is that how the two entities are connected to each
other, i.e. what kind of relationship type they hold between them.

Primary/Foreign key is used to specify


this relationship.

Remember: Note:
• Foreign Key is also know as • Table - The physical instantiation of a relation in the
database schema.
Reference/Referential key. • Relation - A logical construct that organizes data into rows
and columns.
File Systems is the traditional way to keep your data organized.

File System
vs
DBMS
struct Employee {
int emp_no;
struct Employee {
int emp_no;
File-oriented system
char emp_name[50]; char emp_name[50]; File Anomalies
int salary; int salary;
} emp[1000]; };
struct Employee emp[1000];

c:\employee.txt c:\employee.txt c:\employee.txt c:\employee.txt c:\employee.txt


1 suraj 4000 1 suraj 4000 1 suraj 4000 1 suraj 4000 1 suraj 4000
2 ramesh 6000 2 ramesh 6000 2 ramesh 6000 2 ramesh 6000 2 ramesh 6000
3 rajan 4500 3 rajan 4500 3 rajan 4500 3 rajan 4500 3 rajan 4500
. | . | . | . | . |
. | . | . | . | . |
. | . | . | . | . |
500 sam 3500 500 sam 3500 500 pankaj 3500 pankaj 500 3500 500 sam 3500
. | . | . | . | . |
. | . | . | . | . |
. | 1000 amit 2300 1000 amit 2300 1000 amit 2300 . |
1000 amit 2300 . | . | . | . |
. | 1000 amit 2300 1000 amit 2300 . |
. | . | . | 1250 neel 4500
2000 jerry 4500 2000 jerry 4500 jerry 2000 4500
. | . | . |
. | . | . |
• Create/Open an existing file with attributes as ("a" or "a+" or "w" or
File-oriented system
"w++") (fopen)
File Anomalies
• Reading from file (fscanf or fgets)
• Writing to a file (fprintf or fputs)
• Closing a file (fclose)
c:\employee.txt file attributes file permissions search empl ID=1 search emp_name
1 suraj 4000 • File Name • File permissions 1 suraj 4000 1 suraj 4000
2 ramesh 6000 • Type • Share permissions 2 ramesh 6000 2 ramesh 6000
3 rajan 4500 • Location 3 rajan 4500 3 rajan 4500
. | . | . |
. | . | . |
. | . | . |
500 sam 3500 500 pankaj 3500 500 pankaj 3500
. | . | . |
. | . | . |
1000 amit 2300 1000 amit 2300 1000 amit 2300
. | . | . |
1000 amit 2300 1000 amit 2300 1000 amit 2300
. | . | . |
2000 jerry 4500 2000 jerry 4500 2000 jerry 4500
. | . | . |
. | . | . |
File-oriented system
A flat file database is a database that stores data in a plain text file (e.g. *.txt, *.csv, *.tsv etc. format). Each line of
the text file holds one record, with fields separated by delimiters, such as commas or tabs.

The Zen of Python,


1 rajan MG Road Pune MH 34500
2 rahul patil SSG Lane Pune MH 54000 Beautiful is better than ugly.
3 suraj raj k Deccan Gymkhana Pune MH 22000 Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
4, S M Kumar, Mg Road Pune MH, 32000 Flat is better than nested.
5, S M Kumar, Mg Road, Pune, MH, 32000 Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Advantages of file-oriented system
The biggest advantage of file-based storage is that anyone can understand the system.

Advantage of File-oriented system

• Backup: It is possible to take faster and automatic back-up of database stored in files of computer-based
systems.

• Data retrieval: It is possible to retrieve data stored in files in easy and efficient way.

• Editing: It is easy to edit any information stored in computers in form of files.

• Remote access: In computer-based systems, it is possible to access data remotely.

• Sharing: Data stored in files of computer-based systems can be shared among multiple users at a same time.
Disadvantage of file-oriented system
The biggest disadvantage of file-based storage is as follows.

Disadvantage of File-oriented system

• Data redundancy: It is possible that the same information may be duplicated in different files. This leads to data
redundancy results in memory wastage. (Suppose a customer having both kind of accounts- saving and current
account. In such a situation a customers detail are stored in both the file, saving.txt- file and current.txt- file ,
which leads to Data Redundancy.)
• Data inconsistency: Because of data redundancy, it is possible that data may not be in consistent state. (Suppose
customer changed his/her address. There might be a possibility that address is changed in only one file
(saving.txt) and other (current.txt) remain unchanged.)
• Limited data sharing: Data are scattered in various files and also different files may have different formats (for
example: .txt, .csv, .tsv and .xml) and these files may be stored in different folders so, due to this it is difficult to
share data among different applications.
• Data Isolation: Because data are scattered in various files, and files may be in different formats (for example: .txt,
.csv, .tsv and .xml), writing new application programs to retrieve the appropriate data is difficult.
• Data security: Data should be secured from unauthorized access, for example a account holder in a bank should
not be able to see the account details of another account holder, such kind of security constraints are difficult to
apply in file processing systems.
Relation Schema: A relation schema represents name of the relation with its attributes.
• e.g. student (roll_no, name, address, phone and age) is relation schema for STUDENT

DBMS
The database management system (DBMS) is the software that interacts with end users, applications, and the
database itself to store and analyze the data.

• database: Is the collection of related data which is organized, store and retrieve large amount of
data easily, which is stored in one or more data files by one or more users, it is called as structured
data.
• management system: is a software, designed to define, manipulate, retrieve and manage data in a
database.
Difference between File System and DBMS

File Management System Database Management System


• File System is easy-to-use system to store data which • Database Management System is used when security
require less security and constraints. constraints are high.

• Data Redundancy is less in Database Management


• Data Redundancy is more in File System. System.
• Data Inconsistency is less in Database Management
• Data Inconsistency is more in File System. System.
• Centralization is hard to get when it comes to File • Centralization is achieved in Database Management
System. System.

• User locates the physical address of the files to access • In Database Management System, user is unaware of
data in File System. physical address where data is stored.

• Security is low in File System. • Security is high in Database Management System.


• File System stores unstructured data. "unstructured
data" may include documents, audio, video, images, • Database Management System stores structured data.
and files.
relational database management system?
A RDBMS is a database management system (DBMS) that is based on the relational model
introduced by Edgar Frank Codd at IBM in 1970.

RDBMS supports

• client/server Technology

• Highly Secured

• Relationship (PK/FK)
Difference between DBMS and RDBMS

DBMS RDBMS

• Data is stored as file. • Data is stored as tables.

• Data is present in multiple tables which can be related


• There is no relationship between data in DBMS. to each other.

• DBMS has no support for distributed databases. • RDBMS supports distributed databases.
• Normalization cannot be achieved. • Normalization can be achieved.
• DBMS supports single user at a time. • RDBMS supports multiple users at a time.
• Data Redundancy is common in DBMS. • Data Redundancy can be reduced in RDBMS.

• DBMS provides low level of security during data • RDBMS has high level of security during data
manipulation. manipulation.
relational model concepts
and
properties of relational table
relational model concepts
Relational model organizes data into one or more tables (or "relations") of columns and rows. Rows are also
called records or tuples. Columns are also called attributes.

• Tables − In relational model, relations are saved in the form of Tables. A table has rows and columns.

• Attribute − Attributes are the properties that define a relation. e.g. (roll_no, name, address, phone and age)

• Tuple − A single row of a table, which contains a single record for that relation is called a tuple.

• Relation schema − A relation schema describes the relation name (table name) with its attribute (columns) names.
e.g. student(roll_no, name, address, phone and age) is relation schema for student relation.

• Attribute domain − Every attribute has some pre-defined datatypes, known as attribute domain.

• Relation key − Each row has one or more attributes, known as relation key, which can identify the row in the
relation (table) uniquely.
properties of relational table
ID job firstName DoB salary Domain refers to all the valid values
1 manager Saleel Bagde yyyy-mm-dd ●●●●●● which a column may contain.
3 salesman Sharmin yyyy-mm-dd ●●●●●●

4 accountant Vrushali yyyy-mm-dd ●●●●●●

2 salesman Ruhan yyyy-mm-dd ●●●●●●

5 9500 manager yyyy-mm-dd ●●●●●●

5 Salesman Rahul Patil yyyy-mm-dd ●●●●●●

Relational tables have six properties:


• Values are atomic.
• Column values are of the same kind. (Attribute Domain: Every attribute has some pre-defined datatypes,
known as attribute domain.)
• Each row is unique.
• The sequence of columns is insignificant – (unimportant).
• The sequence of rows is insignificant – (unimportant).
• Each attribute/column must have a unique name.
What is data?
What is Data?
Data is any facts that can be stored and that can be processed by a computer.

Data can be in the form of Text or Multimedia

e.g.
• number, characters, or symbol
• images, audio, video, or signal
What is Entity Relationship
Diagram?
Entity Relationship Diagram (ER Diagram)

Use E-R model to get a high-level graphical view to describe


the "ENTITIES" and their "RELATIONSHIP"

The basic constructs of ER Model are


Entity, Attributes and Relationships.
An entity can be a real-world object.

What is Entity?
Entity

In relation to a database , an entity is a person, place, or thing about which


data can be stored.

e.g., in a school database, students, teachers, classes, and courses can be


considered as entities.

All these entities have some attributes or properties that give them their identity.

Every entity has its own characteristics.


When you are designing attributes for your entities, you will sometimes find that an attribute does not
have a value. For example, you might want an attribute for a person's middle name, but you can't require a
value because some people have no middle name. For these, you can define the attribute so that it can
contain null values.

What is an Attribute?
Entity
Attributes are the properties that define a relation.
e.g. student(ID, firstName, middleName, lastName, city)

Attribute
In some cases, you might not want a specific attribute to contain a null
value, but you don't want to require that the user or program always provide a
value. In this case, a default value might be appropriate. A default value is a
value that applies to an attribute if no other valid value is available.
Attributes

A table has rows and columns


In RDBMS, a table organizes data in rows and columns. The COLUMNS are known as
ATTRIBUTES / FIELDS whereas the ROWS are known as RECORDS / TUPLE.

In Relation: EMP
Attributes

ID EmployeeName Job Hiredate Salary


1 KING PRESIDENT 2017-02-15 5000
… … … … …
Rows
… … … … …
… … … … …
Attributes

In Entity Relationship(ER) Model attributes can be classified


into the following types.

• Simple/Atomic and Composite Attribute


• Single Valued and Multi Valued attribute
• Stored and Derived Attributes
• Complex Attribute
• Simple / Atomic Attribute --VS-- Composite Attribute Attributes
(Can’t be divided further) (Can be divided further)
• Single Value Attribute --VS-- Multi Valued Attribute
(Only One value) (Multiple values)
• Stored Attribute --VS-- Derived Attribute
(Only One value) (Virtual)
• Complex Attribute
(Composite & Multivalued)

• Atomic Attribute: An attribute that cannot be divided into smaller independent attribute is known as atomic
attribute.
e.g. ID’s, age, gender, zip, marital status cannot further divide.

• Single Value Attribute: An attribute that has only single value is known as single valued attribute.
e.g. manufactured part can have only one serial number, voter card, blood group, price, quantity, branch can
have only one value.

• Stored Attribute: The stored attribute are such attributes which are already stored in the database and from
which the value of another attribute is derived.
e.g. (HRA, DA…) can be derive from salary, age can be derived from DoB, total marks or average marks of a
student can be derived from marks.
Composite VS Multi Valued
Attribute
Composite / Multi Valued Attributes
Composite Attribute
Person Entity
• Name attribute: ( firstName, middleName, and lastName )
• PhoneNumber attribute: ( countryCode, cityCode, and phoneNumber )

Multi Valued Attribute


Person Entity
• Hobbies attribute: [ reading, hiking, hockey, skiing, photography, . . . ]
• SpokenLanguages attribute: [ Hindi, Marathi, Gujarati, English, . . . ]
• Degrees attribute: [ 10th , 12th, BE, ME, PhD, . . . ]
• emailID attribute: [ [email protected], [email protected], . . . ]
What is an Prime, Non-Prime
Attribute?
Attributes

Prime attribute (Entity integrity)


An attribute, which is a part of the prime-key (candidate key), is known as a prime attribute.

Non-prime attribute
An attribute, which is not a part of the prime-key (candidate key), is said to be a non-prime
attribute.
erdplus.com

Entity Relationship Diagram Symbols www.draw.io

Attribute
Composite
Attribute

Key Attribute

Strong Entity Weak Entity


Derived
Attribute

Weak
Relationship Relationship
Multivalued
Attribute
Entity Relationship Diagram
DoB
What is a degree, cardinality, domain and
union in database?
• Degree d(R) / Arity: Total number of attributes/columns present in a relation/table is called degree of the
relation and is denoted by d(R).

• Cardinality |R|: Total number of tuples/rows present in a relation/table, is called cardinality of a


relation and is denoted by |R|.

• Domain: Total range of accepted values for an attribute of the relation is called the domain of the
attribute. (Data Type)

• Union Compatibility: Two relations R and S are set to be Union Compatible to each other if and only if:
1. They have the same degree d(R).
2. Domains of the respective attributes should also be same.
Data integrity refers to the correctness
and completeness of data. A domain constraint and types
of data integrity constraints
 Domain Constraint = data type + Constraints (not null/unique/primary key/foreign key/check/default )
e.g. custID INT, constraint pk_custid PRIMARY KEY(custID)

Three types of integrity constraints: entity integrity, referential integrity and domain integrity:

• Entity integrity: Entity Integrity Constraint is used to ensure the uniqueness of each record the table. There are
primarily two types of integrity constraints that help us in ensuring the uniqueness of each row, namely,
UNIQUE constraint and PRIMARY KEY constraint.

• Referential integrity: Referential Integrity Constraint ensures that there always exists a valid relationship
between two tables. This makes sure that if a foreign key exists in a table relationship then it should always
reference a corresponding value in the second table or it should be null.

• Domain integrity: A domain is a set of values of the same type. For example, we can specify if a particular
column can hold null values or not, if the values have to be unique or not, the data type or size of values that
can be entered in the column, the default values for the column, etc..
What is a domain constraint in database?
• Domain Constraint = data type + Constraints (NOT NULL / UNIQUE / PRIMARY KEY
/ FOREIGN KEY / CHECK / DEFAULT)

Data Domain refers to all the valid values which a column may contain and can be done by giving data type to
the column.
Keys are used to establish relationships between tables
and also to uniquely identify any record in the table. types of Keys?
r = Employee(EmployeeID, FullName, job, salary, PAN,
DateOfBirth, emailID, deptno)
• Candidate Key: are individual columns in a table that qualifies for uniqueness of all the rows. Here in Employee
table EmployeeID, PAN or emailID are Candidate keys.

• Primary Key: is the columns you choose to maintain uniqueness in a table. Here in Employee table you can
choose either EmployeeID, PAN or emailID columns, EmployeeID is preferable choice.

• Alternate Key: Candidate column other the primary key column, like if EmployeeID is primary key then , PAN
or emailID columns would be the Alternate key.

• Super Key: If you add any other column to a primary key then it become a super key, like EmployeeID +
FullName is a Super Key.

• Composite Key: If a table do not have any single column that qualifies for a Candidate key, then you have to
select 2 or more columns to make a row unique. Like if there is no EmployeeID, PAN or emailID columns, then
you can make FullName + DateOfBirth as Composite key. But still there can be a narrow chance of duplicate
row.
Candidate Key
Primary Key

Composite Key
Alternate Key
Degrees of relationship
The degree of relationship can be defined as the number of occurrences in
one entity that is associated with the number of occurrences in another entity.
Relationships

There are three degrees of relationship

1. one-to-one (1:1)

2. one-to-many (1:M)

3. many-to-many (M:N)
one-to-one relationship
one-to-one relationship
A one-to-one relationship between two tables means that a row in one table can only relate to
zero/one row in the table on the other side of their relationship. This is the least common database
relationship.

A one-to-one relationship is a type of cardinality that refers to the relationship between two entities
R and S in which one element of entity R may only be linked to zero/one element of entity S, and
vice versa.

Country-1 Capital-1 Country-1 Capital-1

Country-2 one-to-one Capital-2 Country-2 Capital-2


relationship =
Country-3 Capital-3 Country-3 Capital-3
one-to-one relationship
A one-to-one relationship between two tables means that a row in one table can only relate to
zero/one row in the table on the other side of their relationship. This is the least common database
relationship.

A one-to-one relationship is a type of cardinality that refers to the relationship between two entities
R and S in which one element of entity R may only be linked to zero/one element of entity S, and
vice versa.

Person-1 Passport-1 Person-1 Passport-1

Person-2 one-to-one Passport-1 Person-2 Passport-1


relationship =
Person-3 Person-4 Passport-1

Person-4 Passport-1
how to create one-to-one relationship
CREATE TABLE user (
userID INT PRIMARY KEY,
userName VARCHAR(40),
password VARCHAR(25),
email VARCHAR(128)
) ;

CREATE TABLE userImage (


imageID INT PRIMARY KEY,
imageUrl VARCHAR(255),
description VARCHAR(255),
userID INT NOT NULL UNIQUE,
FOREIGN KEY(UserID)
REFERENCES user(userID)
) ;
how to create one-to-one relationship
CREATE TABLE person (
person_ID INT PRIMARY CREATE TABLE passportDetails (
KEY , passportID VARCHAR(20) PRIMARY KEY,
name VARCHAR(45), passport_Number VARCHAR(255),
emailID VARCHAR(128) person_ID INT UNIQUE,
); FOREIGN KEY(person_ID) REFERENCES
person(person_ID)
);
one-to-many relationship
one-to-many relationship
A one-to-many relationship between two tables means that a row in one table can have zero or more
row in the table on the other side of their relationship.

a one-to-many relationship is a type of cardinality that refers to the relationship between two entities R
and S in which an element of R may be linked to many elements of S, but a member of S is linked to
only one element of R.

Customer-1 Order-1 Customer-1 Order-1

Customer-2 Order-1 Customer-2 Order-1


one-to-many
Customer-3
relationship
Order-2
= Customer-2 Order-2

Customer-4 Order-1 Customer-3 Order-1

Customer-5 Order-2 Customer-3 Order-2

Order-3 Customer-3 Order-3

Order-1 Customer-4 Order-1


one-to-many relationship
A one-to-many relationship between two tables means that a row in one table can have one or more
row in the table on the other side of their relationship.

a one-to-many relationship is a type of cardinality that refers to the relationship between two entities R
and S in which an element of R may be linked to many elements of S, but a member of S is linked to
only one element of R.

Invoice-1 Invoice_Item-1 Invoice-1 Invoice_Item-1

Invoice-2 Invoice_Item-1 Invoice-2 Invoice_Item-1


one-to-many
Invoice-3
relationship
Invoice_Item-2
= Invoice-2 Invoice_Item-2

Invoice-4 Invoice_Item-1 Invoice-3 Invoice_Item-1

Invoice_Item-2 Invoice-3 Invoice_Item-2

Invoice_Item-2 Invoice-3 Invoice_Item-3

Invoice_Item-1 Invoice-4 Invoice_Item-1


how to create one-to-many relationship
CREATE TABLE customer (
custID INT PRIMARY KEY, CREATE TABLE orders (
name VARCHAR(45), ordID INT PRIMARY KEY,
address VARCHAR(240), orderdate DATETIME,
phone VARCHAR(45), custID INT NOT NULL,
repID INT NOT NULL, shipDate DATETIME,
creditLimit FLOAT(9,2), total FLOAT(8,2),
comments TEXT, FOREIGN KEY(custID) REFERENCES
constraint custid_zero customer(custID),
CHECK(custID > 0) constraint total_greater_zero CHECK(total
); >= 0)
);
CREATE TABLE invoice ( how to create one-to-many relationship
invoiceID INT PRIMARY KEY, CREATE TABLE invoice_items (
customerID INT, ID INT PRIMARY KEY,
invoiceDate DATE, invoiceID INT NOT NULL,
invoiceAmount INT itemNumber INT,
); itenName VARCHAR(45),
itemQuantity INT,
itemRate INT,
FOREIGN KEY(invoiceID) REFERENCES
invoice(invoiceID)
);
many-to-one relationship
many-to-one relationship
CREATE TABLE users (
loginID INT,
userName VARCHAR(45),
constraint fk_users_login_loginID FOREIGN KEY(loginID)
REFERENCES login(loginID)
);
CREATE TABLE login (
loginID INT,
loginName VARCHAR(45),
createdON DATETIME,
isActive TINYINT,
PRIMARY KEY(loginID)
);
many-to-many relationship
many-to-many relationship
A many-to-many relationship is a type of cardinality that refers to the relationship between two
entities R and S in which R may contain a parent instance for which there are many children in S
and vice versa.

=
=
CREATE TABLE item (
how to create many-to-many relationship
item_ID INT PRIMARY KEY,
name VARCHAR(45),
description TEXT
);
CREATE TABLE orders (
orders_ID INT PRIMARY KEY,
orderdate DATETIME,
custID INT NOT NULL,
shipDate DATETIME,
total FLOAT(8,2),
constraint total_greater_zero CHECK(total >=
0)
);
CREATE TABLE orders_has_item (
orders_ID INT NOT NULL,
item_ID INT NOT NULL,
PRIMARY KEY(orders_ID, item_ID),
constraint fk_orders_has_item_orders FOREIGN
KEY(orders_ID)
REFERENCES orders(ID),
constraint fk_orders_has_item_item1 FOREIGN
how to create many-to-many relationship
CREATE TABLE blog (
ID INT PRIMARY KEY,
blog TEXT,
blogDate DATETIME
);

CREATE TABLE comments (


ID INT PRIMARY KEY,
comment TEXT,
commentDate DATETIME
);

CREATE TABLE blog_has_comments (


blog_ID INT,
comments_ID INT,
PRIMARY KEY(blog_ID, comments_ID),
constraint fk_blog_has_comments_blog FOREIGN KEY(blog_ID)
REFERENCES blog(ID),
constraint fk_blog_has_comments_comments FOREIGN KEY(comments_ID)
REFERENCES comments(ID)
);
erdplus.com
www.draw.io

What is Data Modeling?


Data modeling is the process of creating a data model for the data to be stored in a Database.
This data model is a conceptual representation of

•Data objects
•The associations between different data objects
•The rules.
Data Modeling

Data modeling is a process used to define and analyze data requirements needed to
support the business processes within the scope of corresponding systems in
organizations.

Data modeling involves a progression from conceptual model to logical model to


physical object.
Conceptual Model Design
Features of conceptual data model include:
• Includes the important entities and the relationships among them.
• No attribute is specified.
• No primary key is specified.
Logical Model Design
Features of logical data model include:
• Includes all entities and relationships among them.
• All attributes for each entity are specified.
• The primary key for each entity is specified.
• Foreign keys are specified.
Physical Model Design
Features of physical data model include:
• Convert entities into tables.
• Convert relationships into foreign keys.
• Convert attributes into columns.
Data Modeling

Feature Conceptual Logical Physical


Entity Names ✓ ✓
Entity Relationships ✓ ✓
Attributes ✓
Primary Keys ✓ ✓
Foreign Keys ✓ ✓
Table Names ✓
Column Names ✓
Column Data Types ✓
Problems that can occure in un-normalized database where all the data is stored in one table.

Anomalies in DBMS
Something that deviates from what is standard, normal, or expected.

There are three types of anomalies that occur when the database is not normalized. These are –
• Insertion anomaly
• Updation anomaly
• Deletion anomaly.
Anomalies in DBMS - Example
student table.

Rollno (PK) name branch hod office_tel

401 Amit CSE Mr. X 53337

402 Rajan CSE Mr. X 53337

403 Bhavin CSE Mr. X 53337

404 Pankaj CSE Mr. X 53337

NULL NULL BCA Mr. Y 77127


INSERT, UPDATE, and DELETE ANOMALY
student table.

RollNo (PK) name branch hod office_tel


401 Amit CSE Mr. X 53337
402 Rajan CSE Mr. X 53337
403 Bhavin CSE Mr. X 53337
404 Pankaj CSE Mr. X 53337
NULL NULL BCA Mr. Y 77127

• Insert anomaly: What if we want to add new branch in the student table? In this case as the student Rollno is
a primary key, is will not allow you to insert new branch. Also, if we have to insert data of 100 students of same
branch, then the branch information will be repeated for all those 100 students. This is Insertion anomalies.
• Update anomaly: What if Mr. X telephone number changes? In that case all the student records will have to
be updated, and if by mistake we miss any record, it will lead to data inconsistency. This is Updation anomaly.
• Delete anomaly: In our Student table, two different information are kept together, Student information and
Branch information. Hence, at the end of the academic year, if student records are deleted, we will also lose the
branch information. This is Deletion anomaly.
Normalization in DBMS
Normalization is the process of removing redundant data from the database by splitting the table
into two or more tables and defining relationships between these tables.
Problem
To understand normalization in database with example tables, let’s assume that we are supposed to store
the details of courses and instructors in a university.

Course code Course venue Instructor Name Instructor’s phone number


CS101 Lecture Hall 20 Prof. Ronald +1 6514821924
CS152 Lecture Hall 21 Prof. John +1 6519272918
CS154 CS Auditorium Prof. Ronald +1 6514821924

At first, this design seems to be good. However, issues start to develop once we need to modify information.
For instance, suppose, if Prof. Ronald changed his mobile number. In such a situation, we will have to make
edits in 2 places. What if someone just edited the mobile number against CS101, but forgot to edit it for
CS154? This will lead to stale/wrong information in the database.
Solution
This problem, however, can be easily tackled by dividing our table into 2 simpler tables.

Table 1 (Instructor)

Instructor's ID Instructor’s Name Instructor’s Number


1 Prof. Ronald +1 6514821924
2 Prof. John +1 6519272918
3 Prof. Smith +1 6519272919

Table 2 (Course)

Course Code Course Venue Instructor ID


CS101 Lecture Hall 20 1
CS152 Lecture Hall 21 2
CS154 CS Auditorium 1
First Normal Form (1NF)

For a table to be in the First Normal Form, it should follow the following 4 rules:

1. It should only have single(atomic) valued attributes/columns.


2. Values stored in a column should be of the same domain
3. All the columns in a table should have unique names.
4. And the order in which data is stored, does not matter.
First Normal Form (1NF)
The First normal form simply says that each cell of a table should contain exactly one value.

Instructor’s Name Course Code


Prof. Ronald (CS101, CS154)

Prof. John (CS152)


Prof. Smith (CS189, CS107)

Here, the issue is that in the first row, we are storing 2 courses against Prof. Ronald. A better method would
be to store the courses separately. This way, if we want to edit some information related to CS101, we do not
have to touch the data corresponding to CS154.

Instructor’s Name Course Code


Prof. Ronald CS101
Prof. Ronald CS154
Prof. John CS152
Prof. Smith CS189
Prof. Smith CS107
Second Normal Form (2NF)

For a table to be in the Second Normal Form

1. It should be in the First Normal form.


2. And, it should not have Partial Dependency.
Second Normal Form (2NF)
For a table to be in second normal form, the following 2 conditions are to be met:
• The table should be in the first normal form.
• The primary key of the table should compose of exactly 1 column (a compound key, if necessary).

Let us take another example of storing student enrollment in various courses. Each student may enroll in
multiple courses. Similarly, each course may have multiple enrollments.
A sample table may look like this (student name and course code)

Enrollments

Student Name Phone City Course Code Course Name


Rahul ●●●●● Pune CS152 Computer_Course_1
Rajat ●●●●● Mumbai CS101 Computer_Course_2
Rahul ●●●●● Pune CS154 Computer_Course_3
Raman ●●●●● Surat CS101 Computer_Course_2
Rajat ●●●●● Mumbai CS189 Computer_Course_5
Second Normal Form (2NF)
Student Student_Enrollment

ID(PK) Student Name Phone City ID(PK) StudentID(FK) Course Code(FK)


1 Rahul ●●●●● Pune 1 1 CS152
2 Rajat ●●●●● Mumbai 2 1 CS154
3 Raman ●●●●● Surat 3 2 CS101
4 Pankaj ●●●●● Baroda 4 3 CS101
5 2 CS189
Courses

Course Code(PK) Course Name


CS101 Computer_Course_2
CS152 Computer_Course_1
CS154 Computer_Course_3
CS107 Computer_Course_4
CS189 Computer_Course_5
Third Normal Form (3NF)

A table is said to be in the Third Normal Form when,

1. It is in the Second Normal form.


2. And, it doesn't have Transitive Dependency.
Third Normal Form (3NF)
Column A is said to be functionally dependent on column B if changing the value of A may require a change in
the value of B.
Here, the department column is dependent on the professor name column. This is because if in a particular
row, we change the name of the professor, we will also have to change the department value.

Course Code Course venue Instructor’s Name Department


CS101 Lecture Hall 18 Prof. Ronald Mathematics Department
CS152 Auditorium building Prof. John Electronics Department
CS154 Lecture Hall 19 Prof. Ronald Mathematics Department
CS189 Auditorium building #1 Prof. Smith Computer Science Department
CS107 Lecture Hall #4 Prof. Smith Computer Science Department
Third Normal Form (3NF)
Here, when we changed the name of the professor, we also had to change the department column. This is
not desirable since someone who is updating the database may remember to change the name of the
professor, but may forget updating the department value. This can cause inconsistency in the database.

Third normal form avoids this by breaking this into separate tables
Course Code Course Venue Instructor's ID
CS101 Lecture Hall 18 1
CS152 Auditorium building, 2
CS154 Lecture Hall 19 1
CS189 Auditorium building #1 3
CS107 Lecture Hall #4 3

Here, the third column is the ID of the professor who’s taking the course.
Instructor's ID Instructor's Name Instructor’s Number Department
1 Prof. Ronald +1 6514821924 Mathematics Department
2 Prof. John +1 6519272918 Electronics Department
3 Prof. Smith +1 6519272919 Computer Science Department
MySQL

MySQL is the most popular Open Source


Relational Database Management System.

MySQL was created by a Swedish company - MySQL AB that was founded in 1995. It was acquired by Sun
Microsystems in 2008; Sun was in turn acquired by Oracle Corporation in 2010.

When you use MySQL, you’re actually using at least two programmes. One program is the MySQL
server (mysqld.exe) and other program is MySQL client program (mysql.exe) that
connects to the database server.
What is SQL?
What is SQL?

SQL (Structured Query Language) is a database language designed and developed for
managing data in relational database management systems (RDBMS). SQL is common
language for all Relational Databases.
What is SQL?

Remember:
• A NULL value is not treated as a blank or 0. Null or NULL is a special marker used in Structured Query
Language to indicate that a data value does not exist in the database.
• Degree d(R): Total no. of attributes/columns present in a relation/table is called degree of the relation and is
denoted by d(R).
• Cardinality |R|: Total no. of tuples present in a relation or Rows present in a table, is called cardinality of a
relation and is denoted by |R|.
Comments in MySQL

• From a # character to the end of the line.


• From a -- sequence to the end of the line.
• From a /* sequence to the following */ sequence.
Login to MySQL
Default port for MySQL Server: 3306 Login

 C:\> mysql -hlocalhost -P3307 -uroot -p


 C:\> mysql -h127.0.0.1 -P3307 -uroot -p [database_name]
 C:\> mysql -h192.168.100.14 -P3307 -uroot -psaleel [database_name]
 C:\> mysql --host localhost --port P3306 --user root --
password=ROOT [database_name]
 C:\> mysql --host=localhost --port=P3306 --user=root --
password=ROOT [database_name]
SHOW DATABASES
SHOW DATABASES Syntax
SHOW {DATABASES | SCHEMAS} [LIKE 'pattern' |
WHERE expr]
SHOW SCHEMAS is a synonym for SHOW DATABASES.

SHOW DATABASES;
SHOW SCHEMAS;
SHOW DATABASES LIKE 'U%';
SHOW SCHEMAS LIKE 'U%';

NULL means “no database is selected”. Issue the USE dbName command to select the database.
USE DATABASES
The USE db_name statement tells MySQL to use the db_name database as the default (current)
database for subsequent statements. The database remains the default until the end of the session or
another USE statement is issued.
USE DATABASES Syntax
USE db_name

Note:
• USE, does not require a semicolon.

• USE must be followed by a database name.

USE db1
\U db1
CREATE DATABASE
CREATE DATABASE
CREATE DATABASE creates a database with the given name. To use this statement, you need the CREATE
privilege for the database.

CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name

CREATE SCHEMA is a synonym for CREATE DATABASE.

CREATE DATABASE db1;


CREATE DATABASE IF NOT EXISTS db1;
DROP DATABASE
If the default database is dropped, the default database is unset (the DATABASE() function
returns NULL).
DROP DATABASE
DROP DATABASE drops all tables in the database and deletes the database. Be very careful with this
statement! To use DROP DATABASE, you need the DROP privilege on the database.

DROP {DATABASE | SCHEMA} [IF EXISTS] db_name

DROP SCHEMA is a synonym for DROP DATABASE.

DROP DATABASE db1;


DROP DATABASE IF EXISTS db1;
Source Command
Source command
You can execute an SQL script file using the source command or \. command

\. file_name
source file_name

• \. 'D:\mysqldemobld7.sql'

• SOURCE 'D:\mysqldemobld7.sql'

• SOURCE

//infoserver1/infodomain1/Everyone/DBT/mysqldemobld7.sql
SELECT statement…
SELECT what_to_select
FROM which_table
WHERE conditions_to_satisfy;
SELECT CLAUSE
The SELECT statement retrieves or extracts data from tables in the database.

• You can use one or more tables separated by comma to extract data.

• You can fetch one or more fields/columns in a single SELECT command.

• You can specify star (*) in place of fields. In this case, SELECT will return all the fields.

• SELECT can also be used to retrieve rows computed without reference to any table e.g. SELECT 1 + 2;
Capabilities of
SELECT Statement

1. SELECTION
2. PROJECTION
3. JOINING
Capabilities of
SELECT Statement

SELECTION
Selection capability in SQL is to choose the rows in a table that you want to return
by a query.

R
EMPNO ENAME JOB HIREDATE DEPTNO
1 Saleel Manager 1995-01-01 10
2 Janhavi Sales 1994-12-20 20
3 Snehal Manager 1997-05-21 10
4 Rahul Account 1997-07-30 10
5 Ketan Sales 1994-01-01 30
Capabilities of
SELECT Statement

PROJECTION
Projection capability in SQL to choose the columns in a table that you want to
return by your query.

R
EMPNO ENAME JOB HIREDATE DEPTNO
1 Saleel Manager 1995-01-01 10
2 Janhavi Sales 1994-12-20 20
3 Snehal Manager 1997-05-21 10
4 Rahul Account 1997-07-30 10
5 Ketan Sales 1994-01-01 30
Capabilities of
SELECT Statement

JOINING
Join capability in SQL to bring together data that is stored in different tables by
creating a link between them.
R S
EMPNO ENAME JOB HIREDATE DEPTNO DEPTNO DNAME LOC
1 Saleel Manager 1995-01-01 20 10 HRD PUNE
2 Janhavi Sales 1994-12-20 10 20 SALES BARODA
3 Snehal Manager 1997-05-21 10 40 PURCHASE SURAT
4 Rahul Account 1997-07-30 20
5 Ketan Sales 1994-01-01 30
SELECT statement

SELECTION Process

SELECT * FROM <table_references>


selection-list | field-list | column-list

PROJECTION Process

SELECT column-list FROM <table_references>

selection-list | field-list | column-list


• SELECT 'HELLO' ' WORLD';
• SELECT 'HELLO' AS 'WORLD';
• SELECT ename `EmployeeName` FROM emp;
• SELECT ename AS `EmployeeName` FROM emp;

Column - ALIAS
A programmer can use an alias to temporarily assign another name to a column or table for the
duration of a SELECT query.

In the selection-list, a quoted column alias can be specified using identifier ( ` ) or string quote ( ' or " ) characters.

Note:
• Assigning an alias_name does not actually rename the column or table.
SELECT statement - ALIAS
SELECT A1 [ [as] alias_name], A2 [ [as] alias_name], . . ., AN FROM r
[ [as] alias_name]
Remember:
• A select_expr can be given an alias using AS alias_name. The alias is used as the expression's column name
and can be used in GROUP BY, HAVING, or ORDER BY clauses.
• The AS keyword is optional when aliasing a select_expr with an identifier.
• Standard SQL disallows references to column aliases in a WHERE clause.
• A table reference can be aliased using tbl_name alias_name or tbl_name AS alias_name
• If the column alias contains spaces, put it in quotes.
• Alias name is max 256 characters.

• SELECT empno as EmployeeID, ename EmployeeName FROM emp;


• SELECT ID as 'Employee ID', ename "Employee Name" FROM emp;
• SELECT * FROM emp employee;
Comparison Functions and Operator
Comparison operations result in a value of 1 (TRUE), 0 (FALSE), or NULL.
Comparison Functions and Operator
= Equal operator
!=, <> Not equal operator
> Greater than operator
>= Greater than or equal operator
< Less than operator
<= Less than or equal operator
<=> NULL-safe equal to operator
IS NULL NULL value test
IS NOT NULL NOT NULL value test
ISNULL() Test whether the argument is NULL
IS Test a value against a boolean
IS NOT Test a value against a boolean
IN() Check whether a value is within a set of values
NOT IN() Check whether a value is not within a set of values
LIKE Simple pattern matching
NOT LIKE Negation of simple pattern matching
BETWEEN ... AND ... Whether a value is within a range of values
NOT BETWEEN ... AND ... Whether a value is not within a range of values
COALESCE() Return the first non-NULL argument
Comparison Functions and Operator
operand meaning: the quantity on which
1. arithmetic_operators: an operation is to be done.
* | / | DIV | % |MOD | - | +
2. comparison_operator: e.g.
= | <=> | >= | > | <= | < | <> | !
=
• operand1 * operand2
• operand1 = operand2
3. boolean_ predicate: • operand IS [NOT] NULL
IS [NOT] NULL • operand [NOT] LIKE
| expr <=> null
'pattern'
4. predicate: • expr AND expr
expr [NOT] LIKE (expr [, • Operand := 1001
expr] ...)
| expr [NOT] IN expr AND
• SELECT 23 DIV 6 ; #3
predicate
| expr [NOT] IN (subquery) • SELECT 23 / 6 ; #3
| expr [NOT] BETWEEN expr [ESCAPE .8333
expr]
5. logical_operators
AND | && | OR | ||
• WHERE col * 4
< 16
• WHERE col <
16 / 4

Column - EXPRESSIONS
"Strings are automatically converted to numbers and numbers to strings as necessary." This means
that in order to compare a string to a number, it tries to parse a number from the start of the string.
In this case there is no number there, so it converts to 0, and 0 = 0 is true.
SELECT statement - EXPRESSIONS
Column EXPRESSIONS

SELECT A1, A2, A3, A4, expressions, . . . FROM r

• SELECT 1001 + 1; • SELECT sal, sal + 1000 AS 'New Salary' FROM


• SELECT 1001 + '1'; emp;
• SELECT '1' + '1' ; • SELECT sal, comm, sal + comm FROM emp;
• SELECT '1' + 'a1'; • SELECT sal, comm, sal + IFNULL(comm, 0) FROM
• SELECT '1' + '1a'; emp;
• SELECT 'a1' + 1; • SELECT ename, ename = ename FROM emp;
• SELECT '1a' + 1; • SELECT ename, ename = 'smith' FROM emp;
• SELECT 1 + -1;
• SELECT 1 + -2;
• SELECT -1 + -1;
• SELECT -1 - -1;
COALESCE()
Return the first non-NULL argument
COALESCE()
TODO

• SELECT primaryphone, bphone, cphone, hphone, IFNULL(COALESCE(bphone, cphone,


hphone), 'Contact customer care') 'Active Phone' FROM coalesce;
Identifiers
Certain objects within MySQL, including database, table, index, column, alias, view, stored
procedure, stored functions, triggers, partition, tablespace, and other object names are known as
identifiers.
Identifiers
The maximum length for each type of identifiers like (Database, Table, Column, Index, Constraint,
View, Stored Program, User-Defined Variable, Tablespace) is 64 characters, whereas for Alias is
256 characters.

• You can refer to a table within the default database as


1. tbl_name
2. db_name.tbl_name.

• You can refer to a column as


1. col_name
2. tbl_name.col_name
3. db_name.tbl_name.col_name.

Note:
• You need not specify a tbl_name or db_name.tbl_name prefix for a column reference unless the reference
would be ambiguous.
• The identifier quote character is the backtick (`)
• DATEDIFF(CURDATE(), hiredate) / 365.25

DateTime Functions
NOW(), CURDATE(), CURTIME()

In MySQL, the NOW() function returns a default value for a DATETIME.


MySQL inserts the current date and time into the column whose default value is NOW().

In MySQL, the CURDATE() returns the current date in 'YYYY-MM-DD'. CURRENT_DATE() and
CURRENT_DATE are the synonym of CURDATE().

In MySQL, the CURTIME() returns the value of current time in 'HH:MM:SS'. CURRENT_TIME() and
CURRENT_TIME are the synonym of CURTIME().
NOW(), CURDATE(), CURTIME()

• SELECT NOW()
• SELECT CURDATE()
• SELECT CURTIME()

Result in something like this:


NOW() CURDATE() CURTIME()
2017-02-11 10:22:31 2017-02-11 10:22:31
+ or - operator
Date arithmetic also can be performed using INTERVAL together with the + or - operator
date + INTERVAL expr unit + INTERVAL expr unit + INTERVAL expr unit + .
. .
date - INTERVAL expr unit - INTERVAL expr unit - INTERVAL expr unit - .
. .
SELECT NOW(), NOW() + INTERVAL 1 DAY;

unit Value ExpectedexprFormat


SECOND SECONDS
MINUTE MINUTES
HOUR HOURS
DAY DAYS
WEEK WEEKS
MONTH MONTHS
QUARTER QUARTERS
YEAR YEARS
ADDDATE()
ADDDATE() is a synonym for DATE_ADD()
ADDDATE(date, INTERVAL expr unit) / ADDDATE(expr,
day_in_number)
• SELECT NOW(), ADDDATE(NOW(), INTERVAL 1 DAY);
• SELECT NOW(), ADDDATE(NOW(), 1);

unit Value ExpectedexprFormat


SECOND SECONDS
MINUTE MINUTES
HOUR HOURS
DAY DAYS
WEEK WEEKS
MONTH MONTHS
QUARTER QUARTERS
YEAR YEARS
SUBDATE()
SUBDATE() is a synonym for DATE_SUB()
SUBDATE(date, INTERVAL expr unit) / SUBDATE(expr,
day_in_number)
• SELECT NOW(), SUBDATE(NOW(), INTERVAL 1 DAY);
• SELECT NOW(), SUBDATE(NOW(), 1);

unit Value ExpectedexprFormat


SECOND SECONDS
MINUTE MINUTES
HOUR HOURS
DAY DAYS
WEEK WEEKS
MONTH MONTHS
QUARTER QUARTERS
YEAR YEARS
EXTRACT
The EXTRACT() function is used to return a single part of a date/time, such as year, month, day,
hour, minute, etc.

EXTRACT(unit FROM date)

Unit Value
MICROSECOND SECOND MINUTE HOUR DAY
WEEK MONTH QUARTER YEAR
MINUTE_SECOND HOUR_SECOND DAY_SECOND DAY_HOUR
HOUR_MINUTE DAY_MINUTE YEAR_MONTH

• SELECT EXTRACT(MONTH FROM NOW());


• SELECT EXTRACT(YEAR_MONTH FROM NOW()) ;
Note:
• There must no space between extract function and ().
e.g.
SELECT EXTRACT (MONTH FROM NOW());
DateTime Functions
Syntax Result
DAY(date) DAY() is a synonym for DAYOFMONTH().

DAYNAME(date) Returns the name of the weekday for date.

DAYOFMONTH(date) Returns the day of the month for date, in the range 1 to 31
Returns the weekday index for date (1 = Sunday, 2 = Monday, …, 7
DAYOFWEEK(date)
= Saturday).

DAYOFYEAR(date) Returns the day of the year for date, in the range 1 to 366
Takes a date or datetime value and returns the corresponding
LAST_DAY(date) value for the last day of the month. Returns NULL if the
argument is invalid.
Returns the month for date, in the range 1 to 12 for January to
MONTH(date)
December
•MONTHNAME(date)
SELECT DAYOFWEEK(NOW()), WEEKDAY(NOW());
Returns the full name of the month for date.
• SELECT DAYOFWEEK(ADDDATE(NOW(), INTERVAL 1 DAY)), WEEKDAY(ADDDATE(NOW(),
INTERVAL 1 DAY));
DateTime Functions
Syntax Result
Returns the weekday index for date (0 = Monday, 1 = Tuesday,
WEEKDAY(date)
… 6 = Sunday).
Returns the calendar week of the date as a number in the
WEEKOFYEAR(date)
range from 1 to 53.
Returns the quarter of the year for date, in the range 1 to
QUARTER(date)
4.
Returns the hour for time. The range of the return value is 0
HOUR(time)
to 23 for time-of-day values.
MINUTE(time) Returns the minute for time, in the range 0 to 59.

SECOND(time) Returns the second for time, in the range 0 to 59.


•DATEDIFF(expr1,expr
SELECT NOW(), NOW()Returns
+ INTERVAL 1 DAY, of
the number WEEKDAY(NOW()
days between+ two dates or datetimes.
2) INTERVAL 1 DAY);

• SELECT * FROM emp WHERE DAY(hiredate) = 17;


DateTime Formats
DateTime Formats
Formats Description
%a Abbreviated weekday name (Sun-Sat)
%b Abbreviated month name (Jan-Dec)
%c Month, numeric (1-12)
%D Day of month with English suffix (0th, 1st, 2nd, 3rd, �)
%d Day of month, numeric (01-31)
%e Day of month, numeric (1-31)
%f Microseconds (000000-999999)
%H Hour (00-23)
%h Hour (01-12)

• SELECT DATE_FORMAT(NOW(), '%a');


DateTime Formats
Formats Description
%I Hour (01-12)
%i Minutes, numeric (00-59)
%j Day of year (001-366)
%k Hour (0-23)
%l Hour (1-12)
%M Month name (January-December)
%m Month, numeric (01-12)
%p AM or PM
%r Time, 12-hour (hh:mm:ss followed by AM or PM)
%S Seconds (00-59)
%s Seconds (00-59)

• SELECT DATE_FORMAT(NOW(), '%j');


DateTime Formats
Formats Description
%T Time, 24-hour (hh:mm:ss)
%U Week (00-53) where Sunday is the first day of week
%u Week (00-53) where Monday is the first day of week
%V Week (01-53) where Sunday is the first day of week, used with %X
%v Week (01-53) where Monday is the first day of week, used with %x
%W Weekday name (Sunday-Saturday)
%w Day of the week (0=Sunday, 6=Saturday)
Year for the week where Sunday is the first day of week, four digits,
%X
used with %V
Year for the week where Monday is the first day of week, four digits,
%x
used with %v
%Y Year, numeric, four digits
%y Year, numeric, two digits

• SELECT DATE_FORMAT(NOW(), '%Y');


• SELECT sal, REPEAT('$', sal/100)
FROM emp;

String Functions
String Functions
Syntax Result
Returns the numeric value of the leftmost character of the
string str. Returns 0 if str is the empty string. Returns NULL
ASCII(str) if str is NULL.
e.g.
• SELECT ASCII(ename) FROM emp;
CHAR() interprets each argument N as an integer and returns a
string consisting of the characters given by the code values of
those integers. NULL values are skipped.
CHAR(N, , . . .)
e.g.
• SELECT CHAR(65, 66, 67); / SELECT CAST(CHAR(65 66, 67) as
CHAR);
Returns the string that results from concatenating the
CONCAT(str1, arguments. CONCAT() returns NULL if any argument is NULL.
str2, . . .) e.g.
• SELECT CONCAT('Mr. ' , ename) FROM emp;
ELT() returns the Nth element of the list of strings: str1 if N
= 1, str2 if N = 2, and so on. Returns NULL if N is less than 1
or greater than the number of arguments.
e.g.
ELT(N, str1,
str2, • SELECT ELT(1, 'Bank', 'Of', 'India', 'Kothrud', 'Pune');
str3, . . .)
• SELECT ELT(1, ename, job, sal) FROM emp;
String Functions
Syntax Result
STRCMP() returns 0 if the strings are the same, -1 if the first
STRCMP(expr1,
argument is smaller than the second according to the current
expr2)
sort order, and 1 otherwise.
LCASE(str) Returns lower case string. LCASE() is a synonym for LOWER().
UCASE(str) Returns upper case string. UCASE() is a synonym for UPPER().
LENGTH(str) Returns the length of the string.
LPAD(str, len, Returns the string str, left-padded with the string padstr to a
padstr) length of len characters.
RPAD(str, len, Returns the string str, right-padded with the string padstr to
padstr) a length of len characters.
Returns the leftmost len characters from the string str, or
LEFT(str, len)
NULL if any argument is NULL.
Returns the rightmost len characters from the string str, or
RIGHT(str, len)
NULL if any argument is NULL.
LTRIM(str) Returns the string str with leading space characters removed.
RTRIM(str) Returns the string str with trailing space characters removed.
Returns
• SELECT * FROM emp1 WHERE the string
ename str with
= BINARY leading and trailing space
UPPER(ename);
TRIM(str)
characters
• SELECT * FROM emp1 removed.
WHERE ename = BINARY LOWER(ename);
String Functions
Syntax Result
Returns the position of the first occurrence of substring
INSTR(str, substr)
substr in string str.
Returns the string str with all occurrences of the string
REPLACE(str, from_str replaced by the string to_str. REPLACE() performs
from_str, to_str) a case-sensitive match when searching for from_str.
e.g.
• SELECT REPLACE('Hello', 'l', 'x');
Returns the string str with the order of the characters
REVERSE(str)
reversed.
SUBSTR() is a synonym for SUBSTRING().
SUBSTR(str, pos, len) e.g.
• SELECT SUBSTR ('This is the test by IWAY', 6);
• SELECT SUBSTR ('This is the test by IWAY', -4, 4);
MID(str, pos, len) MID function is a synonym for SUBSTRING.
• SELECT ename, job, IF(ISNULL(phone), '**********', RPAD(LEFT(phone, 4), 10,
'*')) FROM emp;
• SELECT `user name`, IF(LENGTH(SUBSTR(`user name`, INSTR(`user name`,"
")))=0,"Weak User", `user name`) R1 FROM emp;
• SELECT LENGTH('saleel') - LENGTH(REPLACE('saleel', 'e', ''));
• SELECT emailid, REVERSE(SUBSTR(REVERSE(emailid), 5)) FROM emp;
Mathematical Functions
Mathematical Functions
Syntax Result
ABS(x) Returns the absolute value of X.
CEIL(x) CEIL() is a synonym for CEILING().
CEILING(x) Returns CEIL value.
FLOOR(x) Returns FLOOR value.
MOD(n, m),
Returns the remainder of N divided by M. MOD(N,0) returns
n % m,
NULL.
n MOD m
POWER(x, y) This is a synonym for POW().
RAND() Returns a random floating-point value
Rounds the argument X to D decimal places. The rounding
ROUND(x) algorithm depends on the data type of X. D defaults to 0 if
ROUND(x, d) not specified. D can be negative to cause D digits left of
the decimal point of the value X to become zero.
Returns the number X, truncated to D decimal places. If D is
0, the result has no decimal point or fractional part. D can
TRUNCATE(x, d)
be negative to cause D digits left of the decimal point of
the value X to become zero.
Mathematical Functions
e.g.

• SELECT CEIL(1.23);
• SELECT CEIL(-1.23);
• SELECT FLOOR(1.23);
• SELECT FLOOR(-1.23);
• SELECT ROUND(-1.23);
• SELECT ROUND(-1.58);
• SELECT ROUND(RAND() * 100);
• SELECT FLOOR(RAND() * 899999 +100000) OTP;
• SELECT weight, TRUNCATE(weight, 0) AS kg, MID(weight, INSTR(weight, ".") + 1)
AS gms FROM mass_table;
Note:
• TABLE always displays all columns of the table.
• TABLE does not support any WHERE clause.
• TABLE can be used with temporary tables.

TABLE statement…
TABLE is a DML statement introduced in MySQL 8.0.19 which returns rows and columns of the named table.
TABLE statement
The TABLE statement in some ways acts like SELECT. You can order and limit the number of rows produced by TABLE
using ORDER BY and LIMIT clauses, respectively.

TABLE table_name [ORDER BY column_name] [LIMIT number


[OFFSET number]]

• TABLE emp;
• TABLE emp ORDER BY 2;
• TABLE emp ORDER BY 2 LIMIT 1, 2;
• TABLE t1 UNION TABLE t2;
SELECT statement… syntax
SELECT is used to retrieve rows selected from one or more tables (using JOINS), and can include
UNION statements and SUBQUERIES.
SELECT statement
syntax
modifiers
SELECT [ALL / DISTINCT / DISTINCTROW] identifier.* / identifier.A1 [ [as]
alias_name], identifier.A2 [ [as] alias_name], identifier.A3 [ [as]
alias_name], expression1 [ [as] alias_name], expression2 [ [as] alias_name]
. . .
• [ FROM <identifier.r1> [as] alias_name], <identifier.r2> [as]
alias_name], . . . ]
• [ WHERE < where_condition1 > { and | or } < where_condition2 > . . . ]
• [ GROUP BY < { col_name | expr | position }, . . . [ WITH ROLLUP ] > ]
• [ HAVING < having_condition1 > { and | or } < having_condition2
> . . . ]
Remember

:
[ ORDER BY < { col_name | expr | position } [ ASC | DESC ], . . . > ]
• ALL (modifier is default) specifies that all matching rows should be returned, including duplicates.
•• [ LIMIT
DISTINCT < { [offset,]
(modifier) row_count
specifies removal | rows
of duplicate row_count OFFSET
from the result set. offset } > ]
• DISTINCTROW (modifier) is a synonym for DISTINCT.

• [ { INTO OUTFILE 'file_name' | INTO DUMPFILE 'file_name' | INTO
It is an error to specify both modifiers.
var_name [, var_name], . . . } ]
WHERE GROUP BY HAVING ORDER BY LIMIT

SELECT statement… execution

FROM WHERE GROUP BY HAVING SELECT DISTINCT

LIMIT ORDER BY
Nulls by default occur at the top, but you can use IsNull to assign default values, that will put it in the position
you require. . The ISNULL() function tests whether an expression is NULL. If expression is a NULL value, the
ISNULL() function returns 1. Otherwise, it returns 0.

ORDER BY Clause
To sort a result, use an ORDER BY clause.

Remember:
• The default sort order is ascending ASC, with smallest values first. To sort in descending (reverse) order, add
the DESC keyword to the name of the column you are sorting by.
• You can sort on multiple columns, and you can sort different columns in different directions.
• If the ASC or DESC modifier is not provided in the ORDER BY clause, the results will be sorted by expression
in ascending order. This is equivalent to ORDER BY expression ASC.

• SELECT id AS 'a' FROM tbl_name ORDER BY `a`;


• SELECT id AS 'a' FROM tbl_name ORDER BY 'a';
SELECT - ORDER BY
When doing an ORDER BY, NULL values are placed first if you do ORDER BY ... ASC and last if you
do ORDER BY ... DESC.

SELECT A1, A2, A3, An FROM r

[ORDER BY {A1, A2, A3, . . . | expr | position} [ASC |


DESC], . . . ]
"Ordered by attributes A1, A2, A3 …"
• Tuples are sorted by specified attributes
• Results are sorted by A1 first

• Within each value of A1, results are sorted by A2 then within each value of A2, results are

sorted by A3
SELECT - ORDER BY
The ORDER BY clause is used to sort the records in your result set.

SELECT A1, A2, A3, An FROM r

[ORDER BY {A1, A2, A3, . . . | expr | position} [ASC |


DESC], . . . ]

READ SELECT ORDER BY


FROM identifier.job outp
identifier.*
emp ASC, ut
identifier.ename
DESC
READ SELECT ORDER BY
FROM identifier.job outp
identifier. *
emp DESC, ut
identifier.ename
ASC
SELECT - ORDER BY
When doing an ORDER BY, NULL values are presented first if you do ORDER BY ... ASC

• SELECT * FROM emp ORDER BY comm ASC;


SELECT - ORDER BY
When doing an ORDER BY, NULL values are presented last if you do ORDER BY ... DESC.

• SELECT * FROM emp ORDER BY comm DESC;


SELECT - ORDER BY
The ORDER BY clause is used to sort the records in your result set.

SELECT A1, A2, A3, An FROM r

[ORDER BY {A1, A2, A3, . . . | expr | position} [ASC |


DESC],
• SELECT. *.FROM
. ] emp ORDER BY comm;
• SELECT * FROM emp ORDER BY comm IS NULL ;
• SELECT * FROM emp ORDER BY comm IS NOT NULL ;
• SELECT ename, LENGTH(ename) FROM emp ORDER BY length(ename), ename DESC ;
• SELECT * FROM emp ORDER BY IF(job = 'manager', 3, IF(job = 'salesman', 2, null)) ;
• SELECT * FROM emp ORDER BY FIELD(job, 'manager', 'salesman') ;
• SELECT * FROM emp ORDER BY ISNULL(comm), comm ;
• SELECT ename `e` FROM emp ORDER BY `e` ;
• SELECT ename `e` FROM emp ORDER BY e ;
• SELECT ename 'e' FROM emp ORDER BY 'e' ;
Remember: * In SQL, a logical expression is often called
a predicate.
In WHERE clause operations can be performed using…
• CONSTANTS
• TABLE columns
• FUNCTION calls (PRE-DEFINED / UDF)

WHERE Clause
The WHERE Clause is used when you want to retrieve specific information from a table excluding
other irrelevant data.

Note:
Expressions in WHERE clause can use.
• Arithmetic operators
• Comparison operators
• Logical operators
SELECT - WHERE
We can use a conditional clause called WHERE clause to filter out results. Using WHERE clause, we can
specify a selection criteria to select required records from a table.

SELECT A1, A2, A3, . . . FROM r1, r2, r3 . . . [ WHERE


P ]
 ri are the relations (tables)

 Ai are attributes (columns)


 P is the selection predicate
Remember:
• A predicate is a condition expression that evaluates to a boolean value, either true or false.
• Predicates can be used as follows: In a SELECT statement's WHERE clause or HAVING clause to
determine which rows are relevant to a particular query.

• SELECT true, false, TRUE, FALSE, True, False;


SELECT - WHERE
SELECT A1, A2, A3, . . . FROM r1, r2, r3 . . . [ WHERE P
]
Comparison Functions and Operators
= Equal operator
> Greater than operator
>= Greater than or equal operator
< Less than operator
<= Less than or equal operator
!=, <> Not equal operator
<=> NULL-safe equal to operator

Note:
• All comparisons return FALSE when either argument is NULL, so no rows are ever selected.
SELECT - WHERE
SELECT A1, A2, A3, . . . FROM r1, r2, r3 . . . [ WHERE P
] comparison_operator:
2. 5. logical_operators
= | <=> | >= | > | <= | < | <> AND | && | OR | ||
| !=
What will be the result of the query below?

• SELECT 1 = 1; • SELECT * FROM emp WHERE ename =


• SELECT True = 1; 0;
• SELECT True = 2; • SELECT * FROM emp WHERE ename =
• SELECT True = 1;
True; • SELECT * FROM emp WHERE ename =
• SELECT 0 = 0; False;
• SELECT False = • SELECT * FROM emp WHERE ename =
False; True;
• SELECT False = 1;
SELECT - WHERE
SELECT A1, A2, A3, . . . FROM r1, r2, r3 . . . [ WHERE P
]
Logical Operators
AND, && Logical AND e.g. SELECT 1 AND 1;
OR, || Logical OR e.g. SELECT 1 OR 1;
NOT, ! Negates value e.g. SELECT NOT 1;

• Logical AND. Evaluates to 1 if all operands are nonzero and not NULL, to 0 if one or more operands are 0,
otherwise NULL is returned.

• Logical OR. When both operands are non-NULL, the result is 1 if any operand is nonzero, and 0 otherwise.
With a NULL operand, the result is 1 if the other operand is nonzero, and NULL otherwise. If both operands are
NULL, the result is NULL.

• Logical NOT. Evaluates to 1 if the operand is 0, to 0 if the operand is nonzero, and NOT NULL returns NULL.
SELECT - WHERE
SELECT A1, A2, A3, . . . FROM r1, r2, r3 . . . [ WHERE P
]
Comparison Functions and Operators
IS NULL / IS UNKNOWN NULL value test
IS NOT NULL / IS NOT
NOT NULL value test
UNKNOWN
If expr is NULL, ISNULL() returns 1, otherwise it
ISNULL(expr)
returns 0.
LEAST(value1, With two or more arguments, returns the smallest
value2, . . .) argument.
GREATEST(value1, value2, . With two or more arguments, returns the largest
SELECT
. .) GREATEST(10, 20, 30), argument.
# 30
LEAST(10, 20, 30); # 10

SELECT GREATEST(10, null, 30), # null


LEAST(10, null , 30); # null
SELECT - WHERE
SELECT A1, A2, A3, . . . FROM r1, r2, r3 . . . [ WHERE P
]
Comparison Functions and Operators
Check whether a value is within a range of
BETWEEN . . . AND . . .
values
Check whether a value is not within a range
NOT BETWEEN . . . AND . . .
of values
Check whether a value is within a set of
expr IN (value, . . .)
values
Check whether a value is not within a set of
expr NOT IN (value, . . .)
values
Pattern matching using an SQL pattern.
expr LIKE 'pattern' [ ESCAPE
Returns 1 (TRUE) or 0 (FALSE). If either
'escape_char' ]
expr or pat is NULL, the result is NULL.
expr NOT LIKE 'pattern' [ ESCAPE
Negation of simple pattern matching.
'escape_char' ]
SELECT - WHERE
• SELECT * FROM emp WHERE job = 'MANAGER' job
= 'SALESMAN';

READ WHERE SELECT


FROM outp
identifier.job = identifier.*
emp ut
'MANAGER' or
identifier.job =
'SALESMAN'
• SELECT * FROM emp WHERE comm IS UNKNOWN; • operand IS [NOT] NULL
• SELECT * FROM emp WHERE comm IS NOT UNKNOWN;

3. boolean_
predicate:
IS [NOT] NULL
| expr <=> null
IS NULL / IS NOT NULL
• "IS NULL" is the keyword that performs the Boolean comparison. It returns true if the supplied
value is NULL and false if the supplied value is not NULL.
• “IS NOT NULL" is the keyword that performs the Boolean comparison. It returns true if the
supplied value is not NULL and false if the supplied value is null.

Note:
• IS UNKNOWN is synonym of IS NULL.
• IS NOT UNKNOWN is synonym of IS NOT NULL.
IS NULL / IS NOT NULL
SELECT * FROM emp WHERE comm = NULL; # Empty
set

• SELECT empno, ename, job, sal, comm


FROM emp WHERE comm IS NOT NULL;

• SELECT empno, ename, job, sal, comm


FROM emp WHERE comm is TRUE;
SELECT – Boolean
• BOOL and BOOLEAN are synonym of TINYINT(1)

A value of zero is considered false. Nonzero values


are considered true.
SELECT true, false, TRUE, FALSE, True, False;

• SELECT * FROM tasks WHERE completed;


• SELECT * FROM tasks WHERE completed is
True;
• SELECT * FROM tasks WHERE completed =
1;
• SELECT * FROM tasks WHERE completed =
True;
• SELECT * FROM tasks WHERE NOT
completed;
• SELECT * FROM tasks WHERE completed is
False;
SELECT – Boolean
• BOOL and BOOLEAN are synonym of TINYINT(1)

A value of zero is considered false. Nonzero values


are considered true.
SELECT true, false, TRUE, FALSE, True, False;

What will be the result of the query below?

• SELECT * FROM emp WHERE 1; • SELECT * FROM emp WHERE ename =


• SELECT * FROM emp WHERE True; 'smith' OR True;
• SELECT * FROM emp WHERE 0; • SELECT * FROM emp WHERE ename =
• SELECT * FROM emp WHERE False; 'smith' AND True;
• SELECT * FROM emp WHERE ename = '' OR 0;• SELECT * FROM emp WHERE ename
• SELECT * FROM emp WHERE ename = '' OR 1; IN('smith', True);
• SELECT * FROM emp WHERE ename = '' OR 1 •= SELECT
1; * FROM emp WHERE ename =
'smith' OR False;
• SELECT * FROM emp WHERE ename =
READ WHERE SELECT
FROM outp
identifier.state identifier.*
states ut
IN ('VT',
'NH', . . .)
4. predicate:

IN
expr [NOT] IN expr AND
predicate
| expr [NOT] IN (subquery)
The IN statement is used in a WHERE clause to choose items from a set. The IN operator allows you
to determine if a specified value matches any value in a set of values or value returned by a
subquery.
SELECT . . . FROM r1
WHERE (
state = 'VT' OR
state = 'NH' OR • SELECT . . . FROM r1 WHERE state IN ('VT', 'NH',
state = 'ME' OR 'ME', 'MA', 'CT', 'RI');
state = 'MA' OR • SELECT . . . FROM r1 WHERE state IN
state = 'CT' OR
(SELECT . . . );
state = 'RI'
);
IN
syntax
column | expression IN ( v1, v2, v3, . . . )
column | expression IN (subquery)

Remember:
• If a value in the column or the expression is equal to any value in the list, the result of the IN operator is TRUE.
• The IN operator is equivalent to multiple OR operators.
• To negate the IN operator, you use the NOT IN operator.

• SELECT empno, ename, job, hiredate, sal, comm, deptno, isactive FROM emp WHERE
job IN ('salesman', 'manager');
Remember: IN
• On the left side of the IN() predicate, the row constructor contains only column references.
• On the right side of the IN() predicate, there is more than one row constructor.

What will be the result of the query below?


• SELECT * FROM emp WHERE deptno IN (10);
• SELECT * FROM emp WHERE deptno IN (10, 20);
• SELECT * FROM emp WHERE False IN (10, 20, 0);
• SELECT * FROM emp WHERE True IN (10, 20, 1);
• SELECT * FROM emp WHERE 10 IN (10, 20);
• SELECT * FROM emp WHERE 1 IN (10, 20, True, False);
• SELECT * FROM emp WHERE deptno IN (10, 20) OR True;
• SELECT * FROM emp WHERE deptno IN (10, 20) AND True;
• SELECT * FROM emp WHERE deptno IN (SELECT deptno FROM dept);
• SELECT * FROM emp WHERE deptno IN (SELECT deptno FROM dept WHERE
dname='accounting');
READ WHERE SELECT
FROM output
identifier.sal identifier.*
emp
BETWEEN
1000 and 3000
4. predicate:
expr [NOT] BETWEEN expr
[ESCAPE expr]
between
The BETWEEN operator is a logical operator that allows you to specify a range to test.
between
syntax
column | expression BETWEEN start_expression AND
end_expression
Remember:
• The BETWEEN operator returns TRUE if the expression to test is greater than or equal to the value of the
start_expression and less than or equal to the value of the end_expression.
• You can use the greater than or equal to (>=) and less than or equal to (<=) to substitute the BETWEEN
operator.

Note:
• if any input to the BETWEEN or NOT BETWEEN is NULL, then the result is UNKNOWN.
e.g.
SELET empno, ename, job, hiredate, sal, comm, deptno, isactive FROM emp
WHERE sal BETWEEN 1000 AND NULL;

• SELECT * FROM salespeople WHERE FORMAT(comm, 2) > 0.1 AND FORMAT(comm, 2) <
0.26;
between
• SELECT empno, ename, job, hiredate, sal, comm, deptno, isactive FROM emp WHERE
sal BETWEEN 1000 AND 3000;
READ WHERE SELECT
FROM output
identifier.ename identifier.*
emp
LIKE 'a%'

4. predicate:
expr [NOT] LIKE (expr [,
expr] ...)
Like
The LIKE operator is a logical operator that tests whether a string contains a specified pattern or not.
Like - String Comparison Functions
syntax
column | expression LIKE 'pattern' [ESCAPE
escape_character]
Remember:
• % matches any number of characters, even zero characters.
• _ matches exactly one character.
• If we use default escape character '\', then don’t use ESCAPE keyword.

Note:
• The ESCAPE keyword is used to escape pattern matching characters such as the (%) percentage and
underscore (_) if they form part of the data.
• If you do not specify the ESCAPE character, \ is assumed.
like
• SELECT empno, ename, job, hiredate, sal, comm, deptno, isactive FROM emp WHERE
ename LIKE 'a%';
like
What will be the result of the query below?

• SELECT * FROM emp WHERE ename LIKE 's%';


• SELECT * FROM emp WHERE 'saleel' LIKE 's%';
• SELECT * FROM emp WHERE True LIKE '1';
• SELECT * FROM emp WHERE True LIKE '1%';
• SELECT * FROM emp WHERE True LIKE 001;
• SELECT * FROM emp WHERE True LIKE 100;
• SELECT * FROM emp WHERE False LIKE 100 OR 0;
• SELECT * FROM emp WHERE False LIKE 0 AND 1;
Row Limiting Clause
LIMIT is applied after HAVING

Remember:
• LIMIT enables you to pull a section of rows from the middle of a result set. Specify two values: The number
of rows to skip at the beginning of the result set, and the number of rows to return.

Note:
• Limit value are not to be given within ( . . . )
• Limit takes one or two numeric arguments, which must both be non-negative integer value.
SELECT - LIMIT
SELECT A1, A2, A3, . . . FROM r
[ LIMIT { [offset,] row_count | row_count OFFSET offset } ]
You can specify an offset using OFFSET from where SELECT will start returning records.
By default offset is zero.

• SELECT * FROM emp LIMIT 5 OFFSET 1;

READ SELECT LIMIT


FROM output
identifier.* 1, 5 | 5
emp offset 1

• SELECT * FROM student LIMIT 5;


• SELECT * FROM student LIMIT 1, 5;
• SELECT * FROM student LIMIT 5 offset 1;
• SELECT rand(), student.* FROM student ORDER BY 1 LIMIT 1;
• SELECT student.* FROM student ORDER BY RAND() LIMIT 1;
SELECT - LIMIT
This variable is used to return the maximum number of rows from SELECT statements. Its default value is
unlimited. But if you changed the limit then SELECT statement returns the rows equals to the value.

SQL_SELECT_LIMIT = { value | DEFAULT }

This variable does not apply to SELECT statement that executed in the stored procedures or functions.

• SET SQL_SELECT_LIMIT=2;
• SET SQL_SELECT_LIMIT=DEFAULT;

• SELECT * FROM emp;


READ GROUP BY SELECT
FROM output
identifier.job AVG(sal), SUM(sal),
emp
MAX(sal), MIN(sal),

aggregate functions
COUNT(*)

• SET sql_mode = ' '; # ERROR


• SET sql_mode = IGNORE_SPACE;

• SELECT empno, ename, sal, deptno FROM emp WHERE sal =


MAX(sal); #error
• SELECT empno, ename, sal, deptno FROM emp WHERE
Remember:
MAX(sal) = sal; #error
None of the above two queries get executed successfully. The reason is that a condition in a WHERE clause
cannot contain any aggregate function (or group function) without a subquery!
aggregate functions
Remember:
There are 3 places where aggregate functions can appear in a query.
• in the SELECT-LIST/FIELD-LIST (the items before the FROM clause).
• in the ORDER BY clause.
• in the HAVING clause.

Note:
• The aggregate functions allow you to perform the calculation of a set of rows and return a single value.
• The WHERE clause cannot refer to aggregate functions. WHERE SUM(sal) = 5000 # Error
• The HAVING clause can refer to aggregate functions. HAVING SUM(sal) = 5000 # No Error
• Nesting of aggregate function is also not allowed.
e.g.
SELECT MAX(COUNT(*)) FROM emp GROUP BY deptno;
• Blank space between aggregate functions like (SUM, MIN, MAX, COUNT) are not allowed.
e.g.
SELECT SUM (sal) FROM emp;
• The GROUP BY clause is often used with an aggregate function to perform calculation and return a single
value for each subgroup.
Things to… Remember: aggregate functions
TODO

AVG([DISTINCT] expr)
• If there are no matching rows, AVG() returns NULL.
• AVG() may take a numeric argument, and it returns a average of non-NULL values.

e.g.
• SELECT AVG(1) "R1";
• SELECT AVG(null) "R1";
• SELECT AVG(1) "R1" WHERE True;
• SELECT AVG(1) "R1" WHERE False;
• SELECT AVG(1) "R1" FROM emp;
• SELECT AVG(sal) "R1" FROM emp WHERE empno = -1;
• SELECT AVG(sal) "Avg Salary" FROM emp;
• SELECT job, AVG(sal) "Avg Salary" FROM emp GROUP BY job;
Things to… Remember: aggregate functions
TODO sal = { 1, 2, -1,
SUM([DISTINCT] expr)
3, -2, 1 }
• SELECT SUM(sal)
• If there are no matching rows, SUM() returns NULL.
• SUM() may take a numeric argument , and it returns a sum of non-NULL values. "R1"

e.g.
• SELECT SUM(1) "R1";
• SELECT SUM(null) "R1";
• SELECT SUM(2 + 2 * 2);
• SELECT SUM(1) "R1" WHERE True;
• SELECT SUM(1) "R1" WHERE False;
• SELECT SUM(1) "R1" FROM emp;
• SELECT SUM(sal) "R1" FROM emp WHERE empno = -1;
• SELECT SUM(sal) "Total Salary" FROM emp;
• SELECT job, SUM(sal) "Total Salary" FROM emp GROUP BY job;
Things to… Remember: aggregate functions
TODO

MAX([DISTINCT] expr)
• If there are no matching rows, MAX() returns NULL.
• MAX() may take a string, number, and date argument, and it returns a maximum of non-NULL values.

e.g.
• SELECT MAX(1) "R1";
• SELECT MAX(null) "R1";
• SELECT MAX('VIKAS');
• SELECT MAX(1) "R1" WHERE True;
• SELECT MAX(1) "R1" WHERE False;
• SELECT MAX(1) "R1" FROM emp;
• SELECT MAX(sal) "R1" FROM emp WHERE empno = -1;
• SELECT MAX(sal) "Maximum Salary" FROM emp;
• SELECT job, MAX(sal) "Maximum Salary" FROM emp GROUP BY job;
Things to… Remember: aggregate functions
TODO

MIN([DISTINCT] expr)
• If there are no matching rows, MIN() returns NULL.
• MIN() may take a string, number, and date argument, and it returns a minimum of non-NULL values.

e.g.
• SELECT MIN(1) "R1";
• SELECT MIN(null) "R1";
• SELECT MIN(1) "R1" WHERE True;
• SELECT MIN(1) "R1" WHERE False;
• SELECT MIN(1) "R1" FROM emp;
• SELECT MIN(sal) "R1" FROM emp WHERE empno = -1;
• SELECT MIN(sal) "Minimum Salary" FROM emp;
• SELECT job, MIN(sal) "Minimum Salary" FROM emp GROUP BY job;
Things to… Remember: aggregate functions
TODO

COUNT(DISTINCT expr)
• If there are no matching rows, COUNT() returns 0.
• Returns a count of the number of non-NULL values.
• COUNT(*) is somewhat different in that it returns a count of the number of rows retrieved, whether or not they
contain NULL values.
• COUNT (*) is a special implementation of the COUNT function that returns the count of all the rows in a
specified table.
• COUNT (*) also considers Nulls and duplicates.
e.g.
• SELECT COUNT(*) "R1";
• SELECT COUNT(null) "R1";
• SELECT COUNT(*) "R1" WHERE True;
• SELECT COUNT(*) "R1" WHERE False;
• SELECT COUNT(0) FROM emp;
• SELECT COUNT(1) FROM emp;
• SELECT COUNT(*) FROM emp WHERE empno = -1;
• SELECT COUNT(comm) "R1" FROM emp;
• SELECT job, COUNT(*) "R1" FROM emp GROUP BY job;
Things to… Remember: aggregate functions
TODO

GROUP_CONCAT([DISTINCT] expr
[ORDER BY {unsigned_integer | col_name |
expr} [ASC | DESC] [,col_name . . .]]
[SEPARATOR str_val])
e.g.
• SELECT job, GROUP_CONCAT(ename) FROM emp GROUP BY job;
G G (r)
A1, A2, . . ., An, F1(A1), F2(A2), . . ., Fm(Am)
GROUP BY Clause
Remember:
• Standard SQL does not allow you to use an ALIAS in the GROUP BY clause, however, MySQL supports this.

Note:
• DISTINCT (if used outside an aggregation function) that is superfluous.
e.g.
SELECT DISTINCT COUNT(ename) FROM emp;
SELECT - GROUP BY
• Columns selected for output can be referred to in ORDER BY and GROUP BY clauses using column names,
column aliases, or column positions. Column positions are integers and begin with 1

• If you use GROUP BY, output rows are sorted according to the GROUP BY columns as if you had an ORDER
BY for the same columns. To avoid the overhead of sorting that GROUP BY produces, add ORDER BY NULL.

• MySQL extends the GROUP BY clause so that you can also specify ASC and DESC after columns named in
the clause

• If a query includes GROUP BY but you want to avoid the overhead of sorting the result, you can suppress
sorting by specifying ORDER BY NULL.

For example:
• SELECT job, COUNT(*) FROM emp GROUP BY job ORDER BY NULL;
• SELECT * FROM emp ORDER BY FIELD (job, 'MANAGER',
'SALESMAN');
This function's will produce a single value for an
entire group or a table.
SELECT - GROUP BY
You can use GROUP BY to group values from a column, and, if you wish, perform calculations on that
column.

SELECT G1, G2, . . . , F1(A1), F2(A2), . . . FROM r1, r2,

r3 . . .
• SELECT job, SUM(sal) FROM emp GROUP BY job;
[GROUP
• SELECT BY {G1, G2, FROM
job, SUM(sal)
. .emp
. |GROUP
exprBY| job
position},
WITH
. . .
ROLLUP;
[WITH ROLLUP]]
READ GROUP BY SELECT
FROM jo output
identifier.job identifier.Job,
emp b
SUM(sal)
SELECT - GROUP BY
Examples:

• SELECT job, sal + 1001 FROM emp GROUP BY job;


• SELECT job, COUNT(job) FROM emp GROUP BY COUNT(job); # error
• SELECT job, sal + 1001 FROM emp GROUP BY sal + 1001;
• SELECT ename, LENGTH(ename) R1 FROM emp GROUP BY R1;
• SELECT job, SUM(sal) FROM emp GROUP BY job WITH ROLLUP;
• SELECT COALESCE (job, 'Total'), SUM(sal) FROM emp GROUP BY job WITH ROLLUP;

• SET sql_mode = '';


• SET sql_mode = 'ONLY_FULL_GROUP_BY';
Remember:
• The WHERE clause cannot refer to aggregate functions. WHERE SUM(sal) = 5000 # Error
• The HAVING clause can refer to aggregate functions. HAVING SUM(sal) = 5000 # No Error

HAVING Clause
The MySQL HAVING clause is used in the SELECT statement to specify filter conditions for a group
of rows. HAVING clause is often used with the GROUP BY clause. When using with the GROUP
BY clause, we can apply a filter condition to the columns that appear in the GROUP BY clause.

Note:
• HAVING is merged with WHERE if you do not use GROUP BY or Aggregate Functions (COUNT(), MIN(),
and so on).
SELECT - HAVING
SELECT G1, G2, . . . , F1(A1), F2(A2), . . . from r1, r2,

r3 . . .

[GROUP BY {G1, G2, . . . | expr | position}, . . . [WITH


• SELECT COUNT(*), job FROM emp GROUP BY job HAVING
ROLLUP]]
COUNT(*) > 2;
[ HAVING having_condition ]
READ GROUP HAVING SELECT
FROM identifier. COUNT(*) > identifier. output
emp BY
job 2 job,
COUNT(*)
When WHERE and HAVING clause are used together in a SELECT query with aggregate function,
WHERE clause is applied first on individual rows and only rows which pass the condition is
included for creating groups. Once group is created, HAVING clause is used to filter groups based
upon condition specified.

Difference between WHERE and


HAVING clause
WHERE and HAVING clause

Remember:
• WHERE clause can be used with - SELECT, UPDATE, and DELETE statements, where as HAVING
clause can only be used with the SELECT statement.
• WHERE clause filters rows before aggregation (GROUPING), where as, HAVING clause filters groups,
after the aggregations are performed.
• Aggregate functions (SUM , MIN, MAX, AVG and COUNT) cannot be used in the WHERE clause, unless
it is in a sub query contained in a WHERE or HAVING clause, whereas, aggregate functions can be used
in HAVING clause.

Note:
• The WHERE clause acts as a pre-filter where as HAVING clause acts as a post-filter.
WHERE Vs HAVING
WHERE VS HAVING

WHERE HAVING
Implemented in row operations. Implemented in column operations.
Single row Summarized row or group or rows.
It only fetches the data from particular rows or table It only fetches the data from grouped data according to
according to the condition. the condition.

Aggregate Functions ccannot appear in WHERE clause. Aggregate Functions Can appear in HAVING clause.
Used with SELECT and other statements such as Used with SELECT statement only.
UPDATE, DELETE or either one of them.

Pre-filter Post-filter
GROUP BY Comes after WHERE. GROUP BY Comes before HAVING.
window function
FIFA / Forbes window function

• RANK() OVER(PARTITION BY expr [, expr] . . . ORDER BY expr [ASC | DESC] [, expr


[ASC | DESC]] . . . )

• DENSE_RANK() OVER(PARTITION BY expr [, expr] . . . ORDER BY expr [ASC|DESC] [,


expr [ASC | DESC]] . . . )

• ROW_NUMBER() OVER(PARTITION BY expr [, expr] . . . ORDER BY expr [ASC|DESC] [,


expr [ASC | DESC]] . . . )

Note:
MySQL does not support these window function features.
• DISTINCT syntax for aggregate functions.
• Nested window functions
User-Defined Variables
User-Defined Variables

Remember:
• A user variable name can contain other characters if you quote it as a string or identifier (for example,
@'my-var', @"my-var", or @`my-var`).
• User-defined variables are session specific. A user variable defined by one client cannot be seen or used by
other clients.
• All variables for a given client session are automatically freed when that client exits.
• User variable names are not case sensitive. Names have a maximum length of 64 characters.
• If the value of a user variable is selected in a result set, it is returned to the client as a string.
• If you refer to a variable that has not been initialized, it has a value of NULL and a type of string.
User-Defined Variables
You can store a value in a user-defined variable in one statement and refer to it later in another statement. This
enables you to pass values from one statement to another.

SET @variable_name = expr [, @variable_name = expr]


. . .
Remember:
• for SET, either = or := can be used as the assignment operator.
• You can also assign a value to a user variable in statements (SELECT, …) other than SET. In this case, the
assignment operator must be := and not = because latter is treated as the comparison operator =.

• set @v1 = 1001, @v2 := 2, @v3 = 'Saleel';


• set @v1 = 1001, @v2 = 2, @v3 := @v1 + @v2;
• SELECT @v1 := MIN(sal), @v2 := MAX(SAL) FROM emp;
• SELECT @v1, @v2, @v3;
User-Defined Variables
Note:
• User variables are intended to provide data values. They cannot be used directly in an SQL statement as an
identifier or as part of an identifier.
e.g.
SET @v1 = 'ENAME'; #WHERE ENAME IS COLUMN NAME.
SELECT @v1 FROM emp;
Rownum
mysql> SELECT * FROM (SELECT @cnt := @cnt + 1 "R1", emp.* FROM emp, (SELECT @cnt :=
0) T1) T2 WHERE "R1" > @cnt - 7;
Select - Rownum
mysql> set @rank = 0;
mysql> SELECT @row := @row + 1 as rownum , emp.* FROM emp;
mysql> SELECT @row := @row + 1 as rownum , emp.* FROM emp, (SELECT @row := 0) as
E;
mysql> SELECT @row := @row + 1 ,E.* FROM (SELECT job, sal FROM emp GROUP BY job
ORDER BY SAL DESC) E , (SELECT @row := 0) EE;
Remember:
• A subquery must be enclosed in parentheses.
• Use single-row operators with single-row subqueries, and use multiple-row operators with multiple-row
subqueries.
• If a subquery (inner query) returns a null value to the outer query, the outer query will not return any rows
when using certain comparison operators in a WHERE clause.
• If ORDER BY occurs within a subquery and also is applied in the outer query, the outermost ORDER BY
takes precedence.
• If LIMIT occurs within a subquery and also is applied in the outer query, the outermost LIMIT takes
precedence.

Sub-Queries
A subquery is a SELECT statement within another statement.
Note:
• You may use comparison operators such as <>, <, >, <=, and >= with a single row subquery.
• Multiple row subquery returns one or more rows to the outer SQL statement. You may use the IN, ANY, or
ALL operator in outer query to handle a subquery that returns multiple rows.
A subquery is a SELECT statement within another statement. Subqueries
Remember:
A subquery may occur in:
• A SELECT clause
• A FROM clause
• A WHERE clause
• A HAVING clause

Note:
A subquery's outer statement can be any one of :
• SELECT
• INSERT
• UPDATE
• DELETE
Single Row Subqueries
A single row subquery returns zero or one row to the outer SQL statement. You can place a
subquery in a WHERE clause, a HAVING clause, or a FROM clause of a SELECT statement.

Outer Query Subquery or Inner query


Multiple Row and Column Subqueries
A multiple row subquery returns one or more rows to the outer SQL statement.
You may use the IN, ANY, or ALL operator in outer query to handle a subquery
that returns multiple rows.

Outer Query Subquery or Inner query


Types of Subqueries

• The Subquery as Scalar Operand – SELECT clause

• Comparisons using Subqueries – WHERE / HAVING clause (Single row subquery)

• Subqueries in the FROM Clause – Inline Views (Derived Tables)

• Subqueries with ALL, ANY, IN, or SOME – WHERE / HAVING clause (Multiple row subquery)

• Subqueries with EXISTS or NOT EXISTS

• Row Subqueries
The Subquery as Scalar Operand
The Subquery as Scalar Operand
syntax
SELECT A1, A2, A3, (subquery) as A4, . . . FROM r

Remember:
• A scalar subquery is a subquery that returns exactly one column value from one row.
• A scalar subquery is a simple operand, and you can use it almost anywhere a single column value is legal.

Note:
• If the subquery returns 0 rows then the value of scalar subquery expression is null.
• if the subquery returns more than one row then MySQL returns an error.

Think:
• SELECT (SELECT 1, 2); #error
• SELECT (SELECT ename, sal FROM emp); #error
• SELECT (SELECT * FROM emp); #error
• SELECT (SELECT NULL + 1);
• SELECT ename, (SELECT dname FROM dept WHERE emp.deptno = dept.deptno) R1 FROM
emp ;
The Subquery as Scalar Operand
e.g.
• SELECT (SELECT stdprice FROM price WHERE prodid = 100890 and enddate IS NOT
NULL) AS "Standard Price", (SELECT minprice FROM price WHERE prodid = 100890
and enddate IS NOT NULL) AS "Minimum Price";

• SELECT (SELECT stdprice FROM price WHERE prodid = 100890 and enddate IS NOT
NULL) - (SELECT minprice FROM price WHERE prodid = 100890 and enddate IS NOT
NULL) AS "Price Difference";
Subquery in the FROM Clause
Subqueries in the FROM Clause
syntax
SELECT A1, A2, A3, (subquery) as A4, . . . FROM (subquery) [AS] name . . .

Note:
• Every table in a FROM clause must have a name, therefore the [AS] name clause is mandatory.

• SET @x :=0;
SELECT * FROM (SELECT @x := @x + 1 as R1, emp.* FROM emp) DT WHERE R1 = 5;
• SELECT * FROM (SELECT @cnt := @cnt + 1 R1, MOD(@cnt,2) R2, emp.* FROM emp, (SELECT
@cnt:=0) DT1 ) DT2 WHERE R2 = 0;
• SELECT MIN(R1) FROM (SELECT COUNT(job) R1 FROM emp GROUP BY job) DT;
• SELECT MAX(R1) FROM (SELECT COUNT(*) R1 FROM actor_movie GROUP BY actorid) DT

SELECT AVG(SUM(column1)) FROM t1 GROUP BY column1;

SELECT AVG(sum_column1)
FROM (SELECT SUM(column1) AS
sum_column1
Comparisons using Subquery
Comparisons using Subqueries
Comparison Operators like : =, !=/<>, >, >=, <, <= ,<=>
syntax
SELECT A1, A2, A3, (subquery) as A4, . . . FROM r WHERE p =
(subquery)
Remember:
• A subquery can be used before or after any of the comparison operators.
• The subquery can return at most one value.
• The value can be the result of an arithmetic expression or a function.

• SELECT * FROM emp WHERE deptno = (SELECT 5 + 5);


• SELECT * FROM emp WHERE sal = (SELECT MAX(sal) FROM emp);

Following statements will raise an error.


• SELECT * FROM emp WHERE deptno = (SELECT deptno FROM dept WHERE deptno in (10,
20));
Comparisons using Subqueries
movie : (movieid, name, release_date)
actor : (actorid, name) Actor Movie
actor_movie : (actorid, movieid)

Movie _Actor

• SELECT a.actorid, a.name FROM actor a, actor_movie am WHERE a.actorid =


am.actorid GROUP BY am.actorid HAVING COUNT(*) = (SELECT MAX(R1) FROM (SELECT
COUNT(*) "R1" FROM actor_movie GROUP BY actorid) M);
When used with a subquery, the word IN is an alias for =ANY.

NOT IN is not an alias for <>ANY, but for <>ALL.

Subquery with IN, ALL, ANY, or


SOME
Subqueries with IN, ALL, ANY, or SOME
• operand comparison_operator ANY (subquery) The word SOME is an alias for ANY.
• operand IN (subquery)
• operand comparison_operator SOME (subquery)
• operand comparison_operator ALL (subquery)

• The ANY keyword, which must follow a comparison operator, means return TRUE if the comparison is TRUE
for ANY of the values in the column that the subquery returns.

• The word ALL, which must follow a comparison operator, means return TRUE if the comparison is TRUE for
ALL of the values in the column that the subquery returns.

• IN and =ANY are not synonyms when used with an expression list. IN can take an expression list, but = ANY
cannot.

• SELECT * FROM emp WHERE deptno IN (5+5, 10+10);


• SELECT * FROM emp WHERE job =ANY (SELECT job FROM emp WHERE deptno IN(10,
20)) ;
• SELECT * FROM emp WHERE deptno =ANY (10, 20); //error
any / some
 "x = ANY (...)": The value must match one or more values in the list to evaluate to TRUE.
 "x != ANY (...)": The value must not match one or more values in the list to evaluate to TRUE.
 "x > ANY (...)": The value must be greater than the smallest value in the list to evaluate to TRUE.
 "x < ANY (...)": The value must be smaller than the biggest value in the list to evaluate to TRUE.
 "x >= ANY (...)": The value must be greater than or equal to the smallest value in the list to evaluate to TRUE.
 "x <= ANY (...)": The value must be smaller than or equal to the biggest value in the list to evaluate to TRUE.
all
 "x = ALL (...)": The value must match all the values in the list to evaluate to TRUE.
 "x != ALL (...)": The value must not match any values in the list to evaluate to TRUE.
 "x > ALL (...)": The value must be greater than the biggest value in the list to evaluate to TRUE.
 "x < ALL (...)": The value must be smaller than the smallest value in the list to evaluate to TRUE.
 "x >= ALL (...)": The value must be greater than or equal to the biggest value in the list to evaluate to TRUE.
 "x <= ALL (...)": The value must be smaller than or equal to the smallest value in the list to evaluate to TRUE.
all

empty table
The expression is TRUE, if table T2 is empty.

SELECT * FROM EMP WHERE DEPTNO >ALL (SELECT C1 FROM T2) //


This statement will return all rows from EMP table.
Subqueries with IN, ALL, ANY, or SOME

You can use a subquery after a comparison operator, followed by the keyword IN, ALL, ANY, or SOME.

• SELECT * FROM emp WHERE deptno IN (SELECT deptno FROM emp WHERE deptno = 10 or
deptno = 20);
• SELECT * FROM emp WHERE sal >ALL (SELECT sal FROM emp WHERE ename = 'ADAMS' or
ename = 'TURNER');
• SELECT * FROM emp WHERE sal >ANY (SELECT sal FROM emp WHERE ename = 'ADAMS' or
ename = 'TURNER');
•SELECT
SELECT * FROM
* FROM emp WHERE
d1 WHERE sal
c1 not in >SOMEmin(c1)
(SELECT (SELECT sal
FROM FROM emp
d1 GROUP WHEREdname,
BY deptno, enameloc,=walletid)
'ADAMS' or
ORDER
BYename
deptno; = 'TURNER');
Row Subquery
Row Subqueries
Scalar or column Subqueries return a single value or a column of values. A row subquery is a subquery
variant that returns a single row and can thus return more than one column value. You can use = , >, <,
>=, <=, <>, !=, <=>

1. SELECT * from EMP where deptno, 1 = (SELECT deptno, 1 from DEPT where
deptno=10);

2. SELECT * FROM emp WHERE ROW (deptno, 1) = (SELECT deptno, 1 FROM dept WHERE
deptno = 10);
Subquery with EXISTS or NOT
EXISTS
Subqueries with EXISTS or NOT EXISTS
The EXISTS operator tests for the existence of rows in the results set of the subquery. If a subquery row value
is found, EXISTS subquery is TRUE and in this case NOT EXISTS subquery is FALSE.

• SELECT * FROM emp WHERE EXISTS (SELECT * FROM dept WHERE emp.deptno =
dept.deptno);
• SELECT * FROM emp WHERE NOT EXISTS (SELECT deptno FROM emp WHERE emp.deptno =
dept.deptno);
• SELECT * FROM emp m WHERE EXISTS (SELECT * FROM emp e WHERE e.mgr = m.empno);
• SELECT * FROM emp m WHERE NOT EXISTS (SELECT * FROM emp e WHERE e.mgr =
m.empno);
JOINS
JOINS

JOINS are used to retrieve data from


multiple tables.

JOIN is performed whenever two or more tables


are joined in a SQL statement.
JOINS
Type of JOINS

• Cartesian or Product Join – Cross Join

• Equijoin – Inner Join

• Natural Join

• Simple Join

• Outer Join – Right Outer Join, Left Outer Join

• Self Join
Cartesian or Product JOIN
• Cartesian/Product means Number of Rows present in Table 1 Multiplied by Number of Rows present in
Table 2.

• Cross Join in MySQL does not require any common column to join two table.
JOINS - Cartesian or Product
The CROSS JOIN gets a row from the first table (r1) and then creates a new row for every row in the second
table (r2). It then does the same for the next row for in the first table (r1) and so on.

r1 r2
Customer-1 Supplier-1 Customer-1 Supplier-1
Customer-1 Supplier-2
Cusomer-2 cross join Supplier-2 Customer-1 Supplier-3
= Cusomer-2 Supplier-1
Customer-3 Supplier-3
Cusomer-2 Supplier-2
Cusomer-2 Supplier-3
Customer-3 Supplier-1
Customer-3 Supplier-2
Customer-3 Supplier-3
JOINS - Cartesian or Product
The CROSS JOIN gets a row from the first table (r1) and then creates a new row for every row in the second
table (r2). It then does the same for the next row for in the first table (r1) and so on.
JOINS - Cartesian or Product
Cartesian or Product joins are joins without a join condition. Each row of one table is combined with each row of
another table. The result is referred to as a Cartesian product.

SELECT A1, A2, A3, . . . FROM r1, r2, . . .

r1 = {1, 2} r1 = {1, 2, 3} r1 = {1, 2}


r2 = {a, b, c} r2 = {a, b} r2 = {a, b, null}
r1 x r2 r1 x r2 r1 x r2
R = { (1, a), R = { (1, a), R = { (1, a),
(2, (1, (2, a),
a), b), (1, b),
(1, (2, (2, b),
b), a), (1,
(2, (2, null),
b), b), (2,
JOINS - Cartesian or Product
Cartesian or Product joins are joins without a join condition. Each row of one table is combined with each row of
another table. The result is referred to as a Cartesian product.

SELECT A1, A2, A3, . . . FROM r1, r2, . . .

• Warehouse/ X
product
• Product/
sales_channel
• Cards
JOINS - Cartesian or Product
SELECT A1, A2, A3, . . . FROM r1, r2, . . .
• SELECT * FROM menucard, softdrink;
JOINS - Cartesian or Product
SELECT A1, A2, A3, . . . FROM r1, r2, . . .
• SELECT mnu.name, sftdrink.name, mnu.rate, sftdrink.rate, mnu.rate + sftdrink.rate
as "Total" FROM menucard mnu, softdrink sftdrink;
JOINS - Cartesian or Product
• SELECT name, COUNT(*) "Total Employees", rate * COUNT(*) "Total Cost" FROM emp,
softdrink GROUP BY name;
JOINS – Cross Join
The CROSS JOIN produced a result set which is the product of rows of two associated tables when no WHERE
clause is used with CROSS JOIN. In this join, the result set appeared by multiplying each row of the first table
with all rows in the second table if no condition introduced with CROSS JOIN.

SELECT A1, A2, A3, . . . FROM r1 CROSS JOIN r2, . . .

envelope docs
Table Table

SELECT * FROM envelope CROSS JOIN docs;


equi JOIN
An equi join / Inner Join is a join with a join condition containing an equality operator.
An equijoin returns only those rows that have equivalent values for the specified columns. Rows
that match remain in the result, those that don't are rejected. The match condition is commonly
called the join condition. equi join / Inner Join returns rows when there is at least one match in
both tables.
equi join example
The following table illustrates the inner join of two tables r1(C-1, C-2, C-3, C-4) and r2(CO-1, CO-2, CO-1,
CO-2, CO-3, CO-1). The result includes rows: (C-1, CO-1), (C-1, CO-2), (C-2, CO-1), (C-2, CO-2) , (C-2, CO-
3) and (C-3, CO-1) as they have the same patterns.

r1 r2

Customer-1 Cust_Order-1 Customer-1 Cust_Order-1

Cust_Order-2 Customer-1 Cust_Order-2


Cusomer-2
inner join Cust_Order-1 = Customer-2 Cust_Order-1
Customer-3 Cust_Order-2 Customer-2 Cust_Order-2

Cust_Order-3 Customer-2 Cust_Order-3


Customer-4
Cust_Order-1 Customer-3 Cust_Order-1
equi join example
The following table illustrates the inner join of two tables r1(AC-1, AC-2, AC-3, AC-4, AC-5) and r2(C-1, C-2,
C-3, C-4). The result includes rows: (2,A), (3,B), and (4,C) as they have the same patterns.
JOINS – equi join
EQUI JOIN performs a JOIN against equality or matching column(s) values of the associated tables. An equal
sign (=) is used as comparison operator in the where clause to refer equality.

SELECT A1, A2, A3, . . . FROM r1, r2 WHERE r1. A1 = r2. A1

r1 = {1, 2, 3, 4}
r2 = {(1, a), (2, b), (1, c), (3, d), (2, e), (1, f)}
r1 = r2
R = {(1,1,a),
(2,2,b),
(1,1,c),
(3,3,d),
(2,2,e),
(1,1,f)}
JOINS – equi join
• SELECT * FROM emp , dept WHERE emp.deptno = dept.deptno;
tableA tableB JOINS – equi join
Table Table

• SELECT * FROM tableA , tableB WHERE


tableA.id = tableB.id;

• SELECT * FROM tableA , tableB WHERE


tableA.name = tableB.name;
ON Contrition
• When this join condition gets applied none of the columns of the relation will get eliminated in the result set.
• In order to apply this join condition, on any two tables they need not to have any common column.

ON condition and USING Attribute


USING Attribute Contrition
• When all the common columns are used in the join predicate then the result would be same as Natural join.
• In the result set of the join the duplicates of the columns used in the predicate gets eliminated.
• It should not have a qualifier(table name or Alias) in the referenced columns.

Note:
• ON clause is optional, If not given then INNER JOIN works like CROSS JOIN.
JOINS – ON & USING clause example
The ON clause
The ON clause is used to join tables where the column names don’t match in both tables.

JOINING CONDITION

The USING clause


The USING clause is used if several columns share the same name but you don’t want to join using all of these
common columns. The columns listed in the USING clause can’t have any qualifiers in the statement.

JOINING CONDITION
Inner JOIN
The inner join is one of the most commonly used joins in SQL. The inner join clause allows you to
query data from two or more related tables.
INNER JOIN returns rows when there is at least one
match in both tables.
JOINS – Inner Join
The INNER JOIN selects all rows from both participating tables as long as there is a match between the
columns. An SQL INNER JOIN is same as JOIN clause, combining rows from two or more tables.

SELECT A1, A2, A3, . . . FROM r1 [INNER] JOIN r2 ON r1. A1 = r2. A1


• SELECT * FROM employee emp INNER JOIN qualification quali ON emp.id =
quali.employeeid;

ON clause is optional, If not given then


INNER JOIN works like CROSS JOIN
INNER JOIN returns rows when there is at least one
match in both tables.
JOINS – Inner Join
The INNER JOIN selects all rows from both participating tables as long as there is a match between the
columns. An SQL INNER JOIN is same as JOIN clause, combining rows from two or more tables.

SELECT A1, A2, A3, . . . FROM r1 [INNER] JOIN r2 ON r1. A1 = r2. A1


• SELECT * FROM customer INNER JOIN ord USING (custid);

ON clause is optional, If not given


INNER JOIN works like CROSS JOIN
Natural JOIN
The NATURAL JOIN is such a join that performs the same task as an INNER JOIN. NATURAL JOIN
does not use any comparison operator. We can perform a NATURAL JOIN only if there is at least one
common attribute that exists between two relations. In addition, the attributes must have the same
name and domain. When this join condition gets applied always the duplicates of the common
columns get eliminated from the result.
Joins two tables based on common column names. JOINS – Natural Join
Hence one must confirm the common columns before
using a NATURAL JOIN

The NATURAL JOIN is such a join that performs the same task as an INNER JOIN.

SELECT A1, A2, A3, . . . FROM r1 NATURAL JOIN r2

• SELECT * FROM emp NATURAL JOIN dept;

• The associated tables have one or more pairs of identically column-names.


• The columns must be of the same name and data type.
• Don't use ON / USING clause in a NATURAL JOIN.
• When this join condition gets applied always the duplicates of the common columns get eliminated from the
result.

A NATURAL JOIN can be used with a LEFT OUTER join, or a RIGHT OUTER join.

If the column-names are not same, then NATURAL JOIN


will work as CROSS JOIN.
INNER JOIN Vs NATURAL JOIN
INNER VS NATURAL

INNER JOIN NATURAL JOIN

Inner Join joins two table on the basis of the column which is Natural Join joins two tables based on same attribute
explicitly specified in the ON clause. name.
In Natural Join, The resulting table will contain all
In Inner Join, The resulting table will contain all the attribute
the attributes of both the tables but keep only one
of both the tables including duplicate columns also
copy of each common column

In Inner Join, only those records will return which exists in


Same as Inner Join
both the tables

SYNTAX:
• SELECT * FROM r1 INNER JOIN r2 ON r1.A1 =
r2.A1; SYNTAX:
• SELECT * FROM r1 INNER JOIN r2 USING(A1, • SELECT * FROM r1 NATURAL JOIN r2;
[A2]);
Simple JOIN
TODO
JOINS – Simple Join
The SIMPLE JOIN is such a join that performs the same task as an INNER JOIN.

SELECT A1, A2, A3, . . . FROM r1 SIMPLE JOIN r2 USING (A1, . . . )

• SELECT * FROM emp SIMPLE JOIN dept USING(deptno)

JOINING CONDITION
The ON clause is required for a left or right outer join.

Outer JOINS
In an outer join, along with rows that satisfy the matching criteria, we also include some or all rows
that do not match the criteria.

CREATE TABLE r1 (id INT, c1 VARCHAR(10));


CREATE TABLE r2 (id INT, c1 VARCHAR(10));

INSERT INTO r1 VALUES (4,'AC-1'), (1,'AC-2'),(2,'AC-3'),(3,'AC-4'),(5,'AC-5');


INSERT INTO r2 VALUES (1,'C-1'), (2,'C-2'),(3,'C-3'),(7,'C-4');
Left Outer JOINS
r1 = {1, 2, 3, 4}
r2 = {(1, a), (2, b), (1, c), (3, SELECT * FROM r1 LEFT JOIN r2 ON r1.c1 =
r2.c1;
d), (2, e), (1, f), (5, z)}
r1 left join r2
R = {(1, 1, a),
(2, 2, b),
(1, 1, c),
(3, 3, d),
(2, 2, e),
(1, 1, f),
JOINS – Left Outer Join
Suppose, we want to join two tables: r1 and r2. SQL left outer join returns all rows in the left table (r1) and all the
matching rows found in the right table (r2). It means the result of the SQL left join always contains the rows in
the left table. . If no matching rows found in the right table, NULL are displayed.
The following example the LEFT JOIN of two tables r1(AC-1, AC-2, AC-3, AC-4, AC-5) and r2(C-1, C-2, C-3, C-4).
The LEFT JOIN will match rows from the r1 table with the rows from r2 table using patterns:
JOINS – Left Outer Join
The LEFT JOIN keyword returns all rows from the left table (r1), with the matching rows in the right table (r2).
The result is NULL in the right side when there is no match.

SELECT A1, A2, A3, . . . FROM r1 LEFT [OUTER ] JOIN r2 ON r1. A1 = r2. A1

SELECT * FROM orders ord LEFT OUTER JOIN employee emp ON emp.id = ord.employeeid;
JOINS – Left Outer Join
• SELECT * FROM student LEFT OUTER JOIN student_order ON student.id =
student_order.studentid ;
JOINS – Left Outer Join
The LEFT JOIN keyword returns all rows from the left table (r1), with the matching rows in the right table (r2).
The result is NULL in the right side when there is no match.

SELECT A1, A2, A3, . . . FROM r1 LEFT [OUTER ] JOIN r2 ON r1. A1 = r2. A1
WHERE r2. A1 IS NULL
SELECT * FROM orders ord LEFT OUTER JOIN employee emp ON emp.id = ord.employeeid
WHERE emp.id IS NULL;
JOINS – Left Outer Join
• SELECT * FROM student LEFT OUTER JOIN student_order ON student.id =
student_order.studentid WHERE student_order.studentID IS NULL;
JOINS – Left Outer Join
The LEFT JOIN keyword returns all rows from the left table (r1), with the matching rows in the right table (r2).
The result is NULL in the right side when there is no match.

SELECT A1, A2, A3, . . . FROM r1 LEFT [OUTER ] JOIN r2 USING (A1, . . .)

• SELECT * FROM emp LEFT OUTER JOIN dept USING(deptno);

SELECT A1, A2, A3, . . . FROM r1 NATURAL LEFT [OUTER ] JOIN r2

• SELECT * FROM emp NATURAL LEFT OUTER JOIN dept;


Right Outer JOINS
r1 = {1, 2, 3, 4} SELECT * FROM r1 RIGHT JOIN r2 ON r1.c1 =
r2 = {(1, a), (2, b), (1, c), (3, r2.c1;
d), (2, e), (1, f), (5, z)}
r1 right join r2
R = {(1, 1, a),
(1, 1, c),
(1, 1, f),
(2, 2, b),
(2, 2, e),
(3, 3, d),
JOINS – Right Outer Join
Suppose, we want to join two tables: r1 and r2. Right outer join returns all rows in the right table (r1) and all the
matching rows found in the left table (r2). It means the result of the SQL right join always contains the rows in
the right table. . If no matching rows found in the left table, NULL are displayed.
The following example the RIGHT OUTER JOIN of two tables r1(AC-1, AC-2, AC-3, AC-4, AC-5) and r2(C-1, C-2,
C-3, C-4). The RIGHT JOIN will match rows from the r1 table with the rows from r2 table using patterns:
JOINS – Right Outer Join
The RIGHT JOIN keyword returns all rows from the right table (r2), with the matching rows in the left table (r1).
The result is NULL in the left side when there is no match.

SELECT A1, A2, A3, . . . FROM r1 RIGHT [OUTER ] JOIN r2 ON r1. A1 = r2. A1

SELECT * FROM orders ord RIGHT OUTER JOIN employee emp ON emp.id =
ord.employeeid;
JOINS – Right Outer Join
• SELECT * FROM student RIGHT OUTER JOIN student_order ON student.id =
student_order.studentid;
JOINS – Right Outer Join
The RIGHT JOIN keyword returns all rows from the right table (r2), with the matching rows in the left table (r1).
The result is NULL in the left side when there is no match.

SELECT A1, A2, A3, . . . FROM r1 RIGHT [OUTER ] JOIN r2 ON r1. A1 = r2. A1
WHERE r1. A1 IS NULL
SELECT * FROM orders ord RIGHT OUTER JOIN employee emp ON emp.id = ord.employeeid
WHERE ord.employeeid IS NULL;
JOINS – Right Outer Join
• SELECT * FROM student RIGHT OUTER JOIN student_order ON student.id =
student_order.studentid WHERE student.ID IS NULL;
JOINS – Right Outer Join
The RIGHT JOIN keyword returns all rows from the right table (r2), with the matching rows in the left table (r1).
The result is NULL in the left side when there is no match.

SELECT A1, A2, A3, . . . FROM r1 RIGHT [OUTER ] JOIN r2 USING (A1, . . .)

SELECT * FROM emp RIGHT OUTER JOIN dept USING(deptno);

SELECT A1, A2, A3, . . . FROM r1 NATURAL RIGHT [OUTER ] JOIN r2

SELECT * FROM emp NATURAL RIGHT OUTER JOIN dept;


LEFT JOIN Vs RIGHT JOIN
LEFT JOIN VS RIGHT JOIN

LEFT OUTER JOIN RIGHT OUTER JOIN FULL OUTER JOIN


All the tuples of the left table remain All the tuples of the right table remain All the tuples from left as well as right
in the result. in the result. table remain in the result.
The tuples of left table that does not The tuples of right table that does not The tuples of left as well as the right
have a matching tuple in right table have a matching tuple in left table are table that does not have the matching
are extended with NULL value for extended with NULL value for tuples in the right and left table
attributes of the right table. attributes of the left table. respectively are extended with NULL
value for attributes of the right and
left tables.
TODO

Self JOINS
TODO
JOINS – Self Join
A SELF JOIN is a join in which a table is joined with itself (which is also called Unary relationships), especially
when the table has a FOREIGN KEY which references its own PRIMARY KEY.

SELECT rx.A1, rx.A2, ry.A1, ry.A2, . . . FROM r1 rx, r1 ry


WHERE rx.A1 = ry.A1
Set Operation in SQL
Set operators are used to join the results of two (or more) SELECT
statements. ...
Remember:
• The result set column names are taken from the column names of the first SELECT statement.
• SELECT statement should have the same data type. (Not in MySQL)
• UNION: To apply ORDER BY or LIMIT to an individual SELECT, place the clause inside the parentheses
that enclose the SELECT.
e.g. (SELECT …) UNION (SELECT …)
• CREATE TABLE Facebook • CREATE TABLE LinkedIn
( (
ID INT PRIMARY ID INT PRIMARY
KEY, KEY,
name VARCHAR(45), name VARCHAR(45),
location location
VARBINARY(45) VARBINARY(45)
SELECT name FROM Students /* Fetch the union of queries */
); );
UNION
SELECT name FROM Contacts;

SELECT name FROM Students /* Fetch the union of queries with


duplicates*/
UNION ALL
SELECT name FROM Contacts;

SELECT name FROM Students /* Fetch names from students */


MINUS /* that aren't present in contacts */
SELECT name FROM Contacts;

SELECT name FROM Students /* Fetch names from students */


INTERSECT /* that are present in contacts as well */
UNION
syntax
SELECT . . . UNION [ALL |
DISTINCT]
SELECT . . . [UNION [ALL |
DISTINCT]
SELECT . . .]
Note:
• it is used to combine the result sets of 2 or more SELECT statements.
• it removes duplicate rows between the various SELECT statements.
• each SELECT statement within the UNION operator must have the same number of fields in the result sets.
• default behaviour for UNION is that duplicate rows are removed from the result.

• (SELECT deptno FROM emp LIMIT 1) UNION (SELECT deptno FROM dept LIMIT 1);
• SELECT 'EMP' as 'Table Name', COUNT(*) FROM emp UNION SELECT 'DEPT', COUNT(*)
FROM dept UNION SELECT 'BONUS', COUNT(*) FROM bonus;
UNION
books newbooks Output

• SELECT bookName, type FROM books UNION SELECT bookName, type


FROM newbooks;
Note:
The following statement will give an error
• SELECT bookName, type FROM books ORDER
BY bookname UNION
SELECT bookName, type FROM newbooks;
UNION ALL
books newbooks Output

• SELECT bookName, type FROM BOOKS UNION ALL SELECT bookName,


type FROM newbooks;
INTERSECT

An INTERSECT query returns the intersection of 2 or more datasets. If a record exists in both data sets, it
will be included in the INTERSECT results.

Note:
• There is no INTERSECT operator in MySQL, you can easily simulate this type of query using either the IN
clause or the EXISTS clause.

• SELECT * FROM oldbook oldbk WHERE EXISTS (SELECT * FROM newbook newbk WHERE
oldbk.id = newbk.id and oldbk.name = newbk.name);
INTERSECT
books newbooks Output

• SELECT bookName, type FROM books WHERE EXISTS ( SELECT bookname, type FROM
newbooks WHERE books.bookName = newbooks.bookName);
• SELECT bookName, type FROM books WHERE bookName IN (SELECT bookName FROM
newbooks);
MINUS

The MINUS operator takes the distinct rows of one query and returns the rows that do not appear in a
second result set.

Note:
• There is no MINUS operator in MySQL, you can easily simulate this type of query using either the NOT IN
clause or the NOT EXISTS clause.
Note: MINUS
• There is no MINUS operator in MySQL, you can easily simulate this type of query using either the NOT IN
clause or the NOT EXISTS clause.

1. SELECT bookName, type FROM books /* Fetch


bookName, type from books */
MINUS /* that are not present
in newbooks */
SELECT bookName, type FROM newbooks;

2. SELECT bookName, type FROM newbooks /* Fetch bookName, type


from newbooks */
MINUS /* that are not present in
books */
SELECT bookName, type FROM books;
MINUS
books newbooks Output

Output
e.g.
• SELECT bookName, type FROM books WHERE NOT EXISTS
(SELECT bookName, type FROM newbooks WHERE
books.bookName = newbooks.bookName);

• SELECT bookName, type FROM newbooks WHERE NOT EXISTS


(SELECT bookName, type FROM books WHERE books.bookName =
newbooks.bookName);
Note:
• Your database table has X columns, Where as the VALUES you are passing are for (X-1) or (X+1). This
mismatch of column-values will giving you the error.

INSERT ROWS
INSERT command inserts new rows into an existing table.

You can insert data using following methods:

• INSERT ... VALUES


• INSERT ... SET
• INSERT ... SELECT
INSERT ROWS using VALUES
DML- INSERT … VALUES
INSERT inserts new rows into an existing table. The INSERT ... VALUES

INSERT [IGNORE] [INTO] tbl_name [(col_name,...)] {VALUES | VALUE} ({expr


| DEFAULT}, ...) , (...), ... [ON DUPLICATE KEY UPDATE assignment_list]

The affected-rows value for an INSERT can be obtained using the ROW_COUNT() function.

Column Values

Column List

Inserting multiple rows


DML- INSERT … VALUES
INSERT inserts new rows into an existing table. The INSERT ... VALUES

INSERT [IGNORE] [INTO] tbl_name [ (col_name, . . .) ] {VALUES |


VALUE} ({expr | DEFAULT}, . . .) , (. . .), . . . [ ON DUPLICATE
KEY UPDATE assignment_list ]
student (
ID INT,
nameFirst VARCHAR(45),
nameLast VARCHAR(45),
DoB DATE ,
emailID VARCHAR(128)
);

e.g.
• INSERT INTO student VALUES (29, 'sharmin', 'patil', '1999-11-10',
'[email protected]');
• INSERT INTO student (ID, nameFirst, nameLast, DOB, emailID) VALUES (30, 'john',
'thomas', '1983-11-10', '[email protected]');
• INSERT INTO student (ID, nameFirst, emailID) VALUES (31, 'jack', '1980-01-14',
'[email protected]');
• INSERT INTO student (ID, nameFirst) VALUES (32, 'james'), (33, 'jr. james'),
INSERT ROWS using SET
DML- INSERT …SET
INSERT inserts new rows into an existing table. The INSERT ... SET forms of the statement insert rows based
on explicitly specified values.

INSERT [INTO] tbl_name SET col_name = {expr |


DEFAULT}, . . . [ON DUPLICATE KEY UPDATE
assignment_list]
student(ID INT, nameFirst VARCHAR(45), nameLast VARCHAR(45), DoB
DATE , emailID VARCHAR(128) )
e.g.
• INSERT INTO student SET nameLast='patil', DoB ='2000-04-21', ID=35 , nameFirst
='rajan', emailID = '[email protected]');

Note:
• A SET clause indicates columns explicitly by name, together with the value to assign each one.
• The affected-rows value for an INSERT can be obtained using the ROW_COUNT() function.
INSERT ROWS using SELECT
INSERT ... SELECT
With INSERT ... SELECT, you can quickly insert many rows into a table from one or many tables.

INSERT [INTO] tbl_name [(col_name, . . .)] SELECT . . . [ON


DUPLICATE KEY UPDATE assignment_list]

• INSERT INTO dept (deptno) SELECT 1 + 1;


• INSERT INTO dept (deptno) SELECT deptno FROM dept;
• INSERT INTO dept SELECT * FROM dept;
• INSERT INTO dept (SELECT MAX(deptno) + 1, 'HRD', 'BARODA', 'r57px33px'
FROM dept);

• set @x := 40;
• INSERT INTO dept VALUES (@x := @x + 1 , 'HRD', 'BARODA', 'r57px33px’);

• set @x := (SELECT MAX(deptno) FROM dept);


• INSERT INTO dept VALUES (@x := @x + 1 , 'HRD', 'BARODA', 'r57px33px’);
ORDER BY in UPDATE: if the table contains two values 1 and 2 in the id column and 1 is updated to 2 before 2
is updated to 3, an error occurs. To avoid this problem, add an ORDER BY clause to cause the rows with larger
id values to be updated before those with smaller values.

Note:
Here c1 column is a Primary Key
• UPDATE temp SET c1 = c1 - 1 ORDER BY c1 ASC; # In case
of decrement

Single-table UPDATE
• UPDATE temp SET c1 = c1 + 1 ORDER BY c1 DESC; # In case of
increment
• SET @x := 0;
• UPDATE emp SET id = @x:= @x+1;

• UPDATE t, (SELECT isactive, COUNT(isactive) r1 FROM emp GROUP BY isactive) a SET


t.c2 = a.r1 WHERE t.c1 = a.isactive;
mysql> SELECT * FROM
t;
+------- +-------
+--------+ +------+
| c1 | | c1 |
c2 | c2 | e.g.
1. Update top 2 rows.
+------- +-------
2. Update UnitPrice for the top 5 most expensive products.
+--------+ +------+
Single-table UPDATE
The UPDATE statement updates columns of existing rows in the named table with new values. The SET clause
indicates which columns to modify and the values they should be given. The WHERE clause, if given, specifies
the conditions that identify which rows to update. With no WHERE clause, all rows are updated. If the ORDER
BY clause is specified, the rows are updated in the order that is specified. The LIMIT clause places a limit on
the number of rows that can be updated.

UPDATE <table_reference> SET col_name1 = {expr1 | DEFAULT} [,


col_name2 = {expr2 | DEFAULT}] . . .
[WHERE where_condition]
[ORDER BY . . .]
[LIMIT row_count]
• UPDATE temp SET dname = 'new_value' LIMIT 2;
• UPDATE temp SET c1 = 'new_value' ORDER BY loc LIMIT 2;
• UPDATE temp SET c1 = 'new_value' WHERE deptno <50;
• UPDATE temp SET c1 = 'new_value' WHERE deptno <50 LIMIT 2;
• ALTER TABLE dept ADD SUMSALARY INT;
• UPDATE dept SET sumsalary = (SELECT SUM(sal) FROM emp WHERE emp.deptno =
dept.deptno GROUP BY emp.deptno);
• UPDATE candidate SET totalvotes = (SELECT COUNT(*) FROM votes WHERE candidate.id =
Single-Table DELETE
Single-table DELETE
The DELETE statement deletes rows from tbl_name and returns the number of deleted rows. To check the
number of deleted rows, call the ROW_COUNT() function. The optional WHERE clause identify which rows to
delete. With no WHERE clause, all rows are deleted. If the ORDER BY clause is specified, the rows are deleted
in the order that is specified. The LIMIT clause places a limit on the number of rows that can be deleted.

DELETE FROM table_reference


[WHERE where_condition]
[ORDER BY . . .]
[LIMIT row_count]

Note:
• LIMIT clauses apply to single-table deletes, but not multi-table deletes.

• DELETE FROM temp;


• DELETE FROM temp ORDER BY loc LIMIT 2;
• DELETE FROM temp WHERE deptno <50;
• DELETE FROM temp WHERE deptno <50 LIMIT 2;
DELETE Vs TRUNCATE
DELETE VS TRUNCATE
DELETE TRUNCATE
You can specify the tuple that you want to delete. It deletes all the tuples from a relation.
DELETE is a Data Manipulation Language command. TRUNCATE is a Data Definition Language command.
DELETE command can have WHERE clause. TRUNCATE command do not have WHERE clause.

DELETE command activates the trigger applied on the TRUNCATE command does not activate the triggers to
table and causes them to fire. fire.
DELETE command eliminate the tuples one-by-one. TRUNCATE delete the entire data page containing the
tuples.
DELETE command lock the row/tuple before deleteing it. TRUNCATE command lock data page before deleting
table data.
DELETE command acts slower as compared to TRUNCATE is faster as compared to DELETE.
TRUNCATE.
DELETE records transaction log for each deleted tuple. TRUNCATE record transaction log for each deleted data
page.
DELETE command can be followed either by COMMIT TRUNCATE command can't be ROLLBACK.
or ROLLBACK.
The char is a fixed-length character data type, CREATE TABLE TEMP (C1 CHAR(10), C2
The varchar is a variable-length character data
VARCHAR(10));
type.
TE TABLE `123` (c1 INT, c2 VARCHAR(10)); INSERT INTO TEMP VALUES('SALEEL',
'SALEEL’);

datatypes SELECT * FROM TEMP WHERE C1 LIKE


'SALEEL';
ENAME CHAR (10) S A L E E L LENGTH -> 10
ENAME S A L E E L LENGTH -> 6
VARCHAR2(10)

When CHAR values are retrieved, the trailing spaces are removed
In MySQL (unless the PAD_CHAR_TO_FULL_LENGTHSQL mode is enabled)

ENAME CHAR (10) S A L E E L LENGTH -> 6


ENAME VARCHAR(10) S A L E E L LENGTH -> 6
dataType - STRING
Datatypes Size Description
CHAR [(length)] 0-255
The maximum row size (65,535 bytes, which is shared
VARCHAR (length) 0 to 65,535 among all columns.
TINYTEXT [(length)] (28 − 1) bytes
TEXT [(length)] (216 -1) bytes 65,535 bytes ~ 64kb
MEDIUMTEXT [(length)] (224 -1) bytes 16,777,215 bytes ~16MB
LONGTEXT [(length)] (232 -1) bytes 4,294,967,295 bytes ~4GB
ENUM('value1', 'value2',...) 65,535 members
SET('value1', 'value2',...) 64 members

By default, trailing spaces are trimmed from CHAR column values on retrieval. If
PAD_CHAR_TO_FULL_LENGTH is enabled, trimming does not occur and retrieved CHAR values are
padded to their full length.

• SET sql_mode = '';


• SET sql_mode = 'PAD_CHAR_TO_FULL_LENGTH';
dataType - NUMERIC
Datatypes Size Description
TINYINT 1 byte -128 to +127 (The unsigned range is 0 to 255).
SMALLINT [(length)] 2 bytes -32768 to 32767. (The unsigned range is 0 to 65535).
MEDIUMINT [(length)] 3 bytes -8388608 to 8388607. (The unsigned range is 0 to 16777215).
-2147483648 to 2147483647. (The unsigned range
INT, INTEGER [(length)] 4 bytes
is 0 to 4294967295).
BIGINT [(length)] 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
FLOAT [(length[,decimals])] 4 bytes FLOAT(255,30)
DOUBLE [PRECISION] [(length[,decimals])], REAL(255,30) / DOUBLE(255,30)
8 bytes
REAL [(length[,decimals])] REAL will get converted to DOUBLE
DECIMAL [(length[,decimals])], DECIMAL(65,30) / NUMERIC(65,30)
NUMERIC [(length[,decimals])] NUMERIC will get converted in DECIMAL

For: float(M,D), double(M,D) or decimal(M,D), M must be >= D

Here, (M,D) means than values can be stored with up to M digits in total, of which D digits may be after the
decimal point.

UNSIGNED prohibits negative values.


dataType – DATE and TIME
Datatypes Size Description
YEAR 1 byte YYYY
DATE 3 bytes YYYY-MM-DD
TIME 3 bytes HH:MM:SS
DATETIME 8 bytes YYYY-MM-DD hh:mm:ss
dataType – Boolean
CREATE TABLE temp (col1 INT ,col2 BOOL, col3 BOOLEAN);

CREATE TABLE tasks ( id INT PRIMARY KEY AUTO_INCREMENT, title VARCHAR(255) NOT
NULL, completed BOOLEAN);
• INSERT INTO tasks VALUE(default, 'Task1', 0);
• INSERT INTO tasks VALUE(default, 'Task2', 1);
• INSERT INTO tasks VALUE(default, 'Task3', False);
• INSERT INTO tasks VALUE(default, 'Task4', True);
• INSERT INTO tasks VALUE(default, 'Task5', null);
• INSERT INTO tasks VALUE(default, 'Task6', default);
• INSERT INTO tasks VALUE(default, 'Task7', 1>2);
• INSERT INTO tasks VALUE(default, 'Task8', 1<2);
• INSERT INTO tasks VALUE(default, 'Task9', 12);
• INSERT INTO tasks VALUE(default, 'Task10', 58);
• INSERT INTO tasks VALUE(default, 'Task11', .75);
• INSERT INTO tasks VALUE(default, 'Task12', .15);
• INSERT INTO tasks VALUE(default, 'Task13', 'a' = 'a');
Note:
• BOOL and BOOLEAN are synonym of TINYINT(1)
• An ENUM column can have a maximum of 65,535 distinct elements. dataType – ENUM
• ENUM values are sorted based on their index numbers, which depend on the order in which the
enumeration members were listed in the column specification.
• Default value, NULL if the column can be NULL, first enumeration value if NOT NULL
• CREATE TABLE temp (col1 INT, COL2 ENUM('A','B','C') NULL);
• INSERT INTO temp(col1) VALUES (1);
• CREATE TABLE temp (col1 INT, col2 ENUM('A','B','C') NOT NULL);
• INSERT INTO temp(col1) VALUES (1);
• CREATE TABLE temp (col1 INT, col2 ENUM('') NOT NULL);
• INSERT INTO temp (col1) VALUES (1,'THIS IS THE TEST');

membership ENUM('Silver', 'Gold', 'Diamond')


interest ENUM('Movie', 'Music', 'Concert')
zone ENUM('North', 'South', 'East', 'West')
season ENUM('Winter', 'Summer', 'Monsoon', 'Autumn')
sortby ENUM('Popularity', 'Price -- Low to High', 'Price -- High to Low',
'Newest First’)
status ENUM('active', 'inactive', 'pending', 'expired')
Note:
• You also cannot use user variable as an enumeration value. This pair of statements do not work:
SET @mysize = 'medium';
CREATE TABLE sizes ( size ENUM('small', @mysize, 'large'));
• A SET column can have a maximum of 64 distinct members. dataType – SET
• A SET is a string object that can have zero or more values, each of which must be chosen from
a list of permitted values specified when the table is created.

• SET column values that consist of multiple set members are specified with members separated
by commas (,).

• CREATE TABLE temp (col SET('a', 'b', 'c', 'd'));


• INSERT INTO temp (col) VALUES ('a, d'), ('d, a'), ('a, d, a'), ('a, d,
d'), ('d, a, d');
UPDATE j SET date = JSON_SET(date,
"$.canVote", 'False');

JSON Datatype
Datatype – JSON
JSON (JavaScript Object Notation) documents.

 Data is in name/value pairs

 Data is separated by comm

 Curly braces hold objects

 Square brackets hold arrays


An object is an unordered set of name/value pairs.

An array is an ordered collection of values.


JSON
Returns data from a JSON document, selected from the parts of the document matched by the path arguments. Returns
NULL if any argument is NULL or no paths locate a value in the document. An error occurs if the json_doc argument is not
a valid JSON document or any path argument is not a valid path expression.

JSON_EXTRACT(json_doc, path[, path] . . .


• SELECT ('[10, 20, [30, 40], [50, 60, 70]]');

• SELECT JSON_EXTRACT('[10, 20, [30, 40], [50, 60, 70]]', '$[0]');

• SELECT JSON_EXTRACT('[10, 20, [30, 40], [50, 60, 70]]', '$[3][0]');

• SELECT JSON_EXTRACT('[10, 20, [30, 40]]', '$[0]', '$[1]');

• SELECT ('{"id" : "1001", "ename" : "saleel"}');

• SELECT ('[ {"id" : "1001“ ,"ename" : "saleel"}, {"id" : "1002", "ename" :


"sharmin", "mob" : "12345"} ]');

• SELECT JSON_EXTRACT ('[ {"id" : "1001" ,"ename" : "saleel"}, {"id" : "1002",


"ename" : "sharmin", "mob" : "12345"} ]', '$[0].id');

• SELECT JSON_EXTRACT('{"id" : "1001", "ename" : "saleel"}', '$.ename');


Datatype – JSON … (Insert)
MySQL supports a native JSON data type that enables efficient access to data in JSON (JavaScript Object
Notation) documents.

CREATE TABLE e (data json);


• INSERT INTO e VALUES ('{}');

• INSERT INTO e VALUES ('{"empno" : "1001", "ename" : "saleel", "phone" : [123,


456]}');

• INSERT INTO e VALUES ('{"empno" : "1002", "ename" : "sharmin" ,"phone" : [9922,


8811], "address" : "Paud Road"}');

• INSERT INTO e VALUES ('{"empno" : "1003", "ename" : "vrushali", "phone" : [7788,


9977], "address" : {"city" : "Pune", "state" : "MH"}}');

• INSERT INTO e VALUES (' [{"empno" : "1004", "ename" : "ram" ,"phone" : [6672,
8811], "address" : "Paud Road"}, {"empno" : "1005", "ename" : "sham" ,"phone" :
[6672, 8843], "address" : "Paud Road"} ]');
Datatype – JSON … (Select)
MySQL supports a native JSON data type that enables efficient access to data in JSON (JavaScript Object
Notation) documents.

CREATE table E (data json);


• SELECT * from E;
• SELECT JSON_EXTRACT (data, '$.*') FROM e;
• SELECT JSON_EXTRACT (data, '$.empno') FROM e;
• SELECT JSON_EXTRACT (data, '$.phone[1]') FROM e;
• SELECT JSON_EXTRACT (data, "$.address.city") FROM e;
• SELECT JSON_EXTRACT (data, "$.empno", "$.ename") FROM e;
Use a CREATE TABLE statement to specify the layout of your table.

CREATE TABLE `123` (c1 INT, c2 VARCHAR(10));

CREATE TABLE
Use a CREATE TABLE statement to specify the layout of your
table.

Remember:
• by default, tables are created in the default database, using the InnoDB storage engine.
• error occurs if the table exists
• error occurs if there is no default database
• error occurs if the database does not exist.
Create Table
syntax
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
(create_definition,...)
e.g.
[table_options]
[partition_options] • CREATE TABLE student (
ID int,
create_definition: firstName
col_name column_definition VARCHAR(45),
lastName
column_definition: VARCHAR(45),
data_type [NOT NULL | NULL] [DEFAULT default_value] DoB DATE,
[AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY] emailID
[COMMENT 'string'] VARCHAR(128)
[reference_definition] );
| data_type [GENERATED ALWAYS] AS (expression)
[VIRTUAL] [UNIQUE [KEY]] [COMMENT comment]
[NOT NULL | NULL] [[PRIMARY] KEY]

table_options:
ENGINE [=] engine_name show engines;
set default_storage_engine = memory;
• MEMORY tables are visible to
Create Table
another client.
• Structure is stored and rows will be show engines;
removed, after re-starting mysql set default_storage_engine = memory;
server.

e.g. CREATE TABLE temp (i INT) ENGINE =


MEMORY; • CSV tables are visible to another
INSERT INTO temp VALUES(1); client.
SELECT * FROM temp; • The CSV storage engine stores data
re-start mysql server. in text files using comma-separated
• TEMPORARY tables
SELECT * FROM temp;are not
visible to another client. values format.
• Structure and rows is removed, • The storage engine for the table
after exit. doesn't support nullable columns.

e.g. CREATE TEMPORARY TABLE temp1 (i e.g. CREATE TABLE csv (


INT); ID INT not null,
INSERT INTO temp1 VALUES(1); ename VARCHAR(10) not null,
SELECT * FROM temp1; job VARCHAR(10) not null,
EXIT sal INT not null) ENGINE = CSV;
INSERT INTO csv VALUES(1,
'saleel', 'manager', 3400);
CREATE TEMPORARY TABLE
Temporary Table
Remember:
• You can use the TEMPORARY keyword when creating a table.

• A TEMPORARY table is visible only to the current session, and is dropped automatically when the session is
closed.

• Use TEMPORARY table with the same name as the original can be useful when you want to try some
statements that modify the contents of the table, without changing the original table.

• The permanent (original) table becomes hidden (inaccessible) to the client who creates the TEMPORARY
table with same name as the original.

• If you issue a DROP TABLE statement, the TEMPORARY table is removed and the original table reappears, it
is possible, only when then original tbl_name and temporary tbl_name are same.

• The original table also reappears if you rename the TEMPORARY table.
e.g. ALTER TABLE dept RENAME TO d;

Temporary
table_name
Temporary Table
e.g.
CREATE TEMPORARY TABLE STUDENT (
ID INT PRIMARY KEY,
namefirst VARCHAR(45),
namelast VARCHAR(45),
DOB DATE,
emailID VARCHAR(128)
);
CREATE TEMPORARY TABLE TEMP (
ID INT PRIMARY KEY,
firstName VARCHAR(45),
phone INT,
city VARCHAR(10) DEFAULT 'PUNE',
salary INT,
comm INT,
total INT GENERATED ALWAYS AS(salary + comm)
VIRTUAL
);
CREATE TEMPORARY TABLE ... LIKE
Use CREATE TABLE ... LIKE to create an empty table based on the definition of another table.

CREATE TEMPORARY TABLE [IF NOT EXISTS] new_tbl LIKE


orig_tbl;
• CREATE TEMPORARY TABLE tempEmployee LIKE employee;

Remember:
• LIKE works only for base tables, not for VIEWS.
• You can use the TEMPORARY keyword when creating a table. A TEMPORARY table is visible only to the
current session, and is dropped automatically when the session is closed.
• Use TEMPORARY table with the same name as the original can be useful when you want to try some
statements that modify the contents of the table, without changing the original table.

• CREATE TEMPORARY TABLE new_tbl SELECT * FROM orig_tbl LIMIT 0;


Default value
The DEFAULT specifies a default value for the column.
Default value
col_name data_type DEFAULT value

The DEFAULT specifies a default value for the column.

• CREATE TABLE posts (


postID INT,
postTitle VARCHAR(255),
postDate DATETIME DEFAULT
NOW(),
deleted INT
);
# version 8.0 and above.
• CREATE TABLE empl (
ID INT primary key,
firstName VARCHAR(45),
phone INT,
city VARCHAR(10) DEFAULT
'PUNE',
salary INT,
comm INT,
total INT DEFAULT(salary +
Default value
The DEFAULT example.

• CREATE TABLE temp (


c1 INT,
c2 INT DEFAULT 100,
c3 INT DEFAULT 200,
c4 INT,
c5 INT
);

• INSERT INTO temp VALUES();


• INSERT INTO temp VALUES(1, DEFAULT, DEFAULT, 1, 1);
• INSERT INTO temp VALUES(2, DEFAULT(c2), DEFAULT(c3), 2, 2);
• INSERT INTO temp VALUES(3, DEFAULT(c3), DEFAULT(c2), 3, 3);
AUTO_INCREMENT Column
The AUTO_INCREMENT attribute can be used to generate a unique number/identity for
new rows.
auto_increment
IDENTITY is a synonym to the
LAST_INSERT_ID variable.

col_name data_type AUTO_INCREMENT [UNIQUE [KEY] | [PRIMARY] KEY]

Remember:
• There can be only one AUTO_INCREMENT column per table.
• it must be indexed.
• it cannot have a DEFAULT value.
• it works properly only if it contains only positive values.
• It applies only to integer and floating-point types.
• when you insert a value of NULL or 0 into AUTO_INCREMENT column, it generates next value.
• use LAST_INSERT_ID() function to find the row that contains the most recent AUTO_INCREMENT value.

• SELECT @@IDENTITY

• SELECT LAST_INSERT_ID()

• SET INSERT_ID = 7
auto_increment
The auto_increment specifies a auto_increment value for the column.

• CREATE TABLE posts (


postID INT UNIQUE KEY
AUTO_INCREMENT,
postTitle VARCHAR(255),
postDate DATETIME DEFAULT NOW(),
deleted INT
);
• CREATE TABLE comments (
commentID INT PRIMARY KEY
AUTO_INCREMENT,
comment TEXT,
commentDate DATETIME DEFAULT NOW(),
deleted INT
);
• CREATE TABLE ... LIKE, the destination table preserves generated column information from the original table.
• CREATE TABLE ... SELECT, the destination table does not preserves generated column information from the
original table.

GENERATED column
Remember:
• Stored functions and user-defined functions are not permitted.
• Stored procedure and function parameters are not permitted.
• Variables (system variables, user-defined variables, and stored program local variables) are not permitted.
• Subqueries are not permitted.
• The AUTO_INCREMENT attribute cannot be used in a generated column definition.
• Triggers cannot use NEW.COL_NAME or use OLD.COL_NAME to refer to generated columns.

Note:
• The expression can contain literals, built-in functions with no parameters, operators, or references to any
column within the same table. If you use a function, it must be scalar and deterministic.
Virtual column - GENERATED ALWAYS
col_name data_type [GENERATED ALWAYS] AS (expression) [VIRTUAL | STORED] [NOT NULL | NULL]
[UNIQUE [KEY]] [[PRIMARY] KEY] [COMMENT 'string']

• VIRTUAL: Column values are not stored, but are evaluated when rows are read, immediately after any
BEFORE triggers. A virtual column takes no storage.
• STORED: Column values are evaluated and stored when rows are inserted or updated. A stored column does
require storage space and can be indexed.

Note:
• The default is VIRTUAL if neither keyword is specified.

• CREATE TABLE product (


productCode INT PRIMARY KEY AUTO_INCREMENT,
productName VARCHAR(45),
productVendor VARCHAR(45),
productDescription TEXT,
quantityInStock INT,
buyPrice FLOAT,
stockValue FLOAT GENERATED ALWAYS AS(quantityInStock *
buyPrice) VIRTUAL
a1 int(10) zerofill 0 0 0 0 0 0 1 5 0 0 length(ID1) -> 10
a2 int(10) 3 6 7 5 length(ID2) -> 4

zerofill value
When you select a column with the type ZEROFILL it pads the displayed value of the field with zeros up to the
display width specified in the column definition.

Note:
• ZEROFILL attribute is use for numeric datatype.
• If you specify ZEROFILL for a column, MySQL automatically adds the UNSIGNED attribute to the column.
zerofill column
col_name data_type ZEROFILL

CREATE TABLE employee ( • INSERT INTO employee VALUES(NULL, 'ram',


ID INT ZEROFILL AUTO_INCREMENT 4700, NULL, default);
PRIMARY KEY, • INSERT INTO employee VALUES(0, 'pankaj',
firstName VARCHAR(40), 3400, 400 , default);
salary INT, • INSERT INTO employee VALUES(100, 'rajan',
commission INT, 3200, NULL , default);
total INT DEFAULT(salary + • INSERT INTO employee VALUES(NULL, 'ninad',
commission) 2600, 0 , default);
) ; • INSERT INTO employee VALUES(0, 'omkar',
4500,3000,
• INSERT INTO employee VALUES (-200, 'rahul', 300 ,300
default);
, default);

• SELECT * FROM employee;


• SELECT ID, LENGTH(ID), salary, LENGTH(salary) FROM employee;
zerofill column
• CREATE TABLE account (
accountNumber INT ZEROFILL
PRIMARY KEY,
balance FLOAT,
openingBalance FLOAT,
accountName VARCHAR(45),
custonerID INT,
openingDate DATE
);

Note:
• If you specify ZEROFILL for a numeric column, MySQL automatically adds the UNSIGNED attribute to the
column.
CONSTRAINTS
CONSTRAINT is used to define rules to allow or restrict what values can be stored in columns. The
purpose of inducing constraints is to enforce the integrity of a database.

CONSTRAINTS can be classified into two types –


• Column Level
• Table Level.
The column level constraints can apply only to one column where as table level constraints are applied to
the entire table.
Remember:
• PRI => primary key
• UNI => unique key
• MUL=> is basically an index that is neither a primary key nor a unique key. The name comes from
"multiple" because multiple occurrences of the same value are allowed.

CONSTRAINTS
To limit or to restrict or to check or to control.

Note:
• a table with a foreign key that references another table's primary key is MUL.
• If more than one of the Key values applies to a given column of a table, Key displays the one with the
highest priority, in the order PRI, UNI, and MUL.
Keys are used to establish relationships between tables
and also to uniquely identify any record in the table. types of Keys?
r = Employee(EmployeeID, FullName, job, salary, PAN,
DateOfBirth, emailID, deptno)
• Candidate Key: are individual columns in a table that qualifies for uniqueness of all the rows. Here in Employee
table EmployeeID, PAN or emailID are Candidate keys.

• Primary Key: is the columns you choose to maintain uniqueness in a table. Here in Employee table you can
choose either EmployeeID, PAN or emailID columns, EmployeeID is preferable choice.

• Alternate Key: Candidate column other the primary key column, like if EmployeeID is primary key then , PAN
or emailID columns would be the Alternate key.

• Super Key: If you add any other column to a primary key then it become a super key, like EmployeeID +
FullName is a Super Key.

• Composite Key: If a table do not have any single column that qualifies for a Candidate key, then you have to
select 2 or more columns to make a row unique. Like if there is no EmployeeID, PAN or emailID columns, then
you can make FullName + DateOfBirth as Composite key. But still there can be a narrow chance of duplicate
row.
Candidate Key
Primary Key

Composite Key
Alternate Key
Remember:
• A primary key cannot be NULL.
• A primary key value must be unique.
• A table has only one primary key.
• The primary key values cannot be changed, if it is referred by some other column.
• The primary key must be given a value when a new record is inserted.

PRIMARY KEY constraint


Choosing a primary key is one of the most important steps in good database design. A primary key
is a column that serves a special purpose. A primary key is a special column (or set of combined
columns) in a relational database table, that is used to uniquely identify each record. Each database
table needs a primary key.
Note:
• Primary key in a relation is always associated with an INDEX object.
• If, we give on a column a combination of NOT NULL & UNIQUE key then it behaves like a PRIMARY key.
• If, we give on a column a combination of UNIQUE key & AUTO_INCREMENT then also it behaves like a
PRIMARY key.
Constraints – Add Primary Key
col_name data_type PRIMARY KEY

The following example creates tables with PRIMARY KEY column.

• CREATE TABLE users ( • CREATE TABLE


ID INT PRIMARY KEY, purchase_orders (
userName po_number INT,
VARCHAR(25), vendor_id INT NOT
password NULL,
VARCHAR(25), po_status INT NOT
email VARCHAR(255) NULL,
) ; PRIMARY
• CREATE TABLE supplier ( • KEY(po_number)
CREATE TABLE person (
supplier_id INT, ); ID INT NOT NULL UNIQUE,
supplier_name VARCHAR(50), lastName VARCHAR(45),
contact_name VARCHAR(50), firstName VARCHAR(45),
constraint pk_supplier_id PRIMARY age INT,
KEY(supplier_id) email VARCHAR(255)
); );
Constraints – Add Composite Primary Key
The following example creates tables with PRIMARY KEY column.
• CREATE TABLE salesDetails (
customerID INT,
productID INT,
timeID INT,
qty INT,
salesDate DATE,
salesAmount INT,
PRIMARY KEY(customerID , productID,
timeID)
) ;
customerID productID timeID quantity salesDate salesAmount
Cust-001 PRD-1 D1-T1 100 ●●●●●● 25,00,000
Cust-001 PRD-1 D2-T1 100 ●●●●●● 25,00,000
Cust-001 PRD-2 D1-T1 200 ●●●●●● 50,00,000
Cust-002 PRD-1 D1-T1 100 ●●●●●● 25,00,000
Cust-004 PRD-1 D1-T1 100 ●●●●●● 25,00,000
Cust-004 PRD-2 D3-T1 200 ●●●●●● 50,00,000
Constraints – Add Composite Primary Key
The following example creates tables with COMPOSITE PRIMARY KEY column.

• CREATE TABLE payments (


paymentID INT,
orderID INT,
amount INT,
bankDetails VARCHAR(255),
PRIMARY KEY(paymentID , orderID)
) ;

• CREATE TABLE order_product (


orderID INT,
productID INT,
qty INT,
rate INT,
constraint pk_orderID_productID PRIMARY
KEY(orderID, productID)
) ;
syntax
ALTER TABLE table_name
ADD CONSTRAINT [ constraint_name ]
PRIMARY KEY (column1, column2, . .
. column_n)

Add Primary Key using Alter


Constraints – Add Primary Key using Alter
You can use the ALTER TABLE statement to ADD PRIMARY KEY on existing column.

syntax
ALTER TABLE table_name
ADD CONSTRAINT [ constraint_name ]
PRIMARY KEY (column1, column2, . .
. column_n)
• CREATE TABLE vendors (
vendor_id INT,
vendor_name
VARCHAR(25),
address VARCHAR(255)
);
• ALTER TABLE vendors ADD PRIMARY KEY(vendor_id);
• ALTER TABLE vendors ADD constraint pk_vendor_id PRIMARY KEY(vendor_id);
syntax
ALTER TABLE table_name
DROP PRIMARY KEY

Drop Primary Key


Constraints – Drop Primary Key
You can use the ALTER TABLE statement to DROP PRIMARY KEY.

syntax
ALTER TABLE table_name
DROP PRIMARY KEY

• CREATE TABLE vendors (


vendor_id INT,
vendor_name
VARCHAR(25),
address VARCHAR(255)
);

ALTER TABLE vendors DROP PRIMARY KEY;


Remember:
• A unique key can be NULL.
• A unique key value must be unique.
• A table can have multiple unique key.
• A column can have unique key as well as a primary key.

UNIQUE KEY constraint


A UNIQUE key constraint is a set of one or more than one fields/columns
of a table that uniquely identify a record in a database table.

Note:
• Unique key in a relation is always associated with an INDEX object.
Constraints – Add Unique Key
col_name data_type UNIQUE KEY

The following example creates table with UNIQUE KEY column.

• CREATE TABLE clients ( • CREATE TABLE contacts (


client_id INT, ID INT,
first_name VARCHAR(50), first_name
last_name VARCHAR(50), VARCHAR(50),
company_name last_name
VARCHAR(255), VARCHAR(50),
email VARCHAR(255) phone VARCHAR(15),
UNIQUE UNIQUE(phone)
• );
CREATE TABLE brands (
);
ID INT,
brandName VARCHAR(30),
constraint uni_brandName
UNIQUE(brandName)
);

• SHOW INDEX FROM clients;


syntax
ALTER TABLE table_name
ADD CONSTRAINT [ constraint_name ]
UNIQUE (column1, column2, . . .
column_n)

Add Unique Key using Alter


Constraints – Add Unique Key using Alter
You can use the ALTER TABLE statement to ADD UNIQUE KEY on existing column.

syntax
ALTER TABLE table_name
ADD CONSTRAINT [ constraint_name ]
UNIQUE (column1, column2, . . .
column_n)
• CREATE TABLE shop (
ID INT,
shop_name VARCHAR(30)
);

• ALTER TABLE shop ADD UNIQUE(shop_name);


• ALTER TABLE shop ADD constraint uni_shop_name UNIQUE(shop_name);
syntax
ALTER TABLE table_name
DROP INDEX constraint_name;

Drop Unique Key


Constraints – Drop Unique Key
You can use the ALTER TABLE statement to DROP UNIQUE KEY.

syntax
ALTER TABLE table_name
ADD CONSTRAINT [ constraint_name ]
UNIQUE (column1, column2, . . .
column_n)
• ALTER TABLE users DROP INDEX <COLUMN_NAME>;
• ALTER TABLE users DROP INDEX U_USER_ID; #CONSTRAINT NAME

• CREATE TABLE users ( • CREATE TABLE users (


ID INT PRIMARY KEY, ID INT PRIMARY KEY,
userName VARCHAR(40), userName VARCHAR(40),
password VARCHAR(255), password VARCHAR(255),
email VARCHAR(255) UNIQUE email VARCHAR(255),
KEY constraint uni_email UNIQUE
) ; KEY(email)
• ALTER TABLE users DROP INDEX • )ALTER
; TABLE users DROP INDEX
email; uni_email;
FOREIGN KEY constraint
A FOREIGN KEY is a key used to link two tables together. A FOREIGN KEY is a field
(or collection of fields) in one table that refers to the PRIMARY KEY in another table.
The table containing the foreign key is called the child table, and the table containing
the candidate key is called the referenced or parent table.
Constraints – Foreign Key

Remember:
• A foreign key can have a different name from its primary key.
• DataType of primary key and foreign key column must be same.
• It ensures rows in one table have corresponding rows in another.
• Unlike the Primary key, they do not have to be unique.
• Foreign keys can be null even though primary keys can not.

Note:
• The table containing the FOREIGN KEY is referred to as the child table, and the table containing the
PRIMARY KEY (referenced key) is the parent table.
• PARENT and CHILD tables must use the same storage engine,
• and they cannot be defined as temporary tables.
Constraints – Foreign Key
A referential constraint could be violated in following cases.

• An INSERT attempt to add a row to a child table that has a value in its foreign key columns that does not match
a value in the corresponding parent table's column.

• An UPDATE attempt to change the value in a child table's foreign key columns to a value that has no matching
value in the corresponding parent table's parent key.

• An UPDATE attempt to change the value in a parent table's parent key to a value that does not have a
matching value in a child table's foreign key columns.

• A DELETE attempt to remove a record from a parent table that has a matching value in a child table's foreign
key columns.

Note:
• PARENT and CHILD tables must use the same storage engine,
• and they cannot be defined as temporary tables.
• If we don’t give constraint name. System will automatically generated the constraint name and
will assign to foreign key constraint. e.g. login_ibfk_1, login_ibfk_2, …..
Anomaly – (Primary Key/Foreign Key)
Remember:
student Table student_course Table
RollNo Name Mobile City State isActive RollNo CourceDuration CourceName
1 Ramesh ●●●● Pune MH 1 1 1.5 month RDBMS
2 Amit ●●●● Baroda GJ 1 2 1.2 month NoSQL
3 Rajan ●●●● Surat GJ 1 3 2 month Networking
4 Bhavin ●●●● Baroda GJ 1 1 2 month Java
5 Pankaj ●●●● Surat GJ 1 2 2 month .NET

Insertion anomaly:
• If we try to insert a record in Student_Course table with RollNo = 7, it will not allow.

Updation and Deletion anomaly:

• If you try to chance the RollNo from Student table with RollNo = 6 whose RollNo = 1 , it will not allow.
• If you try to chance the RollNo from Student_Course table with RollNo = 9 whose RollNo = 3 , it will not allow.
• If we try to delete a record from Student table with RollNo = 1, it will not allow.
Alter, Drop – (Primary Key/Foreign Key)
Remember:
student = { student_course = {
rollno INT, * (PK) rollno INT, * (FK)
name VARCHAR(10), courceduration VARCHAR(10),
mobile VARCHAR(10), courcename VARCHAR(10)
city VARCHAR(10), }
state VARCHAR(10),
isActive BOOL
}
DDL command could be violated in following cases.
Alter command:
• If we try to modify datatype of RollNo in Student or Student_Course table with VARCHAR, it will not allow.
• If we try to apply auto_increment to RollNo in Student table, it will not allow
• If we try to drop RollNo column from Student table , it will not allow.

Drop command:
• If we try to drop Student table, it will not allow.
Constraints – Foreign Key
A foreign key is a field in a table that matches another field of another table. A foreign key places constraints on data in the
related tables, which enables MySQL to maintain referential integrity.

• CREATE TABLE movie ( • CREATE TABLE actor (


movie_id INT PRIMARY KEY, actor_id INT PRIMARY
movie_title VARCHAR(50), KEY,
movie_year INT, actor_fname
movie_time INT, VARCHAR(20),
movie_lang VARCHAR(15), actor_lname
movie_dt_rel DATE, VARCHAR(20),
movie_rel_country actor_gender
VARCHAR(5) VARCHAR(1)
); );
• CREATE TABLE movie_cast (
movie_id INT,
actor_id INT,
role VARCHAR(30),
constraint fk_movie_id FOREIGN KEY(movie_id)
REFERENCES movie(movie_id),
constraint fk_actor_id FOREIGN KEY(actor_id)
REFERENCES actor(actor_id)
Constraints – Find Foreign Key columns
The following example find Foreign Key columns.

• CREATE TABLE owner ( • CREATE TABLE contacts (


owner_id INT PRIMARY contact_id INT PRIMARY
KEY, KEY,
first_name VARCHAR(50), owner_id INT,
last_name VARCHAR(50), contact_number
email VARCHAR(255) VARCHAR(15)
); );

• CREATE TABLE shop ( • CREATE TABLE shop_brand


shop_id INT, (
owner_id INT, ID INT PRIMARY KEY,
shop_name VARCHAR(30) shop_id INT,
); brand_id INT
);
• CREATE TABLE brands (
brand_id INT PRIMARY KEY,
brand_name VARCHAR(30)
UNIQUE
);
syntax
ALTER TABLE table_name
ADD CONSTRAINT [ constraint_name ]
FOREIGN KEY (child_col1, child_col2, . . .
child_col_n)
REFERENCES parent_table (parent_col1, parent_col2,

Add Foreign Key Constraint using


. . . parent_col_n);

Alter
Constraints – Add Foreign Key using Alter
You can use the ALTER TABLE statement to ADD FOREIGN KEY on existing column.

syntax
ALTER TABLE table_name
ADD CONSTRAINT [ constraint_name ]
FOREIGN KEY (child_col1, child_col2, . . .
child_col_n)
REFERENCES parent_table (parent_col1,
parent_col2, . . .( parent_col_n); CREATE TABLE login (
CREATE TABLE users
ID INT PRIMARY KEY, ID INT PRIMARY KEY,
userName VARCHAR(40), userID INT,
password VARCHAR(255), loginDate DATE,
email VARCHAR(255) UNIQUE loginTime TIME
KEY ) ;
) ;
• ALTER TABLE login ADD FOREIGN KEY(userID) REFERENCES users(ID);
• ALTER TABLE login ADD constraint fk_userID FOREIGN KEY(userID) REFERENCES
users(ID);
syntax
ALTER TABLE table_name
DROP FOREIGN KEY constraint_name

Drop Foreign Key Constraint


using Alter
Constraints – Drop Foreign Key
You can use the ALTER TABLE statement to DROP FOREIGN KEY.
CREATE TABLE users ( CREATE TABLE login (
ID INT PRIMARY KEY , ID INT PRIMARY KEY,
userName VARCHAR(40), userID INT,
password VARCHAR(255), loginDate DATE,
email VARCHAR(255) loginTime TIME,
) ; FOREIGN KEY(userID) REFERENCES
users(ID)
CREATE TABLE login ( ) ;
ID INT PRIMARY KEY,
userID INT,
loginDate DATE,
loginTime TIME,
constraint fk_userID FOREIGN KEY(userID)
REFERENCES users(ID)
) ;
• ALTER TABLE login DROP FOREIGN KEY fk_userID;
• ALTER TABLE login DROP FOREIGN KEY login_ibfk_1; // login_ibfk_1 is the default

• constraint
SELECT name.
TABLE_NAME, CONSTRAINT_NAME, CONSTRAINT_TYPE FROM information_schema.table_constraints WHERE
TABLE_SCHEMA='DB2’;
On DELETE / On UPDATE – Foreign Key
SET NULL: Delete or update the row from the parent table and set the foreign key column or columns in the child
table to NULL. If you specify a SET NULL action, make sure that you have not declared the columns in the child
table as NOT NULL.

RESTRICT: Rejects the delete or update operation for the parent table. Specifying RESTRICT (or NO ACTION) is
the same as omitting the ON DELETE or ON UPDATE clause.

NO ACTION: Is equivalent to RESTRICT. The MySQL Server rejects the delete or update operation for the parent
table if there is a related foreign key value in the referenced table.

SET DEFAULT: This action is recognized by the MySQL parser, but both InnoDB and NDB reject table definitions
containing ON DELETE SET DEFAULT or ON UPDATE SET DEFAULT clauses.
1. CREATE TABLE TEST (c1 INT, c2 INT, c3 INT,
check (c3 = SUM(c1)));
// ERROR

Check Constraint
Constraints – Check
CHECK condition expressions must follow some rules.
• Literals, deterministic built-in functions, and operators are permitted.
• Non-generated and generated columns are permitted, except columns with the AUTO_INCREMENT attribute.
• Sub-queries are not permitted.
• Environmental variables (such as CURRENT_USER, CURRENT_DATE, …) are not permitted.
• Non-Deterministic built-in functions (such as AVG, COUNT, RAND, LAST_INSERT_ID, FIRST_VALUE,
LAST_VALUE, ...) are not permitted.
• Variables (system variables, user-defined variables, and stored program local variables) are not permitted.
• Stored functions and user-defined functions are not permitted.

Note:
Prior to MySQL 8.0.16, CREATE TABLE permits only the following limited version of table CHECK constraint
syntax, which is parsed and ignored.
Remember:
If you omit the constraint name, MySQL automatically generates a name with the following convention:
• table_name_chk_n
Constraints – Check
col_name data_type CHECK(expr)

The following example creates USERS table with CHECK column.

CREATE TABLE users ( CREATE TABLE users (


ID INT PRIMARY KEY, ID INT PRIMARY KEY,
userName VARCHAR(40), userName VARCHAR(40),
password VARCHAR(255), password VARCHAR(255),
email VARCHAR(255), email VARCHAR(255),
ratings INT CHECK(ratings ratings INT,
> 50) CHECK(ratings > 50)
) ; ) ;
CREATE TABLE users ( CREATE TABLE users (
ID INT PRIMARY KEY, ID INT PRIMARY KEY,
userName VARCHAR(40), userName VARCHAR(40),
password VARCHAR(255), password VARCHAR(255),
email VARCHAR(255), email VARCHAR(255),
ratings INT, ratings INT,
constraint chk_ratings constraint chk_ratings CHECK(ratings >
CHECK(ratings > 50) 50),
) ; constraint chk_email CHECK(LENGTH(email)
syntax
ALTER TABLE table_name
ADD CONSTRAINT [ constraint_name ]
CHECK (conidiation)

Add Check Constraint using Alter


Constraints – Add Check using Alter
You can use the ALTER TABLE statement to ADD CHECK KEY on existing column.

syntax
ALTER TABLE table_name
ADD CONSTRAINT [ constraint_name ]
CHECK (conidiation)

CREATE TABLE users (


ID INT PRIMARY KEY,
userName VARCHAR(40),
password VARCHAR(255),
email VARCHAR(255),
ratings INT
) ;

• ALTER TABLE users ADD CHECK(ratings > 50);


• ALTER TABLE users ADD constraint chk_ratings CHECK(ratings > 50);
syntax
ALTER TABLE table_name
DROP CHECK [ CONSTRAINT ]
constraint_name

Drop Check Constraint


Constraints – Drop Check Key
You can use the ALTER TABLE statement to DROP CHECK KEY.

syntax CREATE TABLE users (


ID INT PRIMARY KEY,
ALTER TABLE table_name userName VARCHAR(40),
DROP CHECK [ CONSTRAINT ] constraint_name password VARCHAR(255),
email VARCHAR(255),
ratings INT,
constraint chk_ratings
CHECK(ratings > 50)
) ;
CREATE TABLE users (
• ALTER TABLE users DROP CHECK
ID INT PRIMARY KEY,
chk_ratings; userName VARCHAR(40),
password VARCHAR(255),
• ALTER TABLE users DROP constraint
email VARCHAR(255),
chk_ratings; ratings INT,
CHECK(ratings > 50)
• ALTER TABLE users DROP CHECK
) ;
users_chk_1;
• SELECT TABLE_NAME, CONSTRAINT_NAME, CONSTRAINT_TYPE FROM information_schema.table_constraints WHERE
TABLE_SCHEMA='DB2' AND (TABLE_NAME LIKE 'U%' OR TABLE_NAME LIKE 'L%');
Check with (IN, LIKE, and BETWEEN)
The CHECK constraint using IN, LIKE, and BETWEEN.

CREATE TABLE users (


ID INT PRIMARY KEY,
userName VARCHAR(40),
password VARCHAR(255) CHECK(LENGTH(password) > 5),
email VARCHAR(255),
country VARCHAR(255) CHECK(country LIKE ('I%') OR country
LIKE ('U%')),
ratings INT CHECK(ratings BETWEEN 1 and 5 OR ratings
BETWEEN 12 and 25),
isActive BOOL CHECK(isActive IN (1, 0))
) ;
ALTER TABLE
ALTER TABLE changes the structure of a table.

Note:
• you can add or delete columns,
• create or destroy indexes,
• change the type of existing columns, or
• rename columns or the table itself.
Alter Table
syntax
ALTER TABLE tbl_name

[alter_specification [, alter_specification] . . .

• | ADD [COLUMN] col_name column_definition [FIRST | AFTER col_name ]


• | ADD [COLUMN] (col_name column_definition, . . .)
• | ADD {INDEX|KEY} [index_name] (index_col_name, . . .)
• | ADD [CONSTRAINT [symbol]] PRIMARY KEY
• | ADD [CONSTRAINT [symbol]] UNIQUE KEY
• | ADD [CONSTRAINT [symbol]] FOREIGN KEY reference_definition
• | CHANGE [COLUMN] old_col_name new_col_name column_definition [FIRST|
AFTER col_name]
• | MODIFY [COLUMN] col_name column_definition [FIRST | AFTER col_name]
• | DROP [COLUMN] col_name
• | DROP PRIMARY KEY
• | DROP {INDEX|KEY} index_name
• | DROP FOREIGN KEY fk_symbol
Alter Table
Remember:
• Change Columns :- You can rename a column using a CHANGE old_col_name new_col_name
column_definition clause. To do so, specify the old and new column names and the definition that the column
currently has.
• Modify Columns :- You can also use MODIFY to change a column's type without renaming it.
• Dropping Columns :- If a table contains only one column, the column cannot be dropped. If columns are
dropped from a table, the columns are also removed from any index of which they are a part. If all columns
that make up an index are dropped, the index is dropped as well.

Note:
• To convert a table from one storage engine to another, use an ALTER TABLE statement that indicates
the new engine:

TER TABLE tbl_name ENGINE = InnoDB


TER TABLE tbl_name ADD col1 INT, ADD col2 INT
TER TABLE tbl_name DROP COLUMN col1, DROP COLUMN col2
TER TABLE tbl_name DROP COLUMN c4, DROP COLUMN c5, ADD c3 INT
Add column
syntax
ALTER TABLE tbl_name [alter_specification [,
alter_specification] . . .]
alter_specification
• ADD [COLUMN] col_name column_definition [FIRST | AFTER
col_name ]
• ADD [COLUMN] (col_name column_definition, . . .)
Add column
• CREATE TABLE vehicles (
vehicleID INT PRIMARY • ALTER TABLE vehicles
KEY , ADD ID INT UNIQUE
year INT, auto_increment first,
make VARCHAR(100) ADD model VARCHAR(100) not
); null,
ADD color VARCHAR(50),
ADD note VARCHAR(255);

• INSERT INTO vehicles VALUES (111,


2000, 'Honda');
• INSERT INTO vehicles VALUES (112,
2002, 'Hyundai');
• INSERT INTO vehicles VALUES (113,
2000, 'Jeep');
• INSERT INTO vehicles VALUES (114,
2005, 'Toyota');
Modify column
syntax
ALTER TABLE tbl_name [alter_specification [,
alter_specification] ...]
alter_specification
• MODIFY [COLUMN] col_name column_definition [FIRST | AFTER
col_name]
• CREATE TABLE vehicles ( Modify column
vehicleID INT PRIMARY
KEY , • ALTER TABLE vehicles
year INT, MODIFY year SMALLINT not
make VARCHAR(100), null,
model VARCHAR(100) not MODIFY make VARCHAR(150)
null, not null,
color VARCHAR(50), MODIFY color VARCHAR(20)
note VARCHAR(255) not null;
);

• INSERT INTO vehicles VALUES (111, 2000, 'Honda', 'A1', 'silver', ' Honda was the
first Japanese automobile manufacturer to release a dedicated luxury brand, Acura,
in 1986.');
• INSERT INTO vehicles VALUES (112, 2002, 'Hyundai', 'AC1', 'white', ' Hyundai
operates the world's largest integrated automobile manufacturing facility in
Ulsan, South Korea which has an annual production capacity of 1.6 million
units.');
Change column
syntax
ALTER TABLE tbl_name [alter_specification [, alter_specification] ...]
alter_specification
• CHANGE [COLUMN] old_col_name new_col_name column_definition [ FIRST |
AFTER col_name ]
Change column
• CREATE TABLE vehicles ( • ALTER TABLE vehicles
vehicleID INT, CHANGE year model_year INT,
year SMALLINT, CHANGE color model_color
make VARCHAR(150), VARCHAR(20),
model VARCHAR(100), CHANGE note vehicleCondition
color VARCHAR(20), VARCHAR(150);
note VARCHAR(255)
);
Change column
• CREATE TABLE users ( • CREATE TABLE login (
ID INT PRIMARY KEY, ID INT PRIMARY KEY,
userName VARCHAR(40), userID INT,
password VARCHAR(25), loginDate DATE,
email VARCHAR(255) loginTime TIME,
) ; constraint fk_userID FOREIGN KEY(userID)
REFERENCES users(ID)
) ;
• INSERT INTO users VALUES (1, 'rajan', 'ranaj123', 'rajan447.gmail.com');
• INSERT INTO users VALUES (2, 'raj', 'raj', 'raj.gmail.com');

• INSERT INTO login VALUES (1, 1, curdate(), curtime());


• INSERT INTO login VALUES (2, 1, curdate(), curtime());
• INSERT INTO login VALUES (3, 2, curdate(), curtime());
• INSERT INTO login VALUES (4, NULL, curdate(), curtime());

• ALTER TABLE users CHANGE ID userID INT;


• ALTER TABLE login CHANGE userID UID INT;

• INSERT INTO login VALUES (5, NULL, curdate(), curtime());


Drop column
syntax
ALTER TABLE tbl_name [alter_specification [,
alter_specification] ...]
alter_specification
• DROP [COLUMN] col_name
Drop column

• CREATE TABLE vehicles ( • ALTER TABLE vehicles


vehicleID INT, CHANGE model_year year INT not null,
model_year SMALLINT, DROP model,
make VARCHAR(150), DROP model_color,
model VARCHAR(100), DROP vehicleCondition;
model_color VARCHAR(20),
vehicleCondition VARCHAR(150)
);
Alter Table
Sample table Rename columns
CREATE TABLE vehicles ( ALTER TABLE vehicles
vehicleID INT PRIMARY KEY , CHANGE year model_year SMALLINT NOT
year INT, NULL,
make VARCHAR(100) CHANGE color model_color VARCHAR(20),
); CHANGE note vehicleCondition
VARCHAR(150);
Add new columns to a table DROP columns
ALTER TABLE vehicles ALTER TABLE vehicles
ADD model VARCHAR(100) NOT NULL, CHANGE model_year year INT NOT NULL,
ADD color VARCHAR(50), DROP model,
ADD note VARCHAR(255); DROP model_color,
DROP vehicleCondition;
Modify columns
ALTER TABLE vehicles
MODIFY year SMALLINT NOT NULL,
MODIFY color VARCHAR(20) NOT
NULL,
MODIFY make VARCHAR(150) NOT
NULL;
DROP TABLE
Remember:
• DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command.
• DELETE operations can be rolled back (undone), while DROP and TRUNCATE operations cannot be
rolled back (Auto COMMIT).
• Dropping a TABLE also drops any TRIGGERS for the table.
• Dropping a TABLE also drops any INDEX for the table.
• Dropping a TABLE will not drops any VIEW for the table.
• If you try to drop a PARENT/MASTER TABLE, it will not get dropped.
Drop Table
syntax
DROP [TEMPORARY] TABLE [IF EXISTS] tbl_name [, tbl_name] ...

Note:
• All table data and the table definition are removed.

• DROP login;
• DROP TABLE users;
• DROP TABLE login, users;
TRUNCATE TABLE
Remember:
• DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command.
• DELETE operations can be rolled back, while DROP and TRUNCATE operations cannot be rolled back.
• The TRUNCATE TABLE statement removes all the data/rows of a table and resets the auto-increment value to
zero.
Truncate Table
Logically, TRUNCATE TABLE is similar to a DELETE statement that deletes all rows, or a sequence of DROP
TABLE and CREATE TABLE statements.

TRUNCATE [TABLE] tbl_name

Remember:
• Truncate operations drop and re-create the table, which is much faster than deleting rows one by one.
• Truncate operations cause an implicit commit, and so cannot be rolled back.
• Truncate does not cause ON DELETE triggers to fire.
• Truncate cannot be performed for parent-child foreign key relationships.
• Truncate retain Identity and reset to the seed (start value) value.
• Cannot truncate a table referenced in a foreign key constraint.
DROP Vs TRUNCATE
DROP VS TRUNCATE
DROP TRUNCATE
The DROP command is used to remove table definition Whereas the TRUNCATE command is used to delete all
and its contents. the rows from the table.
In the DROP command, VIEW of table does not exist. In the TRUNCATE command, VIEW of table exist.
In the DROP command, integrity constraints will be In the TRUNCATE command, integrity constraints will
removed. not be removed.
In the DROP command, INDEX associated to the table In the TRUNCATE command, INDEX associated to the
will be removed. table will not be removed.
In the DROP command, TRIGGER associated to the table In the TRUNCATE command, TRIGGER associated to the
will execute. table will not execute.
In the DROP command, TRIGGER associated to the table In the TRUNCATE command, TRIGGER associated to the
will be removed. table will be not removed.
RENAME Table
Change the table name.

RENAME TABLE old_tbl_name TO new_tbl_name

• RENAME TABLE emp TO employee;


A View in SQL as a logical subset of data from one or more tables. Views are used to restrict data access. A
View contains no data of its own but its like window through which data from tables can be viewed or changed.
The table on which a View is based are called BASE Tables.

There are 2 types of Views in SQL:


• Simple View : Simple views can only contain a single base table.
• Complex View : Complex views can be constructed on more than one base table. In particular, complex
views can contain: join conditions, a group by clause, a order by clause.

Views
Remember:
View
• it can be described as virtual table which derived its data from one or more than one table.
• it is stored in the database.
• it can be created using tables of same database or different database.
• it is used to implement the security mechanism in the SQL.

Rules:
• If a VIEW is defined as SELECT * on a table, new columns added to the table later do not become part of the
VIEW, and columns dropped from the table will result in an error when selecting from the VIEW.
• A VIEW must have unique column names with no duplicates, just like a base table. By default, the names of
the columns retrieved by the SELECT statement are used for the VIEW column names.
• The definition cannot refer to a TEMPORARY table, and you cannot create a TEMPORARY VIEW.
• You cannot associate a TRIGGER with a VIEW.

Note:
• If we drop the BASE TABLE, the VIEW will not be dropped.
View
Views are not updatable in the following cases:

• A table in the FROM clause is reference by a subquery in the WHERE statement.


• There is a subquery in the SELECT clause.
• The SQL statement defining the view joins tables.
• One of the tables in the FROM clause is a non-updatable view.
• The SELECT statement of the view contains an aggregate function such as SUM(), COUNT(), MAX(), MIN(),
and so on.
• The keywords DISTINCT, GROUP BY, HAVING clause, LIMIT clause, UNION, or UNION ALL appear in the
defining SQL statement.
Difference between Simple and Complex View
SIMPLE VIEW COMPLEX VIEW
Contains only one base table or is created from only one
Contains more than one base tables or is created from
table, it may include WHERE clause and ORDER BY
more than one tables.
clause.
We cannot use group functions like MAX(), COUNT(),
We can use group functions.
etc.
Does not contain groups of data. It can conatin groups of data.
DML operations could be performed through a simple DML operations could not always be performed through
view. a complex view.
INSERT, DELETE and UPDATE are directly possible on a We cannot apply INSERT, DELETE and UPDATE on
simple view. complex view directly.
Simple view does not contain group by, , having clause, It can contain group by, having clause, limit clause,
limit clause, distinct, pseudo column like rownum, distinct, pseudocolumn like rownum, columns defined
columns defined by expressions. by expressions.
NOT NULL columns that are not selected by simple view
Does not include NOT NULL columns from base tables.
can be included in complex view.
Create View
The select_statement is a SELECT statement that provides the definition of the view. The select_statement
can select from base tables or other views.

CREATE [OR REPLACE] VIEW view_name [(column_list)]


AS select_statement [WITH CHECK OPTION]

UPDATE AND DELETE on VIEW (with check option given on view) will work only when the DATA MATCHES
IN WHERE CLAUSE.

• CREATE VIEW v1 as SELECT * FROM dept;


• CREATE or REPLACE VIEW v1 as SELECT * FROM dept WITH CHECK
OPTION;

desc INFORMATION_SCHEMA.VIEWS;
licence table Create View

• CREATE VIEW agent1_view AS SELECT * FROM licence WHERE agentID = 1 ORDER BY


validTo; # Simple View
• CREATE VIEW agent2_view AS SELECT * FROM licence WHERE agentID = 2;
• CREATE VIEW agent3_view AS SELECT * FROM licence WHERE agentID = 3;
Try Out Create View
CREATE TABLE customer (
ID INT PRIMARY KEY ,
name VARCHAR(50),
description TEXT
);

CREATE TABLE orders (


orderID INT ,
customerID INT,
orderDate DATE,
amount INT,
constraint fk_customerID FOREIGN KEY(customerID) REFERENCES customer(cID));

INSERT INTO customer VALUES (1, 'saleel', 'description Text 1'),


(2, 'vrushali', 'description Text 2'), (3, 'sharmin',
'description Text 3'), (4, 'ruhan', 'description Text 4');

INSERT INTO orders VALUES(1, 1, NOW(), 3000), (2, 1, NOW(),


1000), (3, 2, NOW(), 100), (4, 2, NOW(), 300), (5, 2, NOW(),
200);
Try Out Create View
• CREATE VIEW v1 AS SELECT * FROM customer, orders WHERE ID = customerID;

• CREATE VIEW v2 AS SELECT customer.* FROM customer, orders WHERE ID = customerID;

• CREATE VIEW v3 AS SELECT orders.* FROM customer, orders WHERE ID = customerID;

• INSERT INTO v1(cID, name, description, orderID, customerID, orderdate, amount)


VALUES (10,'S10',"D1", 10, 1, NOW(), 111); // Error: Can not modify more than
one base table through a join view 'db5.v1’

// We may get Error: Can not insert into join view 'db5.v2' without fields list.

• INSERT INTO v2(cID, name, description) VALUES(5, 'neel', 'description Text 5');

• INSERT INTO v3(orderID, customerID, orderdate, amount) VALUES(6, 1, NOW(),


200);
SHOW CREATE VIEW Syntax
SHOW CREATE VIEW view_name

show create VIEW v1;

SHOW [FULL] TABLES [{FROM | IN} db_name]


[LIKE 'pattern' | WHERE expr]

show full tables where table_type like 'VIEW';


Alter / Drop View
This statement changes the definition of a view, which must exist.

ALTER VIEW view_name [(column_list)]


AS select_statement
[WITH CHECK OPTION]
e.g.
• ALTER VIEW studentview AS SELECT namefirst, namelast, emailid FROM
student;

DROP VIEW removes one or more views.

DROP VIEW [IF EXISTS]


view_name [, view_name] ...

e.g.
• DROP VIEW studentview;
• DROP VIEW studentid10view, studentviewwithcheck;
• DROP VIEW studentTotalMarksView, studentAddressView;
MySQL indexes (PRIMARY KEY, UNIQUE, INDEX, and FULLTEXT) are stored in B-trees.
FULLTEXT indexes are created on text-based columns (CHAR, VARCHAR, or TEXT columns)
to help speed up queries and DML operations on data contained within those columns, omitting
any words that are defined as stopwords.

Index
• it is a schema object.
• it is used by the server to speed up the retrieval of rows.
• it reduces disk I/O(input/output) process.
• it helps to speed up select queries where clauses, but it slows down data input, with the update and the
insert statements.
• it can be created or dropped with no effect on the data.
Index
Indexes are used to find rows with specific column values quickly. Without an index, MySQL must begin with the
first row and then read through the entire table to find the relevant rows. If the table has an index for the columns in
question, MySQL can quickly determine the position to seek to in the middle of the data file without having to look
at all the data. This is much faster than reading every row sequentially.

• To find the rows matching a WHERE clause quickly.


• If the table has a multiple-column index, any leftmost prefix of the index can be used by the optimizer to look up
rows. For example, if you have a three-column index on (col1, col2, col3), you have indexed search capabilities
on (col1), (col1, col2), and (col1, col2, col3).

If we drop the base table, the INDEX will be dropped automatically.


Create Index
Indexes are used to find rows with specific column values quickly.

CREATE [UNIQUE] INDEX index_name


ON tbl_name (index_col_name,...)

e.g.

• CREATE INDEX indexOnName ON emp(ename);


• CREATE INDEX indexOnUniversity ON
student_qualifications(university);
• CREATE UNIQUE INDEX uniqueIndexOnName ON emp(ename);
SHOW INDEX Syntax
To get the index of a table, you specify the table name after the FROM keyword. The statement will return
the index information associated with the table in the current database.

SHOW {INDEX | INDEXES | KEYS}


{FROM | IN} tbl_name
[{FROM | IN} db_name]
[WHERE expr]

e.g.

• SHOW INDEX FROM emp;


• SHOW INDEX FROM student_qualifications;

SHOW INDEX returns table index information.


Drop Index

DROP INDEX drops the index named index_name from the table tbl_name.

DROP INDEX index_name ON tbl_name

.g.
DROP INDEX indexOnName ON emp;
DROP INDEX indexOnUniversity ON student_qualifications;
DROP INDEX uniqueIndexOnName ON emp;
Lock / unlock table
lock / unlock
MySQL enables client sessions to acquire table locks to prevent from modifying tables

Sessions holding a READ lock, DROP TABLE and TRUNCATE TABLE operations are
not permitted.

LOCK TABLES tbl_name lock_type


[, tbl_name] lock_type] ...

lock_type:
READ |WRITE

UNLOCK TABLES

LOCK TABLE DEPT READ;

LOCK TABLE DEPT WRITE;

UNLOCK TABLE
• mysqldump -uroot -p db1 >> d:\bk.sql
• mysqldump -u[username] -p[password] --all-databases > d:\db_backup.sql
• mysqldump -P 3306 -h 192.168.100.26 -usaleel -psaleel db_name >
db_backup.sql
• mysqldump --column-statistics=0 -P 3306 -h 192.168.100.26 -usaleel -
psaleel db_name > db_backup.sql
• mysql -P 3306 –h192.168.100.74 -uroot -proot db2 < d:\
backup_fileName.sql
• mysql -P 3306 –h192.168.100.74
db2 snapshots
-uroot -proot < d:\ backup_fileName.sql

To create a raw data snapshot of MyISAM tables, you can use standard copy tools such as cp or
copy, a remote copy tool such as scp or rsync, an archiving tool such as zip or tar, or a file system
snapshot tool such as dump, providing that your MySQL data files exist on a single file system. If
you are replicating only certain databases, copy only those files that relate to those tables.
CountryName,CapitalName,CapitalLatitude,CapitalLongitude,CountryCode,ContinentName,re
mark
Somaliland,Hargeisa,9.55,44.05,NULL,Africa,
South Georgia and South Sandwich Islands,King Edward Point,-54.283333,-
36.5,GS,Antarctica,
French Southern and Antarctic Lands,Port-aux-Français,-49.35,70.216667,TF,Antarctica,
Palestine,Jerusalem,31.76666667,35.233333,PS,Asia,
Aland Islands,Mariehamn,60.116667,19.9,AX,Europe,
Nauru,Yaren,-0.5477,166.920867,NR,Australia,
Saint Martin,Marigot,18.0731,-63.0822,MF,North America,
Tokelau,Atafu,-9.166667,-171.833333,TK,Australia,

import .csv / .tsv file


Western Sahara,El-Aaiún,27.153611,-13.203333,EH,Africa,

CREATE TABLE countries (


CountryName VARCHAR(45),
CapitalName VARCHAR(45), LOAD DATA INFILE 'path/file-name.csv'
CapitalLatitude VARCHAR(45), INTO TABLE countries
CapitalLongitude VARCHAR(45), FIELDS TERMINATED BY ',' or FIELDS
CountryCode VARCHAR(45), TERMINATED BY '\t'
ContinentName VARCHAR(45), LINES TERMINATED BY '\n'
remark VARCHAR(45) IGNORE 1 ROWS;
);
cluster
A cluster comprises multiple interconnected computers or servers that appear as if they are one server to end
users and applications.
DATA DICTIONARY
DATA DICTIONARY - INFORMATION_SCHEMA
• INFORMATION_SCHEMA provides access to database metadata, information about the MySQL server such
as the name of a database or table, the data type of a column, or access privileges.

• INFORMATION_SCHEMA is a database within each MySQL instance, the place that stores information about
all the other databases that the MySQL server maintains. The INFORMATION_SCHEMA database contains
several read-only tables, you can only read the contents of tables, not perform INSERT, UPDATE, or DELETE
operations on them, and you cannot set triggers on them.
DATA DICTIONARY - INFORMATION_SCHEMA
Data Dictionary

INFORMATION_SCHEMA.COLUMNS

INFORMATION_SCHEMA.TABLES

INFORMATION_SCHEMA.TABLE_CONSTRAINTS

INFORMATION_SCHEMA.STATISTICS

INFORMATION_SCHEMA.KEY_COLUMN_USAGE

INFORMATION_SCHEMA.ROUTINES

INFORMATION_SCHEMA.PARAMETERS

INFORMATION_SCHEMA.TRIGGERS
Class Room

Session 1
PL/SQL
PL/SQL is a procedural language extension to Structured Query Language (SQL). The purpose of
PL/SQL is to combine database language and procedural programming language.
Note:
• Statements that return a result set can be used within a Stored Procedure but not within a Stored Function.
This prohibition includes SELECT statements that do not have an INTO var_list clause.

CREATE PROCEDURE and CREATE


FUNCTION
Stored Procedure and Function
These statements create stored routines. By default, a routine is associated with the default database. To
associate the routine explicitly with a given database, specify the name as db_name.sp_name when you create it.

CREATE PROCEDURE sp_name ([proc_parameter[,...]])


proc_parameter: SELECT * FROM information_schema.parameters
[ IN | OUT | INOUT ] param_name type WHERE SPECIFIC_NAME = 'pro1';

desc mysql.proc
CREATE FUNCTION sp_name ([func_parameter[,...]])
RETURNS type

DROP PROCEDURE IF EXISTS procedurename; DROP FUNCTION IF EXISTS functionname;


delimiter $$ delimiter $$
CREATE PROCEDURE procedurename() CREATE FUNCTION functionname() RETURNS INT
begin begin
statements……. statements…….
end $$ return (something);
delimiter ; end $$
delimiter ;
Parameter: Is an unknown thing. Means it exists but don’t know it.
e.g. Blood sugar it exists but we don’t know it.
A parameter is a variable in a method definition. When a method is called, the arguments are the data you pass
into the method's parameters. Parameter is variable in the declaration of function. Argument is the actual
value of this variable that gets passed to function.

Difference between arguments


and parameters?
• Parameter is variable in the declaration of procedure or a function.
• Argument is the actual value of this variable that gets passed to a procedure or a function.
Stored Procedure and Function

Parameter List

Argument List
Difference between Stored
Procedure and Function?
Stored Procedure and Function
• A FUNCTION always returns a value using the return statement. PROCEDURE may return one or more
values through OUT parameter(s) or may not return any at all.
• Functions are normally used for computations where as procedures are normally used for executing
business logic.
• A Function returns 1 value only. Procedure can return multiple values (max 1024).
• A function can be called directly by SQL statement like select func_name from dual while procedures
cannot.

The major difference is that UDFs can be used like any other expression within SQL
statements, whereas stored procedures must be invoked using the CALL statement.
Calling Procedure from Function and contrariwise

• DROP FUNCTION IF EXISTS F1;


delimiter $$
CREATE FUNCTION F1() returns varchar(100)
begin
declare x varchar(100) default 'Hello World';
# SELECT "Hello World"; # ERROR 1415 (0A000): Not allowed to
call p1(x); return a result set from a function
return x;
end $$
delimiter ;

• DROP PROCEDURE IF EXISTS P1;


delimiter $$
CREATE PROCEDURE P1(out para1 varchar(100))
begin
# SELECT "Hello World123"; # ERROR 1415 (0A000): Not allowed to
SELECT "Hello World123" into para1; return a result set from a function
end $$
delimiter ; This will work
SOURCE and CALL Stored
Procedure
SOURCE and CALL Stored Procedure
If you are already running mysql, you can execute an SQL script file using the source command or \.
command

source file_name.sql
\. file_name.sql

MySQL> source pl1.sql;


MySQL> \. file_name.sql;

The CALL statement invokes a stored procedure that was defined previously with CREATE PROCEDURE.
Stored procedures that take no arguments can be invoked without parentheses. That is, CALL sp_name and
CALL sp_name() are equivalent.

CALL sp_name([parameter[,...]])
CALL sp_name[()]

MySQL> call sp_name;


MySQL> call sp_name();
DELIMITER - Statement
By default, mysql itself recognizes the semicolon as a statement delimiter, so you must redefine the
delimiter temporarily to cause mysql to pass the entire stored program definition to the server. To
redefine the mysql delimiter, use the delimiter command.
DROP PROCEDURE IF EXISTS procedurename; DROP FUNCTION IF EXISTS functionname;
delimiter $$ delimiter $$
CREATE PROCEDURE procedurename() CREATE FUNCTION functionname() RETURNS INT
begin begin
statements……. statements…….
end $$ return (something);
delimiter ; end $$
delimiter ;

BEGIN ... END


Compound-Statement
A compound statement is a block that can contain:
• other blocks
• declarations of variables
• declarations of cursors
• declarations of exception handlers
• compound statements
• flow control constructs such as loops and conditional tests.
BEGIN ... END
BEGIN ... END syntax is used for writing compound statements, which can appear within stored programs
(stored procedures and functions, triggers, and events). A compound statement can contain multiple
statements, enclosed by the BEGIN and END keywords. statement_list represents a list of one or more
statements, each terminated by a semicolon (;) statement delimiter. The statement_list itself is optional, so the
empty compound statement (BEGIN END) is legal.

[begin_label:] BEGIN
• DROP PROCEDURE IF EXISTS procedurename;
[statement_list] delimiter $$
. . . . . CREATE PROCEDURE procedurename()
. . . . . begin
declare x BOOL default false;
. . . . .
begin
declare y BOOL default true;
END [end_label] SELECT x;
end ;
SELECT y;
end $$
delimiter ;
DECLARE variable_name datatype(size) [ DEFAULT de- Declaring variables
fault_value ];
1. declare x INT DEFAULT 0; DECLARE variable_name
SET x = 10; datatype(size)
Assigning variables
2. declare y INT;
SET y = 10; 1 DECLARE z INT;
2 SET z = 10;

Note:
DECLARE VARIABLES
• DECLARE is permitted only inside a BEGIN ... END compound statement and must be at its start, before
any other statements.

Remember:
• First, you specify the variable name after the DECLARE keyword. The variable name must follow the
naming rules of MySQL table column names.
• Second, you specify the data type of the variable and its size. A variable can have any MySQL data types
such as INT, VARCHAR , and DATETIME.
• Third, when you declare a variable, its initial value is NULL. You can assign the variable a default value
using the DEFAULT keyword.
Local Variable DECLARE and User-Defined Variables
Local variables are declared within stored procedures and are only valid within the BEGIN…END block
where they are declared. Local variables can have any SQL data type.

DECLARE var_name [, var_name] ... type [DEFAULT value]

User variables in MySQL stored procedures, user variables are referenced with an ampersand (@) prefixed
to the user variable name.

SET @var_name = expr [, @var_name = expr] ...

• DROP PROCEDURE IF EXISTS procedurename; • DROP PROCEDURE IF EXISTS procedurename;


delimiter $$ delimiter $$
CREATE PROCEDURE procedurename() CREATE PROCEDURE procedurename()
begin begin
declare x VARCHAR(12) default 'Infoway'; set @x = 'Infoway';
SELECT x; SELECT @x;
end $$ end $$
delimiter ; delimiter ;
Local Variable DECLARE
Local variables are declared within stored procedures and are only valid within the BEGIN…END block where
they are declared. Local variables can have any SQL data type.

DECLARE var_name [, var_name] ... type [DEFAULT value]

• DROP PROCEDURE IF EXISTS procedurename;


delimiter $$
CREATE PROCEDURE procedurename()
begin
declare x VARCHAR(20);
set x = 'Hello World';
SELECT x;
end $$
delimiter ;
Local Variable DECLARE
• DROP PROCEDURE IF EXISTS procedurename;
delimiter $$
CREATE PROCEDURE procedurename()
begin
declare a INT default 10;
declare b, c INT;
set a = a + 100;
set b = 2;
set c = a + b;
begin
declare c INT;
set c = 5;
SELECT a, b, c;
end;
SELECT a, b, c;
end $$
delimiter ;
A procedure is a group of PL/SQL statements that you can call by name.

Stored Procedure
A procedure is a group of PL/SQL statements that you can call by name.

Remember:
• It is not permitted to assign the value DEFAULT to stored procedure or function parameters
e.g.
PROCEDURE procedurename(in p_ID INT DEFAULT 10)
• Or stored program local variables
e.g.
SET var_name = DEFAULT some_value.
Stored Procedure - Examples
• DROP PROCEDURE IF EXISTS procedurename;
delimiter $$
CREATE PROCEDURE procedurename()
begin
SELECT * FROM emp;
end $$
delimiter ;

• DROP PROCEDURE IF EXISTS procedurename;


delimiter $$
CREATE PROCEDURE procedurename()
begin
declare x VARCHAR(12);
SELECT ename INTO x FROM emp WHERE empno = 7788;
SELECT x;
end $$
delimiter ;
Stored Procedure - Examples
• DROP PROCEDURE IF EXISTS procedurename;
delimiter $$
CREATE PROCEDURE procedurename(IN para1 INT)
begin
declare x VARCHAR(12);
SELECT ename INTO x FROM emp WHERE empno= para1;
SELECT x;
end $$
delimiter ;

• DROP PROCEDURE IF EXISTS procedurename;


delimiter $$
CREATE PROCEDURE procedurename(IN para1 VARCHAR(15))
begin
declare x VARCHAR(12);
SELECT job INTO x FROM emp WHERE ename= para1;
SELECT x;
end $$
delimiter ;
Stored Procedure - Examples
• DROP PROCEDURE IF EXISTS procedurename;
delimiter $$
CREATE PROCEDURE procedurename(IN para1 VARCHAR(12))
begin
SELECT * FROM emp WHERE job=para1;
end $$
delimiter ;

• DROP PROCEDURE IF EXISTS procedurename;


delimiter $$
CREATE PROCEDURE procedurename(IN para1 VARCHAR(12), OUT s INT, OUT j VARCHAR(12))
begin
SELECT para1, SUM(Sal) INTO varJob, varSumSal FROM emp WHERE job=para1;
end $$
delimiter ;
Stored Procedure - Examples
• DROP PROCEDURE IF EXISTS procedurename;
delimiter $$
CREATE PROCEDURE procedurename(IN p1 INT(2), IN p2 VARCHAR(12), IN p3 VARCHAR(10),
IN p4 VARCHAR(20))
begin
INSERT into DEPT values (p1, p2, p3, p4);
end $$
delimiter ;

• DROP PROCEDURE IF EXISTS procedurename;


delimiter $$
CREATE PROCEDURE myprocedure (INOUT p1 INT(2))
begin
set p1 = p1+2;
end $$
delimiter ;

mysql> SET @x = 10
mysql> CALL procudeureName(@x);
mysql> SELECT @x
Stored Procedure - Examples
• DROP PROCEDURE IF EXISTS procedurename;
delimiter $$
CREATE PROCEDURE procedurename()
begin
CREATE TABLE temp (IN col1 INT);
end $$
delimiter ;

• DROP PROCEDURE IF EXISTS procedurename;


delimiter $$
CREATE PROCEDURE procedurename(IN v1 INT, IN v2 VARCHAR(20), IN v3 VARCHAR(20), IN v4
VARCHAR(20))
begin
INSERT INTO dept VALUES (v1, v2, v3, v4);
end $$
delimiter ;
• DROP PROCEDURE IF EXISTS procedurename;
delimiter $$
CREATE PROCEDURE procedurename(IN var1 INT)
begin
SELECT * FROM emp LIMIT var1;
end $$
delimiter ;
Stored Procedure - Examples
• DROP PROCEDURE IF EXISTS procedurename;
delimiter $$
CREATE PROCEDURE procedurename()
begin
CREATE TABLE temp (col1 INT);
end $$
delimiter ;

• DROP PROCEDURE IF EXISTS procedurename;


delimiter $$
CREATE PROCEDURE procedurename(IN x INT, IN y INT, OUT z INT, OUT z1 INT )
begin
SET z = x + y;
SET z1 = x * y;
end $$
delimiter ;
-----------------------------------------------------------------------------------------------
mysql> SET @a := 0;
mysql> SET @b := 0;
mysql> CALL pro1(5, 4, @a, @b);
IF
IF search_condition THEN statement_list
[ELSEIF search_condition THEN statement_list] ...
[ELSE statement_list]
END IF

e.g.
DROP PROCEDURE IF EXISTS procedurename;
delimiter $$
CREATE PROCEDURE procedurename(v_value INT)
begin
if v_value = 0 then
SELECT 'The enter value is 0' as "Message Box";
elseif v_value = 1 THEN
SELECT 'The enter value is 1' as "Message Box";
else
SELECT 'The enter value is neither 0 or 1' as "Message Box";
end if;
end $$
delimiter ;
LOOP
[begin_label:] LOOP ITERATE means "start the loop again."
LEAVE statement is used to exit the flow control construct that has the given label.
statement_list
END LOOP
[end_label]

• ITERATE label
e.g.
• LEAVE label
DROP PROCEDURE IF EXISTS procedurename;
delimiter $$
CREATE PROCEDURE procedurename(v_value INT)
begin
declare x INT default 0;
lbl:loop
set x = x + 1;
SELECT x;
if x = v_value then
leave lbl;
end if;
end loop lbl;
end $$
delimiter ;
Cursor
Steps:
• This statement declares a cursor and associates it with a SELECT statement that retrieves the rows to be
traversed by the cursor.
DECLARE cursor_name CURSOR FOR select_statement

• This statement opens a previously declared cursor.


OPEN cursor_name

• This statement fetches the next row for the SELECT statement associated with the specified cursor (which
must be open), and advances the cursor pointer. If a row exists, the fetched columns are stored in the named
variables. The number of columns retrieved by the SELECT statement must match the number of output
variables specified in the FETCH statement.
FETCH [[NEXT] FROM] cursor_name INTO var_name [, var_name] ...
If no more rows are available, a No Data condition.

• This statement closes a previously opened cursor.


CLOSE cursor_name
Cursor
Q1. Using cursor get all student details.

DROP PROCEDURE IF EXISTS getAllStudent;


delimiter $$

CREATE PROCEDURE getAllStudent()


begin
declare v_ID INT;
declare v_namefirst, v_namelast VARCHAR(45);
declare v_dob DATE;
declare v_emailID VARCHAR(128);
declare cur1 CURSOR FOR SELECT * FROM student;

declare EXIT HANDLER FOR NOT FOUND SELECT "No more student found";
OPEN cur1;
loopLabel: LOOP
FETCH cur1 INTO v_ID, v_namefirst, v_namelast, v_dob, v_emailID;
SELECT v_ID, v_namefirst, v_namelast, v_dob, v_emailID;
END LOOP loopLabel;
CLOSE cur1;
end $$
delimiter ;
Cursor
Q2 Write a program to enter studentID and using cursor get his student qualification details.
DROP PROCEDURE if EXISTS getStudentQualification;
CREATE PROCEDURE getStudentQualification(v_ID INT)
b1:begin
declare x INT;
SELECT ID into x FROM student WHERE ID = v_ID;
if x is null then
SELECT "Student not found....";
else
b2: begin
declare v_name, v_college, v_university VARCHAR(128);
declare v_marks VARCHAR(45);
declare v_year INT;
declare cur1 cursor for SELECT name, college, university, marks, year FROM student_qualifications where studentID = x;
declare exit handler for NOT FOUND SELECT "Done";
OPEN cur1;
lbl:loop
FETCH cur1 INTO v_name, v_college, v_university, v_marks, v_year;
SELECT v_name, v_college, v_university, v_marks, v_year;
end loop lbl;
CLOSE cur1;
end b2;
end if
end b1 $$
delimiter ;
Note:
• By default, all parameters are IN parameters.
• You cannot specify IN , OUT or INOUT modifiers to the parameters.

SET GLOBAL log_bin_trust_function_creators = 1;

FUNCTIONS
The RETURNS clause may be specified only for a FUNCTION, for which it is mandatory. It indicates the
return type of the function, and the function body must contain a RETURN value statement.

Remember:
ERROR 1415 (0A000): Not allowed to return a result set from a function

SELECT "Hello World"; // will not work in FUNCTION


SELECT "Hello World" into x; // will work in FUNCTION
User Defined Function - Examples
• DROP FUNCTION IF EXISTS functionname;
delimiter $$
CREATE FUNCTION functionname() RETURNS INT
begin
declare x INT;
set x = 1001;
return (x);
end $$
delimiter ;

• DROP FUNCTION IF EXISTS functionname;


delimiter $$
CREATE FUNCTION functionname(para1 VARCHAR(12)) RETURNS INT
begin
declare total INT default 0;
SELECT sum(sal) into total from EMP where job=para1;
return (total);
end $$
delimiter ;
User Defined Function - Examples
• DROP FUNCTION IF EXISTS functionname;
delimiter $$
CREATE FUNCTION functionname() RETURNS INT
begin
declare x INT;
SELECT max(deptno) + 1 INTO x FROM dept;
return(x);
end $$
delimiter ;

• DROP FUNCTION IF EXISTS functionname;


delimiter $$
CREATE FUNCTION functionname(no int) RETURNS VARCHAR(20)
begin
declare x VARCHAR(20);
SELECT distinct 'Number present' INTO x FROM t1 WHERE c1 = no;
if x is not null then
return(x);
else
return (no);
end if;
end $$
delimiter ;
TRIGGERS
A trigger is a special type of stored procedure that automatically runs when an event occurs in the
database server. DML triggers run when a user tries to modify data through a data manipulation
language (DML) event. DML events are INSERT, UPDATE, or DELETE statements on a TABLE or
VIEW.
Remember:
• The trigger is always associated with the table named tbl_name, which must refer to a permanent table.
• You cannot associate a trigger with a TEMPORARY table or a VIEW.
• If you drop a table, any triggers for the table are also dropped.
• It is possible to define multiple triggers for a given table that have the same trigger event and action time.
For example, you can have two BEFORE UPDATE triggers for a table. By default, triggers that have the
same trigger event and action time activate in the order they were created.
TRIGGER
The trigger is always associated with the table named tbl_name, which must refer to a permanent table.

CREATE TRIGGER trigger_name


trigger_time trigger_event
ON tbl_name FOR EACH ROW
trigger_body

trigger_time: { BEFORE | AFTER }


trigger_event: { INSERT | UPDATE | DELETE }

• SHOW CREATE TRIGGER trigger_name

DESC INFORMATION_SCHEMA.TRIGGERS
TRIGGER

You put the trigger name after the CREATE TRIGGER statement. The trigger name should follow the naming
convention [trigger time]_[table name]_[trigger event], for example before_employees_update.

Trigger activation time can be BEFORE or AFTER. You must specify the activation time when you define a
trigger. You use the BEFORE keyword if you want to process action prior to the change is made on the table
and AFTER if you need to process action after the change is made.

The trigger event can be INSERT, UPDATE or DELETE. This event causes the trigger to be invoked. A trigger
only can be invoked by one event. To define a trigger that is invoked by multiple events, you have to define
multiple triggers, one for each event.

A trigger must be associated with a specific table. Without a table trigger would not exist therefore you have
to specify the table name after the ON keyword.

You place the SQL statements between BEGIN and END block. This is where you define the logic for the
trigger.
What is trigger_time and trigger_event ?
trigger_time : trigger_time is the trigger action time. It can be BEFORE or AFTER to indicate that the trigger
activates before or after each row to be modified.

trigger_event : trigger_event indicates the kind of operation that activates the trigger.

INSERT: The trigger activates whenever a new row is inserted into the table; for example, through
INSERT statements.
UPDATE: The trigger activates whenever a row is modified; for example, through UPDATE statements.
DELETE: The trigger activates whenever a row is deleted from the table; for example, through DELETE
and REPLACE statements.

Remember:
• DROP TABLE and TRUNCATE TABLE statements on the table do not activate this trigger, because they
do not use DELETE.
• Dropping a partition does not activate DELETE triggers, either.
BEFORE and AFTER
• If a BEFORE trigger fails, the operation on the corresponding row is not performed.

• A BEFORE trigger is activated by the attempt to insert or modify the row or delete the row, regardless of
whether the attempt subsequently succeeds.

• An AFTER trigger is executed only if any BEFORE triggers and the row operation execute successfully.

• An error during either a BEFORE or AFTER trigger results in failure of the entire statement that caused
trigger invocation.
NEW and OLD
The OLD and NEW keywords enable you to access columns in the rows affected by a trigger. OLD and NEW
are MySQL extensions to triggers; they are not case sensitive.

A column named with OLD is read only. In a BEFORE trigger, you can also change its value with
SET NEW.col_name = value.

• In an INSERT trigger, only NEW.col_name can be used; there is no OLD row.


• In a DELETE trigger, only OLD.col_name can be used; there is no NEW row.
• In an UPDATE trigger, you can use OLD.col_name to refer to the columns of a row before it is updated
and NEW.col_name to refer to the columns of the row after it is updated.

The trigger occurs. This can either be BEFORE or AFTER an INSERT, UPDATE or DELETE. A
BEFORE trigger must be used if you need to modify incoming data. An AFTER trigger must be
used if you want to reference the new/changed record as a foreign key for a record in another
table.

A column named with OLD is read only.


NOTE
• The trigger cannot use the CALL statement to invoke stored procedures that return data to the client or that use
dynamic SQL. (Stored procedures are permitted to return data to the trigger through OUT or INOUT parameters.)
DROP TRIGGER
This statement drops a trigger. The schema (database) name is optional. If the schema is omitted, the trigger
is dropped from the default schema.

DROP TRIGGER [IF EXISTS] [schema_name.]trigger_name

If you drop a table, any triggers for the table are also dropped.

As of MySQL 5.7.2, it is possible to define multiple triggers for a given table that have the same trigger event and
action time. For example, you can have two BEFORE UPDATE triggers for a table. By default, triggers that have the
same trigger event and action time activate in the order they were created.
Example of trigger
• DROP TRIGGER IF EXISTS triggername;
delimiter $$
CREATE TRIGGER triggername BEFORE INSERT ON dept FOR EACH ROW
begin
SELECT 'Hello World'; #error
end $$
delimiter ;

ERROR 1415 (0A000): Not allowed to return a result set from a trigger
Example of trigger
• DROP TRIGGER IF EXISTS triggername;
delimiter $$
CREATE TRIGGER triggername AFTER INSERT ON dept FOR EACH ROW
begin
INSERT INTO d1 VALUES (NEW.deptno, NEW.dname, NEW.loc, NEW.pwd);
end $$
delimiter ;

• DROP TRIGGER IF EXISTS triggername;


delimiter $$
CREATE TRIGGER triggername AFTER UPDATE ON dept FOR EACH ROW
begin
INSERT INTO d1 VALUES(OLD.dname, NEW.dname);
end $$
delimiter ;
• DROP TRIGGER IF EXISTS triggername;
delimiter $$
CREATE TRIGGER triggername AFTER DELETE ON dept FOR EACH ROW
begin
INSERT INTO d VALUES(OLD.deptno, OLD.dname, OLD.loc, OLD.pwd, now(), user());
end $$
delimiter ;
Example of trigger
• DROP TRIGGER IF EXISTS triggername;
delimiter $$
CREATE TRIGGER triggername AFTER INSERT ON dept FOR EACH ROW
begin
INSERT INTO d VALUES (NEW.deptno, NEW.dname, NEW.loc, NEW.pwd, now(), user());
end $$
delimiter ;

• DROP TRIGGER IF EXISTS triggername;


delimiter $$
CREATE TRIGGER triggername AFTER INSERT ON dept FOR EACH ROW
begin
if DATE_FORMAT (now(), '%W') = 'Wednesday' then
signal sqlstate '42000' set message_text = 'Invalid';
end if;
end $$
delimiter ;
Example of trigger
• DROP TRIGGER IF EXISTS triggername;
delimiter $$
CREATE TRIGGER triggername BEFORE INSERT ON dept FOR EACH ROW
begin
declare msg VARCHAR(100);
if NEW.dname = 'A' then
set NEW.dname = 'Apple';
else
set msg = 'My error message';
signal sqlstate '42000' set message_text = msg;
end if;
end $$
delimiter ;
• DROP TRIGGER IF EXISTS triggername;
delimiter $$
CREATE TRIGGER triggername BEFORE INSERT ON dept FOR EACH ROW
begin
if NEW.deptno < 50 then
signal sqlstate '42000' set message_text = 'Invalid department number';
end if;
end $$
delimiter ;
Example of trigger
• DROP TRIGGER IF EXISTS triggername;
delimiter $$
CREATE TRIGGER triggername BEFORE INSERT ON dept FOR EACH ROW
begin
if NEW.deptno < 50 then
signal sqlstate '42000' set message_text = 'Invalid department number';
end if;
end $$
delimiter ;

• DROP TRIGGER IF EXISTS triggername;


delimiter $$
CREATE TRIGGER triggername BEFORE INSERT ON emp FOR EACH ROW
begin
if NEW.sal <= 0 then
set NEW.sal = 25000; ERROR 1362 (HY000): Updating of NEW row is not
end if; allowed in after trigger
end $$
delimiter ;
mysql> INSERT INTO emp (empno, ename, sal, mgr, deptno)
VALUES(1, ‘ abc', -10000, 7788, 10);
Example of trigger
• DROP TRIGGER IF EXISTS triggername;
delimiter $$
CREATE TRIGGER triggername BEFORE INSERT ON city FOR EACH ROW
begin
declare msg VARCHAR(100);
if NEW.c1 <> 'Pune' then
set msg = 'Invalid city name';
signal sqlstate '42000' set message_text = msg;
end if;
end $$
delimiter ;

• DROP TRIGGER IF EXISTS triggername;


delimiter $$
CREATE TRIGGER triggername BEFORE INSERT ON dept FOR EACH ROW
begin
set NEW.dname = upper(NEW.dname);
end $$
delimiter ;
mysql> INSERT INTO dept VALUES(2,
'abc', 2, 2);
Example of trigger
• DROP TRIGGER IF EXISTS triggername;
delimiter $$
CREATE TRIGGER triggername BEFORE INSERT ON dept FOR EACH ROW
begin
declare x INT default 0;
SELECT max(id) + 1 INTO x FROM log;
INSERT INTO log VALUES(x, 'Data inserted', curdate(),curtime(), user());
end $$
delimiter ;

• DROP TRIGGER IF EXISTS triggername;


delimiter $$
CREATE TRIGGER triggername BEFORE INSERT on dept FOR EACH ROW
begin
declare x INT;
set x = (SELECT max(deptno) + 1 FROM dept);
set NEW.deptno = x;
end $$
delimiter ;
Example of trigger
• DROP TRIGGER IF EXISTS triggername;
delimiter $$
CREATE TRIGGER triggername BEFORE INSERT ON emp FOR EACH ROW
begin
declare x INT;
set x = (SELECT deptno FROM dept WHERE deptno = NEW.deptno);
if x is null then
signal sqlstate '42000' set message_text = 'error’;
end if;
end $$
delimiter ;

• DROP TRIGGER IF EXISTS triggername;


delimiter $$
CREATE TRIGGER triggername BEFORE INSERT ON dept FOR EACH ROW
begin
declare x INT;
SELECT max(deptno) + 1 INTO x FROM dept;
set NEW.deptno := x;
end $$
delimiter ;
Example of trigger
Difference between BEFORE and AFTER trigger.

• DROP TRIGGER IF EXISTS triggername; • DROP TRIGGER IF EXISTS triggername;


delimiter $$ delimiter $$
CREATE TRIGGER triggername BEFORE INSERT ON CREATE TRIGGER triggername BEFORE INSERT ON
dept FOR EACH ROW dept FOR EACH ROW
begin begin
declare x INT; declare x INT;
SELECT count(*) INTO x FROM dept; SELECT count(*) INTO x FROM dept;
if x > 4 then if x > 4 then
signal sqlstate '42000' set message_text = 'error’; signal sqlstate '42000' set message_text = 'error’;
end if; end if;
end $$ end $$
delimiter ; delimiter ;
Example of trigger
• DROP TRIGGER IF EXISTS triggername;
delimiter $$
CREATE TRIGGER triggername BEFORE INSERT ON dept FOR EACH ROW
begin
set NEW.dname = trim(NEW.dname);
set NEW.loc = trim(NEW.loc);
set NEW.pwd = trim(NEW.pwd);
end $$
delimiter ;
Item, warehouse , item_ordered, … Example of trigger
• DROP TABLE IF EXISTS item;
• DROP TABLE IF EXISTS warehouse;
• DROP TABLE IF EXISTS item_in_warehouse;
• DROP TABLE IF EXISTS item_ordered;

• CREATE TABLE item(itemid INT, itemname VARCHAR(20));


• CREATE TABLE warehouse(warehouse_id INT, warehouse_name VARCHAR(255), channel_id
INT);
• CREATE TABLE item_in_warehouse(id INT PRIMARY KEY AUTO_INCREMENT, item_id INT,
warehouse_id INT, minimum_stock INT, rol INT, stock INT);
• CREATE TABLE item_ordered(orderID INT, itemID INT, orderDate DATE, orderTime
TIME, qty INT);
Item, warehouse , item_ordered, … Example of trigger
• INSERT INTO item VALUES(1, 'SPORTS SHOES');
• INSERT INTO item VALUES(2, 'CASUAL SHOES');
• INSERT INTO item VALUES(3, 'T-SHIRTS');
• INSERT INTO item VALUES(4, 'JEANS');
• INSERT INTO item VALUES(5, 'JACKETS');
• INSERT INTO item VALUES(6, 'SWEATERS');
• INSERT INTO item VALUES(7, 'WATCHES’);

• INSERT INTO warehouse VALUES( 143, 'AC Warehouse', 1);


• INSERT INTO warehouse VALUES( 156, 'National', 2);
• INSERT INTO warehouse VALUES( 231, 'Global', 3);
• INSERT INTO warehouse VALUES( 254, 'NON-STOP', 2);
• INSERT INTO warehouse VALUES( 321, 'Migrant System', 2);
• INSERT INTO warehouse VALUES( 464, 'Blaze', 1);
Item, warehouse , item_ordered, … Example of trigger
• INSERT INTO item_in_warehouse (item_id, warehouse_id) VALUES (1, 143);
• INSERT INTO item_in_warehouse (item_id, warehouse_id) VALUES (2, 156);
• INSERT INTO item_in_warehouse (item_id, warehouse_id) VALUES (3, 231);
• INSERT INTO item_in_warehouse (item_id, warehouse_id) VALUES (5, 254);
• INSERT INTO item_in_warehouse (item_id, warehouse_id) VALUES (3, 321);
• INSERT INTO item_in_warehouse (item_id, warehouse_id) VALUES (1, 464);
• INSERT INTO item_in_warehouse (item_id, warehouse_id) VALUES (6, 156);
• INSERT INTO item_in_warehouse (item_id, warehouse_id) VALUES (1, 156);
• INSERT INTO item_in_warehouse (item_id, warehouse_id) VALUES (7, 464);
• INSERT INTO item_in_warehouse (item_id, warehouse_id) VALUES (6, 321);
• INSERT INTO item_in_warehouse (item_id, warehouse_id) VALUES (5, 464);
• INSERT INTO item_in_warehouse (item_id, warehouse_id) VALUES (4, 321);
• INSERT INTO item_in_warehouse (item_id, warehouse_id) VALUES (3, 464);
• INSERT INTO item_in_warehouse (item_id, warehouse_id) VALUES (6, 231);
Item, warehouse , item_ordered, … Example of trigger
Item, warehouse , item_ordered, … Example of trigger
• DROP TRIGGER IF EXISTS insert_in_item_ordered;
delimiter $$
CREATE TRIGGER insert_in_item_ordered BEFORE INSERT ON item_ordered FOR EACH ROW
begin
declare x INT;
set NEW.orderDate := current_date();
set NEW.orderTime := current_time();
SELECT itemID INTO x FROM item WHERE itemID = NEW.itemID;
if x is null then
signal sqlstate '42000' set message_text = "Item not found in item table!";
end if;
end $$
delimiter ;
Item, warehouse , item_ordered, … Example of trigger
• DROP TRIGGER IF EXISTS itemid_primarykey;
delimiter $$
CREATE TRIGGER itemid_primarykey AFTER INSERT ON item FOR EACH ROW
begin
declare x INT;
SELECT itemid INTO x FROM item WHERE itemid = NEW.itemid;
if x is null then
signal sqlstate '42000' set message_text = 'itemid already present, cannot insert duplicate itemid.';
end if;
end $$
delimiter ;

• DROP TRIGGER IF EXISTS readOnlyItemName;


delimiter $$
CREATE TRIGGER readOnlyItemName AFTER UPDATE ON item FOR EACH ROW
begin
signal sqlstate '42000' set message_text = 'Product name is read-only and it can not be changed.';
end $$
delimiter ;
Item, warehouse , item_ordered, … Example of trigger
• DROP TRIGGER IF EXISTS insert_item_in_warehouse;
delimiter $$
CREATE TRIGGER insert_item_in_warehouse BEFORE INSERT ON item_in_warehouse FOR EACH ROW
begin
declare itemNotFound BOOL default True;
declare warehouseNotFound BOOL default True;
SELECT False INTO warehouseNotFound FROM item WHERE itemid = NEW.item_id;
SELECT False INTO warehouseFound FROM warehouse WHERE warehouse_id = NEW.warehouse_id;
if itemNotFound then
signal sqlstate '42000' set message_text = 'Item not found!’;
end if;
if warehouseNotFound then
signal sqlstate '42000' set message_text = 'Warehouse not found!’;
end if;
end $$
delimiter ;
Item, warehouse , item_ordered, … Example of trigger
DROP TRIGGER IF EXISTS calculate_minimum_stock_ROL;
delimiter $$
CREATE TRIGGER calculate_minimum_stock_ROL BEFORE INSERT ON item_in_warehouse FOR EACH ROW
begin
declare _minimum_stock INT;
declare _ROL INT;
set _minimum_stock := NEW.stock / 2;
set _ROL := _minimum_stock * .25;
set NEW.minimum_stock := _minimum_stock;
set NEW.ROL := _ROL;
end $$
delimiter ;
Bank Example of trigger
• DROP TABLE IF EXISTS customer_Account;

• CREATE TABLE customer_Account (


accountID VARCHAR(20),
customerName VARCHAR(20),
account_Type VARCHAR(20),
openDate DATE,
phone_number VARCHAR(12)
);
Bank Example of trigger
• DROP TRIGGER IF EXISTS customer_AccountID;
delimiter $$
CREATE TRIGGER customer_AccountID BEFORE INSERT ON customer_account FOR EACH ROW
begin
declare x int;
SELECT max(cast(substr(accountID, 5) AS UNSIGNED)) + 1 INTO x FROM customer_account WHERE
account_Type = NEW.account_Type;
if x is null then
if NEW.account_Type = 'saving' then
set NEW.accountID = concat('S/A-', 1);
elseif NEW.account_Type = 'current' then
set NEW.accountID = concat('C/A-', 1);
else
signal sqlstate '42000' set message_text = "Invalid Account Type!";
end if;
else
if NEW.account_Type = 'saving' then
set NEW.accountID = concat('S/A-', x);
else
set NEW.accountID = concat('C/A-', x);
end if;
end if;
end $$
delimiter ;
Bank Example of trigger
• DROP TRIGGER IF EXISTS customer_phone;
delimiter $$
CREATE TRIGGER customer_phone BEFORE INSERT ON customer_account FOR EACH ROW
begin
set NEW.phone_number := rpad(left(NEW.phone_number, 4), 10, 'x');
end $$
delimiter ;

• DROP TRIGGER IF EXISTS open_date;


delimiter $$
CREATE TRIGGER open_date BEFORE INSERT ON customer_account FOR EACH ROW
begin
if NEW.opendate > curDate() then
signal sqlstate '42000' SET message_text = 'Invalid Opening Date!';
end if;
end $$
delimiter ;
Bank Example of trigger
• DROP PROCEDURE IF EXISTS showCustomerAccount;
delimiter $$
CREATE PROCEDURE showCustomerAccount()
begin
SELECT * FROM customer_Account;
end $$
delimiter ;

• DROP TRIGGER IF EXISTS lock_issue_card;


delimiter $$
CREATE TRIGGER lock_issue_card BEFORE INSERT ON credit_card FOR EACH ROW
begin
if @TRIGGER_DISABLED is False or cast(@TRIGGER_DISABLED as char) is null then
set @TRIGGER_DISABLED := True;
signal sqlstate '42000' set message_text = 'You cannot insert data in issue_card table';
end if;
end $$
delimiter ;
Bank Example of trigger
• DROP TRIGGER IF EXISTS issue_card;
delimiter $$
CREATE TRIGGER issue_card BEFORE INSERT ON credit_card FOR EACH ROW
begin
declare x VARCHAR(20);
if @TRIGGER_DISABLED is True then
set @TRIGGER_DISABLED := False;
SELECT accountID INTO x FROM customer_Account WHERE accountID = NEW.accountID;
if x is null then
signal sqlstate '42000' set message_text = 'Invalid Account Number, card cannot be issued! "Contact
customer care!“';
end if;
end if;
end $$
delimiter ;
Bank Example of trigger
• DROP PROCEDURE IF EXISTS issueCard;
delimiter $$
CREATE PROCEDURE issueCard(in _accountID VARCHAR(20), _issueDate DATE, _pin INT, _isactive
BOOL)
begin
if @TRIGGER_DISABLED is True then
INSERT INTO credit_card VALUES(_accountID, _issueDate, _pin, _isactive);
end if;
end $$
delimiter ;
TODO

SQL Injection
TODO

Injection in Insert/Update
TODO

Load- XML
XML file
XML File
<?xml version="1.0" encoding="utf-16"?>
<employees>
<employee>
<id> be129 </id>
<firstname> Jane </firstname>
<lastname> Doe </lastname>
<title> Engineer </title>
</employee>

<employee>
<id> be130 </id>
<firstname> William </firstname>
<lastname> Defoe </lastname>
<title> Accountant </title>
</employee>
</employees>
Table structure for XML file and load XML file.
Example:

CREATE TABLE `EMPLOYEE` (


`id` varchar (45) DEFAULT NULL,
`firstname` varchar (45) DEFAULT NULL,
`lastname` varchar (45) DEFAULT NULL,
`title` varchar (45) DEFAULT NULL
);

LOAD XML INFILE ‘C:\\EMPLOYEE.XML' INTO TABLE EMPLOYEE ROWS


IDENTIFIED BY '<employee>';

SELECT * FROM EMPLOYEE;


Select data from XML using MySQL ExtractValue
Example:
function
SELECT ExtractValue( '<?xml version="1.0" encoding="UTF-8"?>
<student>
<p1>
<id>1001</id>
<name> Saleel Bagde </name>
<email> [email protected] </email>
<email> [email protected] </email>
</p1>
<p1>
<id>1002</id>
<name> Sharmin Bagde </name>
<email> [email protected] </email>
</p1>
</student>', '//student//p1[$1]//email[$2]');
Inserting XML script in table.
Example:
CREATE TABLE `xmlTable` ( `xmlData` text);
INSERT INTO XMLTABLE VALUES (“
<Students>
<student1>
<RollNumber>1</RollNumber>
<Name> Saleel </Name>
<email> [email protected] </email>
<email> [email protected] </email> </student1>
<student2>
<RollNumber> 2 </RollNumber>
<Name> Vrushali </Name>
<email> [email protected] </email>
</student2>
<student3>
<RollNumber> 3 </RollNumber>
<Name> Sharmin </Name>
<email> [email protected] </email>
</student3>
</Students>");
Select from XML script from table.
Example:

SELECT EXTRACTVALUE (xmlData,"//Students//student1//email[$2]") FROM


XMLTABLE;
Inserting XML script in table.
Example:
CREATE TABLE `xmlTable` ( `xmlData` text);
INSERT INTO XMLTABLE VALUES (“
<Students>
<student>
<RollNumber>1</RollNumber>
<Name> Saleel </Name>
<email> [email protected] </email>
<email> [email protected] </email>
</student>
<student>
<RollNumber> 2 </RollNumber>
<Name> Vrushali </Name>
<email> [email protected] </email>
</student>
<student>
<RollNumber> 3 </RollNumber>
<Name> Sharmin </Name>
<email> [email protected] </email>
</student>
</Students>");
Select from XML script from table.
Example:

SELECT EXTRACTVALUE(xmlData,"//Students//student[$1]//email[$2]") FROM


XMLTABLE;
XML file
Employee.xml File
<?xml version="1.0" encoding="utf-16"?>
<employees>
<employee>
<id> be129 </id>
<firstname> Jane </firstname>
<lastname> Doe </lastname>
<title> Engineer </title>
</employee>

<employee>
<id> be130 </id>
<firstname> William </firstname>
<lastname> Defoe </lastname>
<title> Accountant </title>
</employee>
</employees>
Load and select data from external XML file
Example:

SET @xml = LOAD_FILE("E:/employee.xml");


SELECT CONVERT(EXTRACTVALUE(@xml,"//employee[$1]//firstname"),
CHAR);
IMP SQL statements
1. Find 2nd highest salary.
SELECT max(sal) FROM emp WHERE sal < (SELECT max(sal) FROM emp);

2. Find 2nd lowest salary.


SELECT min(sal) FROM emp WHERE sal > (SELECT min(sal) FROM emp);

3. Find 2nd highest salary of each department.


SELECT max(sal) FROM emp WHERE sal NOT IN (SELECT max(sal) FROM emp GROUP BY
deptno) GROUP BY deptno;

4. Find 2nd lowest salary of each department.


SELECT min(sal) FROM emp WHERE sal NOT IN (SELECT min(sal) FROM emp GROUP BY
deptno) GROUP BY deptno;

5. Serial number jobwise.


SELECT @CNT := CASE WHEN job = @JB THEN @CNT + 1 ELSE 1 END R1, @JB := JOB FROM
emp, (SELECT @CNT :=0, @JB := '') E ORDER BY job;
IMP SQL statements
6. Find only the duplicate records.
SELECT * FROM d1 WHERE c1 NOT IN (SELECT min(c1) FROM d1 GROUP BY deptno, dname,
loc, walletid) ORDER BY deptno;

SELECT * FROM (SELECT @cnt1 := @cnt1+1 R1, duplicate.* FROM duplicate,(SELECT


@cnt1:=0) t1) t2 WHERE t2.R1 NOT IN (SELECT min(@cnt := @cnt+1) R1 FROM
duplicate, (SELECT @cnt:=0) t4 GROUP BY deptno, dname, loc, walletid) ORDER BY
deptno;

7. TODO
8. TODO
9. TODO
10. TODO
Interview questions
• What is the difference between CHAR and VARCHAR?

• What is the difference between DELETE, DROP, AND TRUNCATE.

• What is the difference between DELETE TABLE and TRUNCATE TABLE commands in MySQL?

• What is the difference between Inner Join and Natural Join.

• What are types of joins in MySQL?

• What is the difference between primary key and unique key?

• What do you mean my Joins and explain different types of MySQL Joins?

select count(*), e.* from e group by empno, ename, job, mgr, hiredate, sal, comm, deptno, bonusid, `user name`, pwd;
IMP SQL statements
TABLET Id Name Ingredient Unit
Table 1 CROCIN PARACETAMOL 100mg
2 COMBIFLAM PARACETAMOL, IBUPROFEN 25mg
3 DIVON PLUS PARACETAMOL, DICLOFENAC 30mg

Id Name Ingredient Unit


SYRUP
11 BENADRYL DIPHENHYDRAMINE .7mg
Table
12 COMBIFLAM PARACETAMOL, IBUPROFEN 0.12mg
13 COREX CHLORPHENAMINE 2.3mg
14 DICLO DICLOFENAC 0.06mg

INJECTION Id Name Ingredient Unit


Table 21 BRUFEN IBUPROFEN 0.10mg
22 CPM CHLORPHENAMINE 0.25mg
23 VOVERAN DICLOFENAC 0.09mg
IMP
1. Think about how multiplication can be done without actually multiplying

2. Square
"Live as if you were to die tomorrow.
Learn as if you were to live forever"
Input a = 10, find ascii of a variable and store in 65 array

65 a 10

\connect --mysql root@localhost:3306


insert into xmltest values ("<Students>
<student1>
<RollNumber>1</RollNumber>
<Name> Saleel </Name>
</student1>

<student2>
<RollNumber> 2 </RollNumber>
<Name> Vrushali </Name>
</student2>

<student3>
<RollNumber> 3 </RollNumber>
<Name> Sharmin </Name>
</student3>

<student4>
<RollNumber> 4 </RollNumber>
<Name> Ruhan </Name>
</student4>

</Students>");
• Display how many employees are working from every department?
• Display the department name where less the 3 employees are working?
data dictionary
information_schema.table_constraints;
information_schema.key_column_usage;
information_schema.referential_constraints

select north, south, east, west, case field('y’, north, south, east, west) when 1 then 'North' when 2 then 'South' when 3 then
'East' else 'West' end R1 from coalesce;

SELECT weight, TRUNCATE(weight, 0) AS kg, MID(weight, INSTR(weight,".") + 1) AS


gms FROM mass_table;
SELECT - ORDER BY
The ORDER BY clause is used to sort the records in your result set.

SELECT A1, A2, A3, An FROM r

[ORDER BY {A1, A2, A3, . . . | expr | position} [ASC |


DESC], . . . ]

READ SELECT ORDER BY


FROM comm DESC outp
*
emp ut

You might also like