Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 192

Noida Institute of Engineering and Technology, Greater Noida

Content

BASICS OF DATABASE
MANAGEMENT SYSTEM
KOE-067

Unit: 3

Topic: Structured Query Language


Faculty Details:
(SQL)
Mr. Manish Kumar
Assistant Professor
Course Details:
(ECE)
B Tech-EC-6th Sem

Mr. Manish Kumar KOE-067 Unit-3


1
05/07/2024
Evaluation scheme
Content

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 2
Evaluation scheme
Content

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 3
Subject Syllabus
Content
Course Contents / Syllabus
UNIT-I Introduction 8 Hours
Introduction: An overview of database management system, database system vs file system,
database system concepts and architecture, views of data – levels of abstraction, data
models, schema and instances, data independence, database languages and interfaces, data
definition languages, DML, overall database structure, transaction management, storage
management, database users and administrator.
Data Modeling using the Entity Relationship Model: ER model concepts, notation for ER
diagram, mapping constraints, keys, concepts of super key, candidate key, primary key,
generalization, aggregation, reduction of an ER diagrams to tables, extended ER model,
relationships of higher degree.
UNIT-II Relational Database Concepts 8 Hours
Relational Database Concepts: Introduction to relational database, relational database
structure, relational model terminology – domains, attributes, tuples, relations & relational
database schema, integrity constraints, entity integrity, referential integrity, keys constraints,
domain constraints, Relational algebra - relational calculus, tuple and domain calculus, basic
operations – selection and projection, set-theoretic operations, join operations.
Data Base Design & Normalization: Functional dependencies, normal forms, first, second, &
third normal forms, BCNF, inclusion dependence, loss less join decompositions, normalization
using FD, MVD, and JDs, alternative approaches to database design

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 4
Subject Syllabus
Content
Course Contents / Syllabus

UNIT-III SQL 8 hours


Structured Query Language (SQL): Basics of SQL, DDL, DML, DCL, advantage of SQL, SQL
data type and literals, types of SQL commands, SQL operators and their procedure, tables
– creation & alteration, defining constraints, views and indexes, queries and sub queries,
aggregate functions, built-in functions, insert, update and delete operations, joins,
unions, intersection, minus, transaction control commands.
PL/SQL: Introduction, features, syntax and constructs, SQL within Pl/SL, DML in PL/SQL
Cursors, stored procedures, stored function, database triggers, indices
UNIT-IV Transaction Processing Concepts 8 hours
Transaction Processing Concepts: Transaction concepts, properties of transaction, testing
of serializability, Serializability of schedules, conflict & view serializable schedule,
recoverability, recovery from transaction failures, two-phase commit protocol, log based
recovery, checkpoints, deadlock handling.
Concurrency Control Techniques: Concurrency control, locking techniques for
concurrency control, time stamping protocols for concurrency control, validation based
protocol, multiple granularity, multi-version schemes, recovery with concurrent
transaction.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 5
Subject Syllabus
Content
Course Contents / Syllabus

UNIT-V Database Security 8 hours


Database Security – Types of security, system failure, backup & recovery techniques,
authorization & authentication, system policies, levels of security – physical, OS, network
& DBMS, privileges – grant & revoke.
Recent Trends in Database Management Systems: Centralized and Client-Server
Architectures, Distributed Databases, Object-Oriented Database, Spatial & Temporal
Databases, Decision Support Systems, Data Analysis, Data Mining & Warehousing, Data
Visualization, Mobile Databases, OODB & XML Databases, Multimedia & Web Databases,
Spatial and Geographical Databases, Web and Mobile Databases, Active Databases

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 6
Text Books
Content

Text books:
1. Elmasri, Navathe, “Fundamentals of Database System”,
Addision Wesley.
2. Korth, Silbertz, Sudarshan, “Database Concepts”, Mc Graw
Hill.
3. Bipin C. Desai, “An Introduction to Database System”,
Galgotia Publication.
4. Majumdar & Bhattacharya, “Database Management System”,
McGraw Hill.
5. Date C.J., “An Introduction to Database System”, Addision
Wesley.

05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 7


Branch wise Applications
Content

1. Railway Reservation System


2. Library Management System
3. Banking
4. Education Sector
5. Credit card exchanges
6. Social Media Sites
7. Broadcast communications
8. Account
9. Online Shopping
10. Airline Reservation System
11. Manufacturing

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 8
CourseContent
Objectives

The Objective of the Student is to:


1. Describe the features of a database system and its
application and compare various types of data models.
2. Construct an ER Model for a given problem and
transform it into a relation database schema.
3. Formulate solution to a query problem using SQL
Commands, relational algebra, tuple calculus and
domain calculus.
4. Explain the need of normalization and normalize a
given relation to the desired normal form.
5. Explain different approaches of transaction processing
and concurrency control.
05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 9
Course Outcomes
Content (COs)

05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 10


Program Outcomes
Content

• Program Outcomes are narrow statements that describe what the students
are expected to know and would be able to do upon the graduation.
• These relate to the skills, knowledge, and behavior that students acquire
through the programmed.
1. Engineering knowledge
2. Problem analysis
3. Design/development of solutions
4. Conduct investigations of complex problems
5. Modern tool usage
6. The engineer and society
7. Environment and sustainability
8. Ethics
9. Individual and team work
10. Communication
11. Project management and finance
12. Life-long learning
05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 11
CO-PO Mapping
Content

CO.K PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12

KOE 067.1 2 2 3 3 3 2 3 2 2 2 2 3

KOE 067.2 3 3 3 2 2 2 2 2 2 2 2 3

KOE 067.3
2 3 3 3 3 2 2 2 2 2 2 2

KOE 067.4
2 3 2 2 2 2 2 2 2 3 2 2

KOE 067.5
2 3 2 2 2 3 2 2 3 2 2 2

05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 12


Program Specific Outcomes (PSOs)
Content

• Program Specific Outcomes (PSOs) are what the students should be able to do
at the time of graduation. The PSOs are program specific. PSOs are written by
the department offering the program. On successful completion of B. Tech. (EC)
Program, the Electronics and Communication engineering graduates will be able
to:
PSO1: To apply the knowledge of mathematics, science and electronics &
communication engineering to work effectively in the industry based on
same or related area.
PSO2: To use their skills to work in modern electronics & communication
engineering tools, software and equipments to design solutions for complex
problems in the related field that meet the specified needs of the society.
PSO3: To function effectively as an individual and as a member or leader of a team
by qualifying through examinations like GATE (Graduate Aptitude Test in
Engineering), IES (Indian Engineering Services), PSUs (Public Sector
Undertakings), TOEFL (Test of English as a Foreign Language), GMAT
(Graduate Management Admission Test) and GRE (Graduate Record
Examinations in US) etc.

05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 13


CO-PSO Mapping
Content

Mapping of Course Outcomes and Program Specific


Outcomes:

Course Outcome PSO1 PSO2 PSO3


CO 1 1 2 2
CO 2 1 3 1
CO 3 1 3 1
CO 4 1 3 1
CO 5 1 2 -
Average 1 2.6 1

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 14
Program EducationalContent
Objectives(PEOs)

• The Program Educational Objectives (PEOs) of an engineering degree program are the
statements that describe the expected achievements of graduates in their career, and what the
graduates are expected to perform and achieve during the first few years after graduation.

PEO1: To have an excellent scientific and engineering breadth so as to comprehend, analyze,


design and solve real-life problems using state-of-the-art technology.

PEO2: To lead a successful career in industries or to pursue higher studies or to understand


entrepreneurial endeavours.

PEO3: To effectively bridge the gap between industry and academics through effective
communication skill, professional attitude and a desire to learn.

05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 15


Result Analysis
Content

Faculty Subject Section A Section B Section C Section D


Name Code
Mr. Kamal K 100 % 100 % 100 % 100 %
Bhatia

05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 16


Question Paper Template
Content

05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 17


Question Paper Template
Content (Cont……)

05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 18


Syllabus for Unit-3
Content

UNIT 3
Structured Query Language (SQL): Basics of SQL, DDL, DML, DCL,
advantage of SQL, SQL data type and literals, types of SQL commands,
SQL operators and their procedure, tables –creation & alteration, defining
constraints, views and indexes, queries and sub queries ,aggregate
functions, built-in functions, insert, update and delete operations, joins,
unions,intersection, minus, transaction control commands.
PL/SQL: Introduction, features, syntax and constructs, SQL within Pl/SL,
DML in PL/SQL Cursors, stored procedures, stored function, database
triggers, indices

05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 19


Prerequisite
Content

– Relational Database Concepts


– Data Base Design & Normalization

05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 20


Content
Brief Introduction about the subject

• The course aims at imparting basic principles of DBMS with


the features of a database system and its application and
compare various types of data models, Construct an ER Model
for a given problem and transform it into a relation database
schema and finally Formulate solution to a query problem
using SQL Commands, relational algebra, tuple calculus and
domain calculus.

05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 21


Prerequisite
Content

Relational Data Model


Keys
Relational Integrity Constraint
Relational Algebra
Join Operation
Relational Calculus

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 22
Unit Outcomes & Objectives
Content

• Student will be able to manage data efficiently by using a database


management system. Normalization process reduces the update, insert
and deletion anomalies when there is change in database.

05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 23


TopicContent
Objectives

• Data will be managed efficiently by using a database management system.


• Normalization process reduces the update, insert and deletion anomalies
when there is change in database.

05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 24


Introduction on SQL:
Content (CO3)

• IBM Sequel language developed as part of System R project at


the IBM San Jose Research Laboratory
• Renamed Structured Query Language (SQL)
• ANSI(American National Standards Institute) and ISO
(International Organization for Standardization) standard SQL:
– SQL-86
– SQL-89
– SQL-92
– SQL:1999 (language name became Y2K compliant!)
– SQL:2003
• Commercial systems offer most, if not all, SQL-92 features, plus
varying feature sets from later standards and special
proprietary features.
– Not all examples here may work on your particular system.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 25
Content
Basics of SQL

• SQL stands for Structured Query Language.


• It is used for storing and managing data in relational database
management system (RDMS).
• It is a standard language for Relational Database System. It
enables a user to create, read, update and delete relational
databases and tables.
• All the RDBMS like MySQL, Informix, Oracle, MS Access and SQL
Server use SQL as their standard database language.
• SQL allows users to query the database in a number of ways,
using English-like statements.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 26
Content
Basics of SQL

Advantages of SQL –
1. High speed
Using the SQL queries, the user can quickly and efficiently retrieve a
large amount of records from a database.
2. No coding needed
In the standard SQL, it is very easy to manage the database system.
It doesn't require a substantial amount of code to manage the
database system.
3. Well defined standards
Long established are used by the SQL databases that are being used
by ISO and ANSI.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 27
Content
Basics of SQL

4. Portability
SQL can be used in laptop, PCs, server and even some mobile
phones.
5. Interactive language
SQL is a domain language used to communicate with the database.
It is also used to receive answers to the complex questions in
seconds.
6. Multiple data view
Using the SQL language, the users can make different views of the
database structure.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 28
Content & DCL
DDL,DML,DQL

• Queries to deal with relational database can be categorized as-


1. DDL – Data Definition Language
2. DML – Data Manipulation Language
3. DQL – Data Query Language
4. DCL – Data Control Language

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 29
Content & DCL
DDL,DML,DQL

1. DDL or Data Definition Language


• It is used to define the structure of the database.
• CREATE TABLE, ADD COLUMN, DROP COLUMN, etc

2. DML or Data Manipulation Language


• It is used to manipulate the data in the database.
• INSERT, DELETE , UPDATE, etc

3. DCL or Data Control Language


• It deals with the rights, permissions and other controls of the
database.
• GRANT, REVOKE
Mr. Manish Kumar KOE-067 Unit-3
05/07/2024 30
Content & DCL
DDL,DML,DQL

4. DQL or Data Query Language


• It is used to define the structure of the database.
• SELECT

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 31
Content & DCL
DDL,DML,DQL

EX-
Table 1 shows the relational database with name STUDENT.

STUDENT
ROLL_NO NAME ADDRESS PHONE AGE
1 RAM DELHI 1234567 18
2 RAMESH GURGAON 456789 18
3 SUJIT ROHTAK 567891 20
4 SURESH DELHI 145867 17

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 32
Content & DCL
DDL,DML,DQL

Case 1: If we want to retrieve attributes ROLL_NO and NAME of all


students
SELECT ROLL_NO,NAME FROM STUDENT;

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 33
Content & DCL
DDL,DML,DQL

Case 2: If we want to retrieve attributes ROLL_NO and NAME of


students whose roll no is greater than 2

SELECT ROLL_NO,NAME FROM STUDENT


WHERE ROLL_NO >2;

ROLL_NO NAME
3 SUJIT
4 SURESH

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 34
Content & DCL
DDL,DML,DQL

Case 3: If we want to retrieve all the attributes of students


SELECT * FROM STUDENT
WHERE ROLL_NO >2 ;

ROLL_NO NAME ADDRESS PHONE AGE

3 SUJIT ROHTAK 567891 20

4 SURESH DELHI 145867 17

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 35
Content
Types of SQL Commands

• SQL commands are instructions.

• It is used to communicate with the database. It is also used to perform


specific tasks, functions, and queries of data.

• There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 36
Content
Types of SQL Commands

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 37
Content
Types of SQL Commands

1. DDL – Data Definition Language


These commands are used to define Database Schema.

a) CREATE – This is command used to create a database ,table etc


SYNTAX-
CREATE DATABASE database_name;
Eg-
CREATE DATABASE my_database;

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 38
Content
Types of SQL Commands

SYNTAX-
CREATE TABLE table_name
(Column1 datatype(size),
Column2 datatype(size),
……..
Column100datatype(size) );
Eg-
CREATE TABLE students
(
ROLL_NO int(3), NAME varchar(20), SUBJECT varchar(40)
);

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 39
Content
Types of SQL Commands

b) DROP – This is command used to delete entire database ,table


SYNTAX-
DROP DATABASE database_name;
Eg-
DROP DATABASE my_database;

DROP TABLE table_name;


Eg-
DROP TABLE students;

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 40
Content
Types of SQL Commands

c) ALTER –
• This is command used to alter the structure of the database.
• Used to add, delete/drop, modify columns in existing database.

• ALTER TABLE – ADD


- used to add columns into the existing table
SYNTAX-

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 41
Content
Types of SQL Commands

• ALTER TABLE – DROP


- Used to drop column in a table.
- Deleting the unwanted columns from the table.

SYNTAX-

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 42
Content
Types of SQL Commands

• ALTER TABLE – MODIFY


- It is used to modify the existing columns in a table
SYNTAX-

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 43
Content
Types of SQL Commands

d) TRUNCATE–
• This command is used to delete complete data from an existing
table..

SYNTAX-
TRUNCATE TABLE table_name;

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 44
Content
Types of SQL Commands
2. DML – Data Manipulation Language
These commands are used to manipulate the data present in
database.

a) INSERT –
SYNTAX-
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

INSERT INTO table_name


VALUES (value1, value2, value3, ...);

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 45
Content
Types of SQL Commands

b) UPDATE –
It is used to modify the existing records in a table.

SYNTAX-
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 46
Content
Types of SQL Commands

c) DELETE –
It is used to delete the existing records in a table.

SYNTAX-
DELETE FROM table_name WHERE condition;

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 47
Content
Types of SQL Commands

3. DCL – Data Control Language

• It provides the administrators, to remove and set database


permissions to desired users as needed.
• These commands are employed to grant, remove and deny
permissions to users for retrieving and manipulating a database.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 48
Content
Types of SQL Commands
GRANT Command
• It is employed to grant a privilege to a user.
• GRANT command allows specified users to perform specified
tasks.
SYNTAX-
GRANT privlege_name on objectname to user;

Where,
• privilege names are SELECT,UPDATE,DELETE,INSERT,ALTER,ALL
• objectname is table name
• user is the name of the user to whom we grant privileges

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 49
Content
Types of SQL Commands
• REVOKE Command
• It is employed to remove a privilege from a user. REVOKE helps
the owner to cancel previously granted permissions

SYNTAX-
REVOKE privlege_name on objectname from user;

Where,
• privilege names are SELECT,UPDATE,DELETE,INSERT,ALTER,ALL
• objectname is table name
• user is the name of the user whose privileges are removing

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 50
Content
Types of SQL Commands
• Example
GRANT SELECT, UPDATE ON employees to Bhanu;

REVOKE SELECT, UPDATE ON employees to Bhanu;

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 51
Disadvantages of SQL:
Content (CO3)

 SQL doesn’t provide the programmers with a technique of


condition checking, looping and branching.
 SQL statements are passed to Oracle engine one at a time
which increases traffic and decreases speed.
 SQL has no facility of error checking during manipulation of
data.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 52
Data Types in SQL
Content (CO3)

Binary Datatypes

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 53
Data Types in SQL
Content (CO3)

Exact Numeric Datatype

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 54
Data Types in SQL
Content (CO3)

Approximate Numeric Datatype

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 55
Data Types in SQL
Content (CO3)

Character String Datatype

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 56
Data Types in SQL
Content (CO3)

Unicode Character String Datatype

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 57
Data Types in SQL
Content (CO3)

Date and Time Datatype

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 58
SQL_operators in SQL
Content (CO3)

SQL_operators

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 59
Content
SQL Data Operators
• The manipulation and retrieving of the data are performed with
the help of data operators which are used to perform arithmetic
operations, logical operations, comparison operations,
compound operations, etc.
• In SQL, an operator can either be a unary or binary operator.
• The unary operator uses only one operand for performing the
unary operation, whereas
• The binary operator uses two operands for performing the binary
operation.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 60
Content
SQL Data Operators
• SQL operators are categorized in the following categories:
1. SQL Arithmetic Operators
2. SQL Comparison Operators
3. SQL Logical Operators
4. SQL Set Operators
5. SQL Bit-wise Operators
6. SQL Unary Operators

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 61
Content
SQL Data Operators
a) SQL Arithmetic Operators
Following are the various arithmetic operators performed on the
SQL data:
1. SQL Addition Operator (+)
2. SQL Subtraction Operator (-)
3. SQL Multiplication Operator (+)
4. SQL Division Operator (/)
5. SQL Modulus Operator (%)

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 62
Content
SQL Data Operators

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 63
Content
SQL Data Operators
Example-
Employee_details table, which has four columns Emp_Id,
Emp_Name, Emp_Salary, and Emp_Monthlybonus.
Emp Id Emp Name Emp Salary Emp
Monthlybonus
101 Tushar 25000 4000
102 Anuj 30000 200

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 64
Content
SQL Data Operators
Suppose, we want to add 20,000 to the salary of each employee
specified in the table.
QUERY-
SELECT EmpId, EmpName, EmpSalary,
EmpSalary + 20000 FROM Employee_details;

Emp Emp Emp Emp Salary


Id Name Salary + 20000

101 Tushar 25000 45000


102 Anuj 30000 50000

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 65
Content
SQL Data Operators
QUERY-
SELECT EmpId, EmpName, EmpSalary, EmpSalary + 20000 as Emp
NewSalary FROM Employee_details;

Emp Emp Emp Emp New


Id Name Salary Salary

101 Tushar 25000 45000


102 Anuj 30000 50000

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 66
Content
SQL Data Operators
b) SQL Comparison Operators
• The Comparison Operators in SQL compare two different data of SQL
table and check whether they are the same, greater, and lesser.
• The SQL comparison operators are used with the WHERE clause in the
SQL queries.

1. SQL Equal Operator (=)


2. SQL Not Equal Operator (!=)
3. SQL Greater Than Operator (>)
4. SQL Greater Than Equals to Operator (>=)
5. SQL Less Than Operator (<)
6. SQL Less Than Equals to Operator (<=)

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 67
Content
SQL Data Operators
b) SQL Comparison Operators

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 68
Content
SQL Data Operators

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 69
Content
SQL Data Operators
Example-
Employee_details table, which has four columns Emp_Id,
Emp_Name, Emp_Salary, and Emp_Monthlybonus.
Emp Id Emp Name Emp Salary Emp
Monthlybonus
101 Tushar 25000 4000
102 Anuj 30000 200
103 Raj 30000 100

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 70
Content
SQL Data Operators
Suppose, we want all the records of those employees from
the Employee_details table whose salary is not 25000.

QUERY-
SELECT * FROM Employee_details WHERE Emp_Salary != 25000;

Emp Id Emp Name Emp Salary Emp


Monthlybonus
102 Anuj 30000 200
103 Raj 30000 100

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 71
Content
SQL Data Operators
c) SQL Logical Operators
• Following are the various logical operators which are performed
on the data stored in the SQL database tables:
1. SQL ALL operator
2. SQL AND operator
3. SQL OR operator
4. SQL BETWEEN operator
5. SQL IN operator
6. SQL NOT operator
7. SQL ANY operator
8. SQL LIKE operator

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 72
Content
SQL Data Operators
1. SQL ALL operator
• The ALL operator in SQL compares the specified value to all the
values of a column from the sub-query in the SQL database.
• This operator is always used with the following statement:
1. SELECT,
2. HAVING, and
3. WHERE.

SYNTAX
SELECT column_Name1, ...., column_NameN FROM table_Name
WHERE column Comparison_operator ALL (SELECT column FROM table
name2)

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 73
Content
SQL Data Operators
Example-
Employee_details table, which has four columns Emp_Id,
Emp_Name, Emp_Salary, and Emp_City.
Emp Id Emp Name Emp Salary Emp City
101 Tushar 25000 Delhi
102 Anuj 30000 Jaipur
103 Raj 35000 Noida

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 74
Content
SQL Data Operators
If we want to access the employee id and employee names of those
employees from the table whose salaries are greater than the salary
of employees who lives in Jaipur city

QUERY-
SELECT Emp_Id, Emp_Name FROM Employee_details WHERE Emp_
Salary > ALL ( SELECT Emp_Salary FROM Employee_details WHERE
Emp_City = Jaipur)

Emp Id Emp Name


103 Raj

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 75
Content
SQL Data Operators
2. SQL AND operator
The AND operator in SQL would show the record from the database
table if all the conditions separated by the AND operator evaluated
to True.

SYNTAX
SELECT column1, ...., columnN FROM table_Name WHERE condition
1 AND condition2 AND condition3 AND ....... AND conditionN;

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 76
Content
SQL Data Operators
Suppose, we want to access all the records of those employees
from the Employee_details table whose salary is 25000 and the city
is Delhi.

QUERY-
SELECT * FROM Employee_details WHERE Emp_Salary = 25000 AND
Emp_City = 'Delhi';

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 77
Content
SQL Data Operators
3. SQL OR operator
QUERY
SELECT * FROM Employee_details WHERE Emp_Salary = 25000 AND
Emp_City = 'Delhi’;

4. SQL BETWEEN operator

QUERY
SELECT * FROM Employee_details WHERE Emp_Salary BETWEEN 30
000 AND 45000;

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 78
Content
SQL Data Operators
5. SQL IN operator
The IN operator in SQL allows database users to specify two or
more values in a WHERE clause.
This logical operator minimizes the requirement of multiple OR
conditions.

SYNTAX
SELECT column_Name1, column_Name2 ...., column_NameN FROM
table_Name WHERE column_name IN (list_of_values);

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 79
Content
SQL Data Operators
Example-
Employee_details table, which has four columns Emp_Id,
Emp_Name, Emp_Salary, and Emp_City.
Emp Id Emp Name Emp Salary Emp City
101 Tushar 25000 Delhi
102 Anuj 30000 Jaipur
103 Raj 35000 Noida

104 Raman 40000 Patna

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 80
Content
SQL Data Operators
Suppose, we want to show all the information of those employees
from the Employee_details table whose Employee Id is 102, 103,
and 104.

QUERY-
SELECT * FROM Employee_details WHERE Emp_Id IN (102, 103, 104
);

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 81
Content
SQL Data Operators
6. SQL ANY operator
The ANY operator in SQL shows the records when any of the values
returned by the sub-query meet the condition.

SYNTAX
SELECT column1, column2 ...., columnN FROM table_Name WHERE
column_name comparison_operator ANY ( SELECT column_name F
ROM table_name WHERE condition(s)) ;

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 82
Content
SQL Data Operators
7. SQL LIKE operator
• The LIKE operator in SQL shows those records from the table
which match with the given pattern specified in the sub-query.
• The percentage (%) sign is a wildcard which is used in
conjunction with this logical operator.
• This operator is used in the WHERE clause with the following
three statements:
1. SELECT statement
2. UPDATE statement
3. DELETE statement

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 83
Content
SQL Data Operators
SYNTAX
SELECT column_Name1, column_Name2 ...., column_NameN FR
OM table_Name WHERE column_name LIKE pattern;

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 84
Content
SQL Data Operators
Example-
Employee_details table, which has four columns Emp_Id,
Emp_Name, Emp_Salary, and Emp_City.
Emp Id Emp Name Emp Salary Emp City
101 Tushar 25000 Delhi
102 Anuj 30000 Jaipur
103 Raj 35000 Noida

104 Raman 40000 Patna

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 85
Content
SQL Data Operators
1. If we want to show all the information of those employees from
the Employee_details whose name starts with ‘’r‘’

QUERY-
SELECT * FROM Employee_details WHERE Emp_Name LIKE ’r%' ;

2. If we want to show all the information of those employees from


the Employee_details whose name ends with ‘’j‘’.

QUERY-
SELECT * FROM Employee_details WHERE Emp_Name LIKE ’%j' ;

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 86
Content
SQL Data Operators
3. If we want to show all the information of those employees from
the Employee_detailswhose name starts with ‘’r'' and ends with
‘’j''
QUERY-
SELECT * FROM Employee_details WHERE Emp_Name LIKE ’r%j' ;

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 87
Content& ALTERATION
Tables - CREATION

CREATE – This is command used to create a database ,table

SYNTAX-
CREATE DATABASE database_name;
Eg-
CREATE DATABASE my_database;

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 88
Content& ALTERATION
Tables - CREATION

SYNTAX-
CREATE TABLE table_name
(Column1 datatype(size),
Column2 datatype(size),
……..
Column100datatype(size) );
Eg-
CREATE TABLE students
(
ROLL_NO int(3), NAME varchar(20), SUBJECT varchar(40)
);

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 89
Content& ALTERATION
Tables - CREATION

Example-
Create a table called “Persons” that contains five columns:
PeronID, LastName, FirstName, Address, City;

CREATE TABLE Persons


(PeronID int,
Lastname varchar(255),
Firstname varchar(255),
Address varchar(255),
City varchar(255));

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 90
Content& ALTERATION
Tables - CREATION

Example-
Create a new table called “Testtables” which I a copy of the
‘customer’

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 91
Content& ALTERATION
Tables - CREATION

ALTER –
• This is command used to alter the structure of the database.
• Used to add, delete/drop, modify columns in existing database.
ALTER TABLE Student RENAME COLUMN NAME TO FIRST_NAME;
• ALTER TABLE – ADD
- used to add columns into the existing table
SYNTAX-

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 92
Content& ALTERATION
Tables - CREATION

Example-
Add an “email” column to the “customers” table.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 93
Content& ALTERATION
Tables - CREATION

• ALTER TABLE – DROP


- Used to drop column in a table.
- Deleting the unwanted columns from the table.

SYNTAX-

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 94
Content& ALTERATION
Tables - CREATION

Example-
Delete an “email” column from the “customers” table.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 95
Content& ALTERATION
Tables - CREATION

• ALTER TABLE – MODIFY


- It is used to modify the existing columns in a table
SYNTAX-

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 96
Content
Specifying Constraints in SQL

• Specifying Attribute constraints & Attribute Defaults

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 97
Content
Specifying Constraints in SQL

• Specifying Attribute constraints & Attribute Defaults

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 98
Content
Specifying Constraints in SQL

Example:
• Specifying a default manager for a new department and a default
department for a new employee.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 99
Content
Specifying Constraints in SQL

Example:

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 100
Content
Specifying Constraints in SQL

CHECK Clause: It is used for restricting attribute or domain values.


Example:
• suppose that department numbers are restricted to integer numbers
between 1 and 20; then, we can change the attribute declaration of
Dnumber in the DEPARTMENT table to the following:

Dnumber INT NOT NULL CHECK (Dnumber > 0 AND Dnumber < 21);
• The CHECK clause can also be used in conjunction with the CREATE
DOMAIN statement.
Example:
we can write the following statement:
CREATE DOMAIN D_NUM AS INTEGER
CHECK (D_NUM > 0 AND D_NUM < 21);
Mr. Manish Kumar KOE-067 Unit-3
05/07/2024 101
Content
Specifying Constraints in SQL

Specifying Key and Referential Integrity Constraints

• The primary key of DEPARTMENT can be specified as follows:


Dnumber INT PRIMARY KEY
• Referential integrity is specified via the FOREIGN KEY clause,
FOREIGN KEY (Dnum) REFERENCES DEPARTMENT(Dnumber) ;

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 102
INDEXContent
Statement

CREATE INDEX Syntax


• Creates an index on a table. Duplicate values are allowed:
CREATE INDEX index_name
ON table_name (column1, column2, ...);
CREATE UNIQUE INDEX Syntax
• Creates an index on a table. Duplicate values are not allowed:
CREATE UNIQUE INDEX index_name
ON table_name (column1, column2, ...);

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 103
INDEXContent
Statement

CREATE INDEX Example


• The SQL statement below creates an index named "idx_lastname" on
the "LastName" column in the "Persons" table:
CREATE INDEX idx_lastname
ON Persons (LastName);
• If you want to create an index on a combination of columns, you can
list the column names within the parentheses, separated by commas:
CREATE INDEX idx_pname
ON Persons (LastName, FirstName);

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 104
INDEXContent
Statement

DROP INDEX Statement


• This statement is used to delete an index in a table.

SQL Server:
DROP INDEX table_name.index_name;

MySQL:
ALTER TABLE table_name
DROP INDEX index_name;

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 105
Content Function
SQL Aggregate

• SQL aggregation function is used to perform the calculations on


multiple rows of a single column of a table.

• It returns a single value.

• It is also used to summarize the data.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 106
Content Function
SQL Aggregate
Types of SQL Aggregation Function

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 107
Content Function
SQL Aggregate
COUNT-
• It is used to Count the number of rows in a database table. It can
work on both numeric and non-numeric data types.
• COUNT function uses the COUNT(*) that returns the count of all
the rows in a specified table.
• COUNT(*) considers duplicate and Null.

SYNTAX-
COUNT(*)
or
COUNT( [ALL|DISTINCT] expression )

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 108
Content Function
SQL Aggregate
PRODUCT MAST
PRODUCT COMPANY QTY RATE COST
Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Cpm1 3 25 75
Item7 Com1 5 30 150
Item8 Com1 3 10 30
Item9 Com2 2 25 50
Item10 Com3 Mr. Manish Kumar 4 KOE-067 Unit-3
30 120
05/07/2024 109
Content Function
SQL Aggregate
• QUERY 1
SELECT COUNT(*)
FROM PRODUCT_MAST;

• QUERY 2
SELECT COUNT(*)
FROM PRODUCT_MAST;
WHERE RATE>=20;

• QUERY 3
SELECT COUNT(DISTINCT COMPANY)
FROM PRODUCT_MAST;

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 110
Content Function
SQL Aggregate
• Output = 10
• Output = 7
• Output = 3

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 111
Content Function
SQL Aggregate
SUM-
• Sum function is used to calculate the sum of all selected
columns.
• It works on numeric fields only.

SYNTAX-
SUM ()
or
SUM ( [ALL|DISTINCT] expression )

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 112
Content Function
SQL Aggregate
• QUERY 1
SELECT SUM(COST)
FROM PRODUCT_MAST;

• QUERY 2
SELECT SUM(COST)
FROM PRODUCT_MAST
WHERE QTY>3;

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 113
Content Function
SQL Aggregate
• Output = 670
• Output = 320

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 114
Content Function
SQL Aggregate
AVG Function-
• The AVG function is used to calculate the average value of the
numeric type.
• AVG function returns the average of all non-Null values.

SYNTAX-
AVG ()
or
AVG ( [ALL|DISTINCT] expression )

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 115
Content Function
SQL Aggregate
• QUERY 1
SELECT AVG(COST)
FROM PRODUCT_MAST;

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 116
Content Function
SQL Aggregate
• Output = 67.00

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 117
Content Function
SQL Aggregate
MAX Function-
• MAX function is used to find the maximum value of a certain
column.
• This function determines the largest value of all selected values
of a column.

SYNTAX-
MAX ()
or
MAX ( [ALL|DISTINCT] expression )

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 118
Content Function
SQL Aggregate
• QUERY 1
SELECT MAX (RATE)
FROM PRODUCT_MAST;

Output = ???

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 119
Content Function
SQL Aggregate
MIN Function-
• MIN function is used to find the minimum value of a certain
column.
• This function determines the smallest value of all selected values
of a column..

SYNTAX-
MIN ()
or
MIN ( [ALL|DISTINCT] expression )

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 120
Content Function
SQL Aggregate
• QUERY 1
SELECT MIN (RATE)
FROM PRODUCT_MAST;

Output = ???

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 121
Content
SQL Joins
• A SQL Join statement is used to combine data or rows from two
or more tables based on a common field between them.
• Different types of Joins are:

1. (INNER) JOIN: Returns records that have matching values in


both tables
2. LEFT (OUTER) JOIN: Returns all records from the left table, and
the matched records from the right table
3. RIGHT (OUTER) JOIN: Returns all records from the right table,
and the matched records from the left table
4. FULL (OUTER) JOIN: Returns all records when there is a match in
either left or right table

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 122
Content
SQL Joins
Consider the two tables below:
Student

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 123
Content
SQL Joins
Student Course

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 124
Content
SQL Joins
1. INNER JOIN
• The INNER JOIN keyword selects all rows from both the tables as
long as the condition satisfies.
• This keyword will create the result-set by combining all rows
from both the tables where the condition satisfies i.e value of the
common field will be same.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 125
Content
SQL Joins
SYNTAX –
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;

Where-
table1: First table.
table2: Second table
matching_column: Column common to both the tables.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 126
Content
SQL Joins
QUESTION- Write a query that will show the Course Id, names and
age of students enrolled in different courses.

SYNTAX –

SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE


FROM Student
INNER JOIN StudentCourse
ON Student.ROLL_NO = StudentCourse.ROLL_NO;

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 127
Content
SQL Joins
OUTPUT

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 128
Content
SQL Joins
2. LEFT JOIN
• This join returns all the rows of the table on the left side of the
join and matching rows for the table on the right side of join.
• The rows for which there is no matching row on right side, the
result-set will contain null.
• LEFT JOIN is also known as LEFT OUTER JOIN.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 129
Content
SQL Joins
SYNTAX –
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;

Where-
table1: First table.
table2: Second table
matching_column: Column common to both the tables.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 130
Content
SQL Joins
QUESTION-

SYNTAX –

SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
LEFT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 131
Content
SQL Joins
OUTPUT

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 132
Content
SQL Joins
3. RIGHT JOIN
• RIGHT JOIN is similar to LEFT JOIN.
• This join returns all the rows of the table on the right side of the
join and matching rows for the table on the left side of join.
• The rows for which there is no matching row on left side, the
result-set will contain null.
• RIGHT JOIN is also known as RIGHT OUTER JOIN.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 133
Content
SQL Joins
SYNTAX –
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;

Where-
table1: First table.
table2: Second table
matching_column: Column common to both the tables.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 134
Content
SQL Joins
QUESTION-

SYNTAX –

SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
RIGHT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 135
Content
SQL Joins
OUTPUT

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 136
Content
SQL Joins
4. FULL /OUTER JOIN
• FULL JOIN creates the result-set by combining result of both LEFT
JOIN and RIGHT JOIN.
• The result-set will contain all the rows from both the tables.
• The rows for which there is no matching, the result-set will
contain NULL values

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 137
Content
SQL Joins
SYNTAX –
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;

Where-
table1: First table.
table2: Second table
matching_column: Column common to both the tables.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 138
Content
SQL Joins
QUESTION-

SYNTAX –

SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 139
Content
SQL Joins
OUTPUT
NAME COURSE_ID
HARSH 1
PRATIK 2
RIYANA 2
DEEP 3
SAPTARHI 1
DHANRAJ NULL
ROHIT NULL
NIRAJ NULL
NULL 4
NULL 5
NULL 4

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 140
Content
PL/SQL
• PL/SQL is a procedural (code that is written as a sequence of
instructions) language that enables programmers to combine the
power of SQL with procedural statements.
• In PL/SQL, all the statements are executed at once which consists
of triggers, functions, procedures, etc,
• It enhances the functionality of an operation and decrease the
traffic.
• Developed by Oracle Corporation in the 1990s.
• It was designed to build server pages and web applications and
exhibits features such as abstraction and error handling.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 141
Content
PL/SQL
Features of PL SQL
1. PL/SQL is tightly integrated with SQL. It possesses all capabilities
of SQL.
2. It helps in checking the error very precisely.
3. There are a lot of different data types and data structures which
are provided by PL/SQL.
4. Structured programming is supported by the usage of functions
and procedures. It has added support for OOPs (Object Oriented
Programming)
5. Development of Server Pages and Web Applications can also be
achieved.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 142
Content
PL/SQL
Advantages of PL SQL
1. Block Structures – Each PL/SQL block of code forms a unit of
task and can be reused.
2. Better performance – PL/SQL executes all statements in bulk
rather than a single statement which increases the processing
speed.
3. Posses capabilities of procedural language – Conditional (if-else
statements) and Iterative (loops such as for, while do-while)
constructs are offered by PL/SQL.
4. Supports error handling – Error and exceptions are handled by
PL/SQL with high accuracy.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 143
Content
PL/SQL
Disadvantages of PL SQL
1. Limited I/O features – PL/SQL provides very limited support for
I/O either to read/write files or to read from or write to a user
interface.
2. Complex syntax – Sometimes, PL/SQL is not very easy for
programmers to follow due to its complex and inconsistent
syntax.
3. Proprietary to Oracle – It means that if one has to change the
database vendors then the user would have to update all the
existing Oracle PL/SQL code. It is a bit expensive.
4. Not beginner-friendly – Certain concepts in PL/SQL can become
difficult for beginners to understand

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 144
Content
PL/SQL

SQL PL/SQL

SQL is a single query that is used to PL/SQL is a block of codes that used
perform DML and DDL operations. to write the entire program blocks/
procedure/ procedure, etc.

It is declarative, that defines what PL/SQL is procedural that defines


needs to be done, rather than how how the things needs to be done.
things need to be done.

Execute as a single statement. Execute as a whole block.


Mainly used to manipulate data. Mainly used to create an
application.
Cannot contain PL/SQL code in it. It is an extension of SQL, so it can
contain SQL inside it.
Mr. Manish Kumar KOE-067 Unit-3
05/07/2024 145
Content
PL/SQL
SQL PL/SQL

Error handling feature is not present PL/SQL handles errors and


in SQL exceptions effectively with the help
of the inbuilt exception handlers.

PL/SQL handles a large chunk of


Handling a large chunk of data can’t data effectively with the help of
be effectively achieved by SQL procedures, functions and triggers.

SQL provides lesser processing PL/SQL offers a high processing


speed speed

Control structures are not supported Control structures such as if-else,


For loop, While loop are supported
Certain concepts of PL/SQL can be
SQL is easy to use and understand complex and prior knowledge might
Mr. Manish Kumar
be necessary
KOE-067 Unit-3
05/07/2024 146
Content
PL/SQL
Syntax of PL SQL
• The basic unit in PL/SQL is a block.
• All PL/SQL programs are made up of blocks, which can be nested
within each other

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 147
Content
PL/SQL
Syntax of PL SQL

DECLARE
declaration statements;
BEGIN
executable statements
EXCEPTIONS
exception handling statements;
END;

• PL/SQL Block sections:


1. Declaration section (optional).
2. Execution section (mandatory).
3. Exception handling section (optional).

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 148
Content
PL/SQL
1. Declaration section:
• It is an optional section and starts with DECLARE keyword.
• It is used to declare the variables, constants, records and cursors
etc.

2. Execution section:
• Execution section starts with BEGIN keyword and ends with END
keyword.
• It is a mandatory section.
• It is used to write the program logic code.

Note: Execution section must have one statement.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 149
Content
PL/SQL
3. Exception handling section:
• Execution section starts with EXCEPTION keyword.
• It is an optional section.
• It is used to handle the exceptions occurred in execution section

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 150
Content
PL/SQL identifiers
There are several PL/SQL identifiers such as variables, constants,
procedures, cursors, triggers etc

1. Variables:
• Like several other programming languages, variables in PL/SQL
must be declared prior to its use. They should have a valid name
and data type as well.
• Syntax for declaration of variables:

variable_name datatype [NOT NULL := value ];

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 151
Content
PL/SQL identifiers
Example to show how to declare variables in PL/SQL :

SQL> SET SERVEROUTPUT ON;

SQL> DECLARE
var1 INTEGER;
var2 REAL;
var3 varchar2(20) ;

BEGIN
null;
END;
/
OUTPUT- PL/SQL procedure successfully completed.

05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 152


Content
PL/SQL identifiers
Explanation:
• SET SERVEROUTPUT ON: It is used to display the buffer used by
the dbms_output.
• var1 INTEGER : It is the declaration of variable,
named var1 which is of integer type. There are many other data
types that can be used like float, int, real, smallint, long etc. It
also supports variables used in SQL as well like NUMBER(prec,
scale), varchar, varchar2 etc.
• PL/SQL procedure successfully completed.: It is displayed when
the code is compiled and executed successfully.
• Slash (/) after END;: The slash (/) tells the SQL*Plus to execute
the block.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 153
Content
PL/SQL identifiers
INITIALISING VARIABLES:

SQL> SET SERVEROUTPUT ON;


SQL> DECLARE
var1 INTEGER := 2 ;
var3 varchar2(20) := ‘Hello World' ;

BEGIN
null;

END;
/

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 154
Content
PL/SQL identifiers

• Assignment operator (:=) : It is used to assign a value to a


variable.

05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 155


Content
PL/SQL identifiers
2. Displaying Output:
• The outputs are displayed by using DBMS_OUTPUT which is a
built-in package that enables the user to display output,
debugging information, and send messages from PL/SQL blocks,
subprograms, packages, and triggers.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 156
Content
PL/SQL identifiers
Example to see how to display a message using PL/SQL-
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
var varchar2(40) := ‘Hello World' ;

BEGIN
dbms_output.put_line(var);

END;
/
OUTPUT – Hello World
• dbms_output.put_line : This command is used to direct the
PL/SQL output to a screen.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 157
Content
PL/SQL identifiers
3. Using Comments:
There are two syntaxes to create comments in PL/SQL :
• Single Line Comment: To create a single line comment , the
symbol – – is used.
• Multi Line Comment: To create comments that span over several
lines, the symbol /* and */ is used.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 158
Content
PL/SQL identifiers
Example to show how to create comments in PL/SQL-
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
-- I am a comment,so I will be ignored
var varchar2(40) := ‘Hello World' ;

BEGIN
dbms_output.put_line(var);

END;
/

OUTPUT – Hello World


Mr. Manish Kumar KOE-067 Unit-3
05/07/2024 159
Content
PL/SQL identifiers

4. Taking input from the user:

• Just like in other programming languages, in PL/SQL also, we can


take input from the user and store it in a variable.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 160
Content
PL/SQL identifiers
Example-

SQL> SET SERVEROUTPUT ON;

SQL> DECLARE

-- taking input for variable a


a number := &a;

-- taking input for variable b


b varchar2(30) := &b;

BEGIN
null;

END;
/

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 161
PL/SQL –Content
Cursors (CO3)

Oracle creates a memory area, known as the context area, for


processing an SQL statement, which contains all the information
needed for processing the statement

 cursor is a pointer to this context area.


 PL/SQL controls the context area through a cursor.
 A cursor holds the rows (one or more) returned by a SQL
statement.
 The set of rows the cursor holds is referred to as the active set.

There are two types of cursors −


 Implicit cursors
 Explicit cursors

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 162
Implicit Content
Cursors (CO3)

 Implicit cursors are automatically created by Oracle whenever


an SQL statement is executed
 Programmers cannot control the implicit cursors and the
information in it.
 Whenever a DML statement (INSERT, UPDATE and DELETE)
is issued, an implicit cursor is associated with this
statement.
 For INSERT operations, the cursor holds the data that
needs to be inserted.
 For UPDATE and DELETE operations, the cursor identifies
the rows that would be affected.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 163
Attributes of Content
SQL CURSOR (CO3)

%FOUND
 Returns TRUE if an INSERT, UPDATE, or DELETE statement affected
one or more rows or a SELECT INTO statement returned one or more
rows. Otherwise, it returns FALSE.
%NOTFOUND
 The logical opposite of %FOUND.
 It returns TRUE if an INSERT, UPDATE, or DELETE statement
affected no rows, or a SELECT INTO statement returned no rows.
Otherwise, it returns FALSE.

%ISOPEN
 Always returns FALSE for implicit cursors, because Oracle closes the
SQL cursor automatically after executing its associated SQL
statement.
%ROWCOUNT
 Returns the number of rows affected by an INSERT, UPDATE, or
DELETE statement, or returned by a SELECT INTO statement.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 164
PL/SQL –Cursor Example
Content (CO3)

update the table and increase the salary of each employee by


500 and use the SQL%ROWCOUNT attribute to determine the
number of rows affected
DECLARE
total_rows number(2);
BEGIN
UPDATE employee1
SET salary = salary + 500
Where age<=25;
IF sql%notfound
THEN
dbms_output.put_line('no customers selected’);
ELSIF sql%found
THEN total_rows := sql%rowcount;
dbms_output.put_line( total_rows||'customers selected’);
END IF;
END;
/
Mr. Manish Kumar KOE-067 Unit-3
05/07/2024 165
Structure of PL/SQL
Content Block: (CO3)

 The basic unit in PL/SQL is a block.


 All PL/SQL programs are made up of blocks, which can be nested
within each other.

DECLARE
declaration statements;
BEGIN
executable statements
EXCEPTIONS
exceptionhandling statements
END;
Mr. Manish Kumar KOE-067 Unit-3
05/07/2024 166
PL/SQL identifiers
Content (CO3)

• There are several PL/SQL identifiers such as variables,


constants, procedures, cursors, triggers etc.
Variables:

Like several other programming languages, variables


in PL/SQL must be declared prior to its use.
They should have a valid name and data type as well.

Syntax for declaration of variables:


variable_name datatype [NOT NULL := value ];

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 167
PL/SQL
Content (CO3)

SQL> SET SERVEROUTPUT ON; /*SET SERVEROUTPUT ON: It is used to


display the buffer used by the
dbms_output. */
SQL> DECLARE
var1 INTEGER; --declaration of variable, named var1 which is of integer type.
var2 REAL;
var3 varchar2(20) ;

BEGIN
null;
END;
/

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 168
Daily QUIZ
Content

1. A functional dependency is a relationship between or among


A. Entities
B. Rows
C. Attributes
D. Tables
2. Which functional dependency types is/are not present in the following dependencies?
Empno -> EName, Salary, Deptno, DName
DeptNo -> DName
EmpNo -> DName
A. Full functional dependency
B. Partial functional dependency
C. Transitive functional dependency
D. Both B and C
3. The database design prevents some data from being stored due to _______.
A. Deletion anomalies
B. Insertion anomalies
C. Update anomalies
D. Selection anomalies
4. If one attribute is determinant of second, which in turn is determinant of third, then the relation cannot
be:
A. Well-structured
B. 1NF
C. 2NF
D. 3NF
05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 169
Recap
Content

 PL/SQL stands for "Procedural Language extensions to the


Structured Query Language.“

 PL/SQL is a block structured language that enables developers


to combine the power of SQL with procedural statements.

 PL/SQL provides a feature to handle the exception which


occurs in PL/SQL block known as exception handling block.
 Applications written in PL/SQL are portable to computer
hardware or operating system where Oracle is operational.

05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 170


Create TableContent
Construct (CO3)

• An SQL relation is defined using the create table command:


create table r (A1 D1, A2 D2, ..., An Dn,
(integrity-constraint1),
...,
(integrity-constraintk))
– r is the name of the relation
– each Ai is an attribute name in the schema of relation r
– Di is the data type of values in the domain of attribute Ai

• Example:
create table branch
(branch_name char(15) not null,
branch_city char(30),
assets integer)

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 171
Integrity Constraints in Create Table (CO3)
Content

• not null
• primary key (A1, ..., An )

Example: Declare branch_name as the primary key


for branch
.
create table branch
(branch_name char(15),
branch_city char(30),
assets integer,
primary key (branch_name))

primary key declaration on an attribute


automatically ensures not null in SQL-92 onwards,
needs to be explicitly stated in SQL-89

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 172
Drop and Alter Table
ContentConstructs (CO3)

• The drop table command deletes all information about the


dropped relation from the database.
• The alter table command is used to add attributes to an
existing relation:
alter table r add A D
where A is the name of the attribute to be added to
relation r and D is the domain of A.
– All tuples in the relation are assigned null as the value for the
new attribute.
• The alter table command can also be used to drop
attributes of a relation:
alter table r drop A
where A is the name of an attribute of relation r
– Dropping of attributes not supported by many databases
Mr. Manish Kumar KOE-067 Unit-3
05/07/2024 173
Basic Query Structure
Content (CO3)

• SQL is based on set and relational operations with certain


modifications and enhancements
• A typical SQL query has the form:

select A1, A2, ..., An


from r1, r2, ..., rm
where P

– Ai represents an attribute
– Ri represents a relation
– P is a predicate.
• This query is equivalent to the relational algebra expression.

• The result of an SQL query is a relation.


Mr. Manish Kumar KOE-067 Unit-3
05/07/2024 174
The select Clause (CO3)
Content

• The select clause list the attributes desired in the result of a


query
– corresponds to the projection operation of the relational
algebra
• Example: find the names of all branches in the loan relation:
select branch_name
from loan
• In the relational algebra, the query would be:
branch_name (loan)
• NOTE: SQL names are case insensitive (i.e., you may use
upper- or lower-case letters.)
– E.g. Branch_Name ≡ BRANCH_NAME ≡ branch_name
– Some people use upper case wherever we use bold font.
Mr. Manish Kumar KOE-067 Unit-3
05/07/2024 175
The select Clause
Content(Cont.) (CO3)

• SQL allows duplicates in relations as well as in query results.


• To force the elimination of duplicates, insert the keyword
distinct after select.
• Find the names of all branches in the loan relations, and
remove duplicates
select distinct branch_name
from loan

• The keyword all specifies that duplicates not be removed.

select all branch_name


from loan

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 176
The select Clause
Content(Cont.) (CO3)

• SQL allows duplicates in relations as well as in query results.


• To force the elimination of duplicates, insert the keyword
distinct after select.
• Find the names of all branches in the loan relations, and
remove duplicates
select distinct branch_name
from loan

• The keyword all specifies that duplicates not be removed.

select all branch_name


from loan

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 177
The select Clause
Content(Cont.) (CO3)

• An asterisk in the select clause denotes “all attributes”


select *
from loan
• The select clause can contain arithmetic expressions
involving the operation, +, –, , and /, and operating on
constants or attributes of tuples.
• The query:
select loan_number, branch_name, amount  100
from loan
would return a relation that is the same as the loan
relation, except that the value of the attribute amount is
multiplied by 100.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 178
The where Clause (CO3)
Content

• The where clause specifies conditions that the result must


satisfy
– Corresponds to the selection predicate of the relational
algebra.
• To find all loan number for loans made at the Perryridge
branch with loan amounts greater than $1200.
select loan_number
from loan
where branch_name = 'Perryridge' and amount > 1200
• Comparison results can be combined using the logical
connectives and, or, and not.
• Comparisons can be applied to results of arithmetic
expressions.
Mr. Manish Kumar KOE-067 Unit-3
05/07/2024 179
Daily Quiz
Content
6. In a given relationship R, if an attribute A uniquely defines all other attributes, then the attribute A is a key attribute
which is also known as the _________ key.
a) Candidate
b) Join
c) Functional
d) None of the Mentioned

7. Anomalies are avoided by splitting the offending relation into multiple relations, is also known as
a) Accupressure
b) Decomposition
c) Precomposition
d) Both Decomposition and Precomposition

8. Every time attribute A appears, it is matched with the same value of attribute B, but not the same value of attribute
C. Therefore, it is true that:
a) A -> B
b) A -> C
c) A -> (B,C)
d) (B,C) -> A

9. When the values in one or more attributes being used as a foreign key must exist in another set of one or more
attributes in another table, we have created a(n):
a) Transitive Dependency
b) Insertion Anomaly
c) Referential Integrity Constraint
d) Normal Form
05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 180
MCQ
Content

1. A functional dependency is a relationship between or among


A. Entities
B. Rows
C. Attributes
D. Tables
2. Which functional dependency types is/are not present in the following dependencies?
Empno -> EName, Salary, Deptno, DName
DeptNo -> DName
EmpNo -> DName
A. Full functional dependency
B. Partial functional dependency
C. Transitive functional dependency
D. Both B and C
3. The database design prevents some data from being stored due to _______.
A. Deletion anomalies
B. Insertion anomalies
C. Update anomalies
D. Selection anomalies
4. If one attribute is determinant of second, which in turn is determinant of third, then the relation cannot
be:
A. Well-structured
B. 1NF
C. 2NF
D. 3NF
05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 181
MCQ
Content

5. Which of the following statement(s) is/are FALSE about OLAP?


A. OLAP involves long running slow transactions that read lot of data
B. OLAP involves frequent insert, update and delete operations
C. OLAP requires data to be in De-Normalized form for optimal processing
D. Both B and C
6. Choose the correct processing technique for the given statements. Identify correlation between salary structure and
policies sold made by Insurance agents in an organization.
A. OLTP
B. OLAP
C. OLAM
D. None of the above
7. Choose the correct processing technique for the given statements. Identify profit trends for different units of
organization over years
A. OLTP
B. OLAP
C. OLAM
D. None of the above
8. 5NF is designed to cope with :
A. Transitive dependency
B. Join dependency
C. Multi valued dependency
D. None of these

05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 182


Weekly Assignment
Content 3
1. Find the highest normal form of a relation R(A, B,C,D,E) with FD set (A->D,B->A,BC-
>D,AC->BE) CO5
ANS: two candidate keys {AC, BC}. 1 Normal Form
2. Find the highest normal form of a relation R(A,B,C,D,E) with FD set as {BC-
>D,AC->BE,B->E}
CO5
ANS: candidate key{AC} 2 Normal Form
3.. Find the highest normal form of a relation R(A,B,C,D,E) with FD set {B->A,A-
>C,BC->D,AC->BE}
CO5
4. Consider a schema R(A, B,C,D) and functional dependencies A->B and C->D.
Then the decomposition of R into R1 (A,B) and R2(C,D) is CO5
(a) dependency preserving and lossless join
(b) lossless join but not dependency preserving
(c) dependency preserving but not lossless join
(d) not dependency preserving and not lossless join
05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 183
Weekly Assignment
Content 3 contd..
5. A table has fields F1,F2,F3,F4, and F5, with the following functional dependencies:
F1->F3 CO5
F2->F4
{F1,F2}->F5
in terms of normalization, this table is in
(a) 1NF (b) 2NF (c) 3NF (d) None of these
6. Consider the following functional dependencies in a database: CO5
Date of Birth->Age
Name->Roll number
Age->Eligibility
Roll number->Name
Course number->Course name
{Roll number,Course number}->Grade
the relation {Roll number, Name,Date of birth, Age} is
(a) in second normal form but not in third normal form
(b) in third normal form but not in BCNF
(c) in BCNF
(d) in none of these
05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 184
Important Question
Content

1. What is normalization ? Explain the different types of Normal Form.


2. Write difference between BCNF Vs 3 NF
3. Explain the Primary Key, Super Key, Foreign Key and Candidate key with example.
4. Short Notes of the Following-
i) MVD or JD ii) Normalization with advantages
5. What is functional Dependency ? What do you mean by loss less decomposition

05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 185


Previous Year Question Paper
Content

05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 186


Previous Year Question Paper
Content

05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 187


Faculty Video Links, Youtube & NPTEL Video
Content
Links and Online Courses Details

You tube /other Video Links


• https://nptel.ac.in/courses/106/104/106104135/
• https://nptel.ac.in/courses/106106220/
• https://www.youtube.com/watch?v=wQB_6o1UQa0
• https://www.youtube.com/watch?v=7B9FnIIIsQc

05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 188


Glossary Questions
Content

• Find the suitable glossary:


{Trivial, PL/SQL, Redundancy, single query }

 ___________is a block structured language that enables developers to


combine the power of SQL with procedural statements.
 __________is at the root of several problems associated with relational
schemas.
 A functional dependency is __________if it is satisfied by all instances of a
relation.
 SQL is a __________that is used to perform DML and DDL operations.

Mr. Manish Kumar KOE-067 Unit-3


05/07/2024 189
Expected Questions
Content

1. What is functional Dependency ? What do you mean by loss less


decomposition?
2. Find the highest normal form of a relation R(A, B,C,D,E) with FD
set (A->D,B->A,BC->D,AC->BE)
3. Consider a schema R(A, B,C,D) and functional dependencies A->B
and C->D. Then the decomposition of R into R1 (A,B) and R2(C,D) is
(a) dependency preserving and lossless join
(b) lossless join but not dependency preserving
(c) dependency preserving but not lossless join
(d) not dependency preserving and not lossless join

190
05/07/2024 Mr. Manish Kumar KOE-067 Unit-3
RecapContent
of Unit-3

 PL/SQL stands for "Procedural Language extensions to the


Structured Query Language.“

 PL/SQL is a block structured language that enables developers


to combine the power of SQL with procedural statements.

 PL/SQL provides a feature to handle the exception which


occurs in PL/SQL block known as exception handling block.
 Applications written in PL/SQL are portable to computer
hardware or operating system where Oracle is operational.

05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 191


References
Content

Text books:
1. Elmasri, Navathe, “Fundamentals of Database System”,
Addision Wesley.
2. Korth, Silbertz, Sudarshan, “Database Concepts”, Mc Graw
Hill.
3. Bipin C. Desai, “An Introduction to Database System”,
Galgotia Publication.
4. Majumdar & Bhattacharya, “Database Management System”,
McGraw Hill.
5. Date C.J., “An Introduction to Database System”, Addision
Wesley.

05/07/2024 Mr. Manish Kumar KOE-067 Unit-3 192

You might also like