0% found this document useful (0 votes)
14 views

DBMS Unit - 2 Notes

Uploaded by

21egjcs021
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

DBMS Unit - 2 Notes

Uploaded by

21egjcs021
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

UNIT-II: Relational Algebra

 Relational Algebra is procedural query language, which takes Relation as input andgenerates relation as
output. Relational algebra mainly provides theoretical foundation for relational databases and SQL.
 Relational algebra is a procedural query language, it means that it tells what data to beretrieved and how to be
retrieved.
 Relational Algebra works on the whole table at once, so we do not have to use loopsetc to iterate over all the
rows (tuples) of data one by one.
 All we have to do is specify the table name from which we need the data, and in a single line of command,
relational algebra will traverse the entire given table to fetchdata for you.
Basic/Fundamental Operations:

1. Select (σ)
2. Project (∏)
3. Union (𝖴)
4. Set Difference (-)
5. Cartesian product (X)
6. Rename (ρ)

Select Operation (σ) :This is used to fetch rows (tuples) from table(relation) which satisfies a given condition.
Syntax: σp(r)

 σ is the predicate
 r stands for relation which is the name of the table
 p is prepositional logic ex: σage > 17 (Student)
This will fetch the tuples(rows) from table Student, for which age will be greater than 17. σage > 17 and gender
= 'Male' (Student)
This will return tuples(rows) from table Student with information of male students, of age more than 17.

BRANCH_NAME LOAN_NO AMOUNT


Downtown L-17 1000
Redwood L-23 2000
Perryride L-15 1500
Downtown L-14 1500
Mianus L-13 500
Roundhill L-11 900
Perryride L-16 1300

Input:
σ BRANCH_NAME="perryride" (LOAN)

Output:

BRANCH_NAME LOAN_NO AMOUNT


Perryride L-15 1500
Perryride L-16 1300

Project Operation (∏):


Project operation is used to project only a certain set of attributes of a relation. In simple words, If you want to
see only the names all of the students in the Student table, then you can use Project Operation.
It will only project or show the columns or attributes asked for, and will also removeduplicate data from the
columns.
Syntax of Project Operator (∏)
∏ column_name1, column_name2, .... , column_nameN(table_name)
Example:
∏Name, Age(Student)
Above statement will show us only the Name and Age columns for all the rows of data in Student table.

Example: CUSTOMER RELATION

NAME STREET CITY


Jones Main Harrison
Smith North Rye
Hays Main Harrison
Curry North Rye
Johnson Alma Brooklyn
Brooks Senator Brooklyn

Input:
∏ NAME, CITY (CUSTOMER)

Output:

NAME CITY
Jones Harrison
Smith Rye
Hays Harrison
Curry Rye
Johnson Brooklyn
Brooks Brooklyn

Union Operation (𝖴):

This operation is used to fetch data from two relations(tables) or temporaryrelation(result of another
operation).For this operation to work, the relations(tables) specified should have same number of
attributes(columns) and same attribute domain. Also the duplicate tuples are autamatically eliminated
from the result.

Syntax: A 𝖴 B
∏Student(RegularClass) 𝖴 ∏Student(ExtraClass)
Example:

DEPOSITOR RELATION
CUSTOMER_NAME ACCOUNT_NO
Johnson A-101
Smith A-121
Mayes A-321
Turner A-176
Johnson A-273
Jones A-472
Lindsay A-284

BORROW RELATION
CUSTOMER_NAME LOAN_NO

Jones L-17
Smith L-23
Hayes L-15
Jackson L-14
Curry L-93
Smith L-11
Williams L-17

Input:
∏ CUSTOMER_NAME (BORROW) 𝖴 ∏ CUSTOMER_NAME (DEPOSITOR)

Output:

CUSTOMER_NAME

Johnson
Smith
Hayes
Turner
Jones
Lindsay
Jackson
Curry
Williams
Mayes
Set Difference (-):
This operation is used to find data present in one relation and not present in the secondrelation. This
operation is also applicable on two relations, just like Union operation.
Syntax: A - B
where A and B are relations.
For example, if we want to find name of students who attend the regular class but not theextra class,
then, we can use the below operation:
∏Student(RegularClass) - ∏Student(ExtraClass)

Input: ∏ CUSTOMER_NAME (BORROW) ∩ ∏ CUSTOMER_NAME (DEPOSITOR)

CUSTOMER_NAME
Smith
Jones

Cartesian Product (X):


This is used to combine data from two different relations(tables) into one and fetch data from the combined
relation.
Syntax: A X B
For example, if we want to find the information for Regular Class and Extra Class which areconducted
during morning, then, we can use the following operation:
σtime = 'morning' (RegularClass X ExtraClass)
For the above query to work, both RegularClass and ExtraClass should have theattribute time.
Notation: E X D

EMPLOYEE
EMP_ID EMP_NAME EMP_DEPT
1 Smith A
2 Harry C
3 John B

DEPARTMENT
DEPT_NO DEPT_NAME
A Marketing
B Sales
C Legal

Input:
EMPLOYEE X DEPARTMENT
Output:

EMP_ID EMP_NAME EMP_DEPT DEPT_NO DEPT_NAME


1 Smith A A Marketing
1 Smith A B Sales

1 Smith A C Legal
2 Harry C A Marketing
2 Harry C B Sales
2 Harry C C Legal

3 John B A Marketing
3 John B B Sales
3 John B C Legal

Rename Operation (ρ):


This operation is used to rename the output relation for any query operation which returnsresult like
Select, Project etc. Or to simply rename a relation(table)
Syntax: ρ(RelationNew, RelationOld)

The rename operation is used to rename the output relation. It is denoted by rho (ρ).

Example: We can use the rename operator to rename STUDENT relation to STUDENT1.
ρ(STUDENT1, STUDENT)

Join in DBMS:

 A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.
 Join in DBMS is a binary operation which allows you to combine join product andselection in
one single statement.
 The goal of creating a join condition is that it helps you to combine the data from twoor more
DBMS tables.
 The tables in DBMS are associated using the primary key and foreign keys.

Types of SQL JOIN


1. INNER JOIN

2. LEFT JOIN

3. RIGHT JOIN
4. FULL JOIN
Table name: EMPLOYEE

EMP_ID EMP_NAME CITY SALARY AGE


1 Angelina Chicago 200000 30
2 Robert Austin 300000 26
3 Christian Denver 100000 42
4 Kristen Washington 500000 29
5 Russell Los angels 200000 36
6 Marry Canada 600000 48

PROJECT
PROJECT_NO EMP_ID DEPARTMENT
101 1 Testing
102 2 Development
103 3 Designing
104 4 Development

1. INNER JOIN

In SQL, INNER JOIN selects records that have matching values in both tables as long as thecondition is
satisfied.

It returns the combination of all rows from both the tables where the condition satisfies.

Syntax
SELECT table1.column1, table1.column2 FROM table1 INNER JOIN table2
ON table1.matching_column = table2.matching_column;

Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT FROM EMPLOYEE INNER JOIN
PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

2. LEFT JOIN

The SQL left join returns all the values from left table and the matching values from the righttable. If
there is no matching join value, it will return NULL.

Syntax
SELECT table1.column1, table1.column2 FROM table1LEFT JOIN table2
ON table1.matching_column = table2.matching_column;

Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT FROM EMPLOYEE LEFT JOIN
PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Marry NULL

3.RIGHT JOIN

In SQL, RIGHT JOIN returns all the values from the values from the rows of right table and the matched values
from the left table. If there is no matching in both tables, it will return NULL.

Syntax
SELECT table1.column1, table1.column2 FROM table1 RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;

Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT FROM EMPLOYEE RIGHT JOIN
PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
.
4. FULL JOIN

In SQL, FULL JOIN is the result of a combination of both left and right outer join. Join tables have
all the records from both tables. It puts NULL on the place of matches not found.

Syntax
SELECT table1.column1, table1.column2 FROM table1 FULL JOIN table2
ON table1.matching_column = table2.matching_column;

Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT FROM EMPLOYEE
FULL JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Marry NULL
Division Operator in SQL
Division Operator (÷): Division operator A÷B can be applied if and only if:
 Attributes of B is proper subset of Attributes of A.
 The relation returned by division operator will have attributes = (All attributes of A –All
Attributes of B)
 The relation returned by division operator will return those tuples from relation Awhich are
associated to every B’s tuple.

The division operator is used when we have to evaluate queries which contain thekeyword ALL.
Table 1: Course_Taken → It consists of the names of Students against the courses that they have
taken.

Student_Name Course

Robert Databases

Robert Programming Languages

David Databases

David Operating Systems

Hannah Programming Languages

Hannah Machine Learning

Tom Operating Systems


Table 2: Course_Required → It consists of the courses that one is required to take in order to
graduate.

Course

Databases

Programming Languages

Find all the students. Create a set of all students that have taken courses. This can be done easily using the
following command.
CREATE TABLE AllStudents AS SELECT DISTINCT Student_Name FROM Course_Taken
This command will return the table AllStudents, as the resultset:

Student_name

Robert

David

Hannah

Tom
Find all the students and the courses required to graduate
Next, we will create a set of students and the courses they need to graduate. We can express this in the
form of Cartesian Product of AllStudents and Course_Required using the following command.
CREATE table StudentsAndRequired AS
SELECT AllStudents.Student_Name, Course_Required.CourseFROM AllStudents,
Course_Required
Now, the new resultset - table Students And Required will be:

Student_Name Course

Robert Databases

Robert Programming Languages

David Databases

David Programming Languages

Hannah Databases

Hannah Programming Languages

Tom Databases

Tom Programming Languages


Relational Calculus:
Relational calculus is a non-procedural query language that tells the system what data to be retrieved but
doesn’t tell how to retrieve it. Relational Calculus exists in two forms:
1. Tuple Relational Calculus (TRC)
2. Domain Relational Calculus (DRC)
Tuple Relational Calculus (TRC)
Tuple relational calculus is used for selecting those tuples that satisfy the given condition.
Table: Student
First_Name Last_Name Age

Ajeet Singh 30
Chaitanya Singh 31
Rajeev Bhatia 27
Carl Pratap 28
Lets write relational calculus queries.
Query to display the last name of those students where age is greater than 30
{ t.Last_Name | Student(t) AND t.age > 30 }

In the above query you can see two parts separated by | symbol. The second part is where wedefine the
condition and in the first part we specify the fields which we want to display for the selected tuples.
The result of the above query would be:
Last_Name

Singh

{ t | Student(t) AND t.Last_Name = 'Singh' }


Query to display all the details of students where Last name is ‘Singh’
Output:
First_Name Last_Name
Age

Ajeet Singh 30
Chaitanya Singh 31

Ex:
Table-1: Customer
Customer name Street City
Saurabh A7 Patiala
Mehak B6 Jalandhar
Sumiti D9 Ludhiana
Ria A5 Patiala
Table-2: Branch
Branch name Branch city
ABC Patiala
DEF Ludhiana
GHI Jalandhar
Table-3: Account
Account number Branch name Balance
1111 ABC 50000
1112 DEF 10000
1113 GHI 9000
1114 ABC 7000
Table-4: Loan
Loan number Branch name Amount
L33 ABC 10000
L35 DEF 15000
L49 GHI 9000
L98 DEF 65000
Table-5: Borrower
Customer name Loan number
Saurabh L33
Mehak L49
Ria L98

Table-6: Depositor
Customer name Account number
Saurabh 1111
Mehak 1113
Sumiti 1114

Queries-1: Find the loan number, branch, amount of loans of greater than or equal to 10000 amount.

{t| t ∈ loan 𝖠 t[amount]>=10000}Resulting relation


Loan number Branch name Amount
L33 ABC 10000
L35 DEF 15000
L98 DEF 65000

Domain Relational Calculus (DRC)


In domain relational calculus the records are filtered based on the domains. Again we take the same
table to understand how DRC works.
Table: Student

First_Name Last_Name Age

Ajeet Singh 30
Chaitanya Singh 31
Rajeev Bhatia 27
Carl Pratap 28

{< First_Name, Age > | ∈ Student 𝖠 Age > 27}


Query to find the first name and age of students where student age is greater than 27
Note:
The symbols used for logical operators are: 𝖠 for AND, ∨ for OR and ┓for NOT.
Output:
First_Name Age

Ajeet 30
Chaitanya 31
Carl 28

SQL Basic Structure


Basic structure of an SQL expression consists of select, from and where clauses.
o select clause lists attributes to be copied - corresponds to relationalalgebra project.
o from clause corresponds to Cartesian product - lists relations to be used.
o where clause corresponds to selection predicate in relational algebra.

The SELECT statement is used to select data from a database.

The data returned is stored in a result table, called the result-set. To fetch the entire table or all the fields in
the table:
SELECT * FROM table_name;To fetch individual column data
SELECT column1,column2 FROM table_name

WHERE SQL clause


WHERE clause is used to specify/apply any condition while retrieving, updating or deletingdata from a
table. This clause is used mostly with SELECT, UPDATE and DELETEquery.
The basic syntax of the SELECT statement with the WHERE clause is as shown below. SELECT column1,
column2, columnN
FROM table_name
WHERE [condition]

Example
Consider the CUSTOMERS table having the following records −
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +

The following code is an example which would fetch the ID, Name and Salary fields fromthe
CUSTOMERS table, where the salary is greater than 2000 −
SQL> SELECT ID, NAME, SALARY
FROM CUSTOMERS
WHERE SALARY > 2000;

This would produce the following result −


+ + + +
| ID | NAME | SALARY |
+ + + +
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+ + + +

From clause:
From clause can be used to specify a sub-query expression in SQL. The relation producedby the
sub-query is then used as a new relation on which the outer query is applied.
 Sub queries in the from clause are supported by most of the SQL implementations.

 The correlation variables from the relations in from clause cannot be used in the sub-queries
in the from clause.

Syntax:
SELECT column1, column2 FROM
(SELECT column_x as C1, column_y FROM table WHERE PREDICATE_X)as table2
WHERE PREDICATE;

SET Operations
SQL supports few Set operations which can be performed on the table data. These are used to get
meaningful results from data stored in the table, under different special conditions.
In this tutorial, we will cover 4 different types of SET operations, along with example:

1. UNION
2. UNION ALL
3. INTERSECT
4. MINUS

1. Union

o The SQL Union operation is used to combine the result of two or more SQL SELECT
queries.
o In the union operation, all the number of datatype and columns must be same in boththe
tables on which UNION operation is being applied.
The union operation eliminates the duplicate rows from its resultset

Syntax
SELECT column_name FROM table1 UNION
SELECT column_name FROM table2;
The First table

ID NAME
1 Jack
2 Harry
3 Jackson

The Second table

ID NAME
3 Jackson
4 Stephan
5 David
Union SQL query will be:SELECT * FROM First UNION
SELECT * FROM Second;
The resultset table will look like:

ID NAME
1 Jack
2 Harry
3 Jackson
4 Stephan
5 David
2. Union All
Union All operation is equal to the Union operation. It returns the set without removingduplication
and sorting the data.

Syntax:
SELECT column_name FROM table1 UNION ALL
SELECT column_name FROM table2;
Example: Using the above First and Second table. Union All query will be like:
SELECT * FROM First UNION ALL
SELECT * FROM Second;

The resultset table will look like:

-ID NAME
1 Jack
2 Harry
3 Jackson
3 Jackson
4 Stephan
5 David
3. Intersect

o It is used to combine two SELECT statements. The Intersect operation returns thecommon
rows from both the SELECT statements.
o In the Intersect operation, the number of data type and columns must be the same.
o It has no duplicates and it arranges the data in ascending order by default.

Syntax
SELECT column_name FROM table1 INTERSECT
SELECT column_name FROM table2;

Example:
Using the above First and second table, Intersect query will be:

SELECT * FROM First INTERSECT


SELECT * FROM Second;
The result set table will look like:

ID NAME
3 Jackson

4. Minus

o It combines the result of two SELECT statements. Minus operator is used to displaythe rows
which are present in the first query but absent in the second query.
o It has no duplicates and data arranged in ascending order by default.

Syntax:
SELECT column_name FROM table1 MINUS
SELECT column_name FROM table2;

Example:

Using the above First and Second table, Minus query will be:
SELECT * FROM FirstMINUS
SELECT * FROM Second;

The result set table will look like:

ID NAME
1 Jack
2 Harry
Aggregate functions in SQL
o SQL aggregation function is used to perform the calculations on multiple rows of asingle
column of a table. It returns a single value.
o It is also used to summarize the data.

Aggregate Functions
1) Count()
2) Sum()
3) Avg()
4) Min()
5) Max()
1. COUNT FUNCTION

o COUNT function is used to Count the number of rows in a database table. It can workon
both numeric and non-numeric data types.
o COUNT function uses the COUNT(*) that returns the count of all the rows in a specified
table. COUNT(*) considers duplicate and Null.
Count(*): Returns total number of records

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 4 30 120

Example: COUNT()
SELECT COUNT(*) FROM PRODUCT_MAST;

Output: 10

Example: COUNT with WHERE


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

Output:7

Example: COUNT() with DISTINCT

SELECT COUNT(DISTINCT COMPANY) FROM PRODUCT_MAST;

Output:3

2. SUM Function

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 )

Example: SUM()
SELECT SUM(COST) FROM PRODUCT_MAST;
Output:670

Example: SUM() with WHERE


SELECT SUM(COST) FROM PRODUCT_MAST WHERE QTY>3;
Output:320

3. AVG function

The AVG function is used to calculate the average value of the numeric type. AVG functionreturns
the average of all non-Null values.

Syntax
AVG()

Example:
SELECT AVG(COST) FROM PRODUCT_MAST;

Output:
67.00

4. 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()

Example:
SELECT MAX(RATE) FROM PRODUCT_MAST;
30

5. 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() )

Example: SELECT MIN(RATE)FROM PRODUCT_MAST;

Output:10

GROUP BY Statement

The GROUP BY statement groups rows that have the same values into summary rows, like"find the
number of customers in each country".
The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN, SUM,
AVG) to group the result-set by one or more columns.
Syntax:

SELECT column_name(s)FROM table_name WHERE condition


GROUP BY column_name(s)
ORDER BY column_name(s);

Example:
 Group By single column: Group By single column means, to place all the rows with same
value of only that particular column in one group. Consider the query as shown below:
 SELECT NAME, SUM(SALARY) FROM Employee
 GROUP BY NAME;
The above query will produce the below output:

Group By multiple columns: Group by multiple column is say for example, GROUP BY
column1, column2. This means to place all the rows with same values of both the columns
column1 and column2 in one group. Consider the below query:
SELECT SUBJECT, YEAR, Count(*)
FROM Student
GROUP BY SUBJECT, YEAR;
HAVING Clause:

We know that WHERE clause is used to place conditions on columns but what if we wantto place
conditions on groups?
This is where HAVING clause comes into use. We can use HAVING clause to place conditions to
decide which group will be the part of final result-set. Also we can not usethe aggregate functions
like SUM(), COUNT() etc. with WHERE clause. So we have to use HAVING clause if we want
to use any of these functions in the conditions.
Syntax:
SELECT column1, function_name(column2) FROM table_name
WHERE condition
GROUP BY column1, column2HAVING condition
ORDER BY column1, column2;
function_name: Name of the function used for example, SUM() , AVG().
table_name: Name of the table.
condition: Condition used.
Example:
SELECT NAME, SUM(SALARY) FROM EmployeeGROUP BY NAME
HAVING SUM(SALARY)>3000;

Example:
Consider the CUSTOMERS table having the following records.
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +

Following is an example, which would display a record for a similar age count that would be more
than or equal to 2.
SQL > SELECT ID, NAME, AGE, ADDRESS, SALARY
FROM CUSTOMERS
GROUP BY age
HAVING COUNT(age) >= 2;

This would produce the following result −


+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 2 | Khilan | 25 | Delhi | 1500.00 |
+ + + + + +
Nested Queries

In nested queries, a query is written inside a query. The result of inner query is used inexecution
of outer query. We will use STUDENT, COURSE,
STUDENT_COURSE tables for understanding nested queries.
STUDENT
S_ID S_NAME S_ADDRESS S_PHONE S_AGE
S1 RAM DELHI 9455123451 18
S2 RAMESH GURGAON 9652431543 18
S3 SUJIT ROHTAK 9156253131 20
S4 SURESH DELHI 9156768971 18

COURSE
C_ID C_NAME
C1 DSA
C2 Programming
C3 DBMS

STUDENT_COURSE
S_ID C_ID
S1 C1
S1 C3
S2 C1
S3 C2
S4 C2
S4 C3

Example
Consider the CUSTOMERS table having the following records −

+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
Now, let us check the following subquery with a SELECT statement.

SQL> SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500);

This would produce the following result.

+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +

Students
id name class_id GPA
1 Jack Black 3 3.45
2 Daniel White 1 3.15
3 Kathrine Star 1 3.85
4 Helen Bright 2 3.10
5 Steve May 2 2.40

Teachers
id name subject class_id monthly_salary
1 Elisabeth Grey History 3 2,500
2 Robert Sun Literature [NULL] 2,000
3 John Churchill English 1 2,350
4 Sara Parker Math 2 3,000
Classes
id grade teacher_id number_of_students
1 10 3 21
2 11 4 25
3 12 1 28

SELECT *
FROM students WHERE GPA > (
SELECT AVG(GPA)
FROM students);

RESULT:
id name class_id GPA
1 Jack Black 3 3.45
3 Kathrine Star 1 3.85
SELECT AVG(number_of_students) FROM classes
WHERE teacher_id IN ( SELECT id
FROM teachers
WHERE subject = 'English' OR subject = 'History');

Views in SQL
o Views in SQL are considered as a virtual table. A view also contains rows and columns.
o To create the view, we can select the fields from one or more tables present in thedatabase.
o A view can either have specific rows based on certain condition or all the rows of atable.

Student_Detail
STU_ID NAME ADDRESS
1 Stephan Delhi
2 Kathrin Noida
3 David Ghaziabad
4 Alina Gurugram
Student_Marks
STU_ID NAME MARKS AGE
1 Stephan 97 19
2 Kathrin 86 21
3 David 74 18
4 Alina 90 20
5 John 96 18

1. Creating view

A view can be created using the CREATE VIEW statement. We can create a view from a single
table or multiple tables.

Syntax:
CREATE VIEW view_name ASSELECT column1, column2.....
FROM table_nameWHERE condition;

2. Creating View from a single table


Query:
CREATE VIEW DetailsView ASSELECT NAME, ADDRESS
FROM Student_Details WHERE STU_ID < 4;

Just like table query, we can query the view to view the data. SELECT * FROM DetailsView;
Output:
NAME ADDRESS
Stephan Delhi
Kathrin Noida
David Ghaziabad

3. Creating View from multiple tables


View from multiple tables can be created by simply include multiple tables in the SELECT
statement.
In the given example, a view is created named MarksView from two tables Student_Detailand
Student_Marks.
Query:
CREATE VIEW MarksView AS
SELECT Student_Detail.NAME, Student_Detail.ADDRESS, Student_Marks.MARKS FROM
Student_Detail, Student_Mark
WHERE Student_Detail.NAME = Student_Marks.NAME;
To display data of View MarksView:SELECT * FROM MarksView;
NAME ADDRESS MARKS
Stephan Delhi 97
Kathrin Noida 86
David Ghaziabad 74
Alina Gurugram 90

4. Deleting View
A view can be deleted using the Drop View statement.
Syntax:
DROP VIEW view_name;
Example:
If we want to delete the View MarksView, we can do this as:
DROP VIEW MarksView;

Uses of a View :
A good database should contain views due to the given reasons:
1. Restricting data access –
Views provide an additional level of table security by restricting access to apredetermined set
of rows and columns of a table.
2. Hiding data complexity –
A view can hide the complexity that exists in a multiple table join.
3. Simplify commands for the user –
Views allows the user to select information from multiple tables without requiring theusers to
actually know how to perform a join.
4. Store complex queries –
Views can be used to store complex queries.
5. Rename Columns –
Views can also be used to rename the columns without affecting the base tables provided the
number of columns in view must match the number of columns specified in select statement.
Thus, renaming helps to to hide the names of the columns of the base tables.
6. Multiple view facility –
Different views can be created on the same table for different users.

Trigger: A trigger is a stored procedure in database which automatically invokes whenever a


special event in the database occurs. For example, a trigger can be invokedwhen a row is inserted
into a specified table or when certain table columns are being updated.
Syntax:
create trigger [trigger_name] [before | after]
{insert | update | delete}on [table_name]
[for each row] [trigger_body] Explanation of syntax:

1. create trigger [trigger_name]: Creates or replaces an existing trigger with thetrigger_name.


2. [before | after]: This specifies when the trigger will be executed.
3. {insert | update | delete}: This specifies the DML operation.
4. on [table_name]: This specifies the name of the table associated with the trigger.
5. [for each row]: This specifies a row-level trigger, i.e., the trigger will be executed for each row
being affected.
6. [trigger_body]: This provides the operation to be performed as trigger is fired
BEFORE and AFTER of Trigger:
BEFORE triggers run the trigger action before the triggering statement is run. AFTER triggers run
the trigger action after the triggering statement is run.
Example:
Given Student Report Database, in which student marks assessment is recorded. In such schema,
create a trigger so that the total and average of specified marks is automatically inserted whenever a
record is insert.
Here, as trigger will invoke before record is inserted so, BEFORE Tag can be used.
Suppose the database Schema –
mysql> desc Student;
+ -+ + -+ -+ + +
| Field | Type | Null | Key | Default | Extra |
+ -+ + -+ -+ + +
| tid | int(4) | NO | PRI | NULL | auto_increment |
| name | varchar(30) | YES | | NULL | |
| subj1 | int(2) | YES | | NULL | |
| subj2 | int(2) | YES | | NULL | |
| subj3 | int(2) | YES | | NULL | |
| total | int(3) | YES | | NULL | |
| per | int(3) | YES | | NULL | |
+ -+ + -+ -+ + +7 rows in set (0.00 sec)
SQL Trigger to problem statement. create trigger stud_marks
before INSERTon
Student
for each row
set Student.total = Student.subj1 + Student.subj2 + Student.subj3, Student.per =Student.total * 60
/ 100;
Above SQL statement will create a trigger in the student database in which whenever subject’s
marks are entered, before inserting this data into the database, trigger will compute those two
values and insert with the entered values. i.e.,
mysql> insert into Student values(0, "ABCDE", 20, 20, 20, 0, 0);
Query OK, 1 row affected (0.09 sec)
mysql> select * from Student;
+ +- + -+ +- + + +
| tid | name | subj1 | subj2 | subj3 | total | per |
+ +- + -+ +- + + +
| 100 | ABCDE | 20 | 20 | 20 | 60 | 36 |
+ +- + -+ +- + + +1 row in set (0.00 sec)
In this way trigger can be creates and executed in the databases.

Advantages of Triggers:

These are the following advantages of Triggers:


o Trigger generates some derived column values automatically
o Enforces referential integrity
o Event logging and storing information on table access
o Auditing
o Synchronous replication of tables
o Imposing security authorizations
o Preventing invalid transactionsCreating a trigger:
Syntax for creating trigger:
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statementsEXCEPTION
Exception-handling-statements
END;

Here,
o CREATE [OR REPLACE] TRIGGER trigger_name: It creates or replaces an existingtrigger
with the trigger_name.
o {BEFORE | AFTER | INSTEAD OF} : This specifies when the trigger would beexecuted.
The INSTEAD OF clause is used for creating trigger on a view.
o {INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML operation.
o [OF col_name]: This specifies the column name that would be updated.
o [ON table_name]: This specifies the name of the table associated with the trigger.
o [REFERENCING OLD AS o NEW AS n]: This allows you to refer new and old values for
various DML statements, like INSERT, UPDATE, and DELETE.
o [FOR EACH ROW]: This specifies a row level trigger, i.e., the trigger would be executed for
each row being affected. Otherwise the trigger will execute just once when the SQL statement
is executed, which is called a table level trigger.
o WHEN (condition): This provides a condition for rows for which the trigger would fire. This
clause is valid only for row level triggers.

PL/SQL Trigger Example


Let's take a simple example to demonstrate the trigger. In this example, we are using the following
CUSTOMERS table:

Create table and have records:


ID NAME AGE ADDRESS SALARY
1 Ramesh 23 Allahabad 20000
2 Suresh 22 Kanpur 22000
3 Mahesh 24 Ghaziabad 24000
4 Chandan 25 Noida 26000
5 Alex 21 Paris 28000
6 Sunita 20 Delhi 30000

Create trigger:
Let's take a program to create a row level trigger for the CUSTOMERS table that would fire for
INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. Thistrigger
will display the salary difference between the old values and new values:
CREATE OR REPLACE TRIGGER display_salary_changes BEFORE DELETE OR INSERT
OR UPDATE ON customersFOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary; dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);dbms_output.put_line('Salary difference: ' ||
sal_diff);
END;

After the execution of the above code at SQL Prompt, it produces the following result.
Trigger created.
Check the salary difference by procedure:

Use the following code to get the old salary, new salary and salary difference after the trigger
created.
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 5000;
IF sql%notfound THEN
dbms_output.put_line('no customers updated');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers updated ');
END IF;
END;
Old salary: 20000
New salary: 25000
Salary difference: 5000
Old salary: 22000
New salary: 27000
Salary difference: 5000
Old salary: 24000
New salary: 29000
Salary difference: 5000
Old salary: 26000
New salary: 31000
Salary difference: 5000
Old salary: 28000
New salary: 33000
Salary difference: 5000

Output:

Old salary: 30000


New salary: 35000
Salary difference: 5000
6 customers updated

Note: As many times you executed this code, the old and new both salary is incremented by5000
and hence the salary difference is always 5000.
After the execution of above code again, you will get the following result.
Old salary: 25000
New salary: 30000
Salary difference: 5000
Old salary: 27000
New salary: 32000
Salary difference: 5000
Old salary: 29000
New salary: 34000
Salary difference: 5000
Old salary: 31000
New salary: 36000
Salary difference: 5000
Old salary: 33000
New salary: 38000
Salary difference: 5000
Old salary: 35000
New salary: 40000
Salary difference: 5000
6 customers updated

Important Points:
Following are the two very important points and should be noted carefully.
o OLD and NEW references are used for record level triggers these are not available fortable level triggers.
o If you want to query the table in the same trigger, then you should use the AFTER keyword, because
triggers can query the table or change it again only after the initialchanges are applied and the table is back
in a consistent state.
Procedure
The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs oneor more specific
tasks. It is just like procedures in other programming languages.
The procedure contains a header and a body.
o Header: The header contains the name of the procedure and the parameters or variables passed to the
procedure.
o Body: The body contains a declaration section, execution section and exception section similar to a
general PL/SQL block.

How to pass parameters in procedure:


When you want to create a procedure or function, you have to define parameters .There isthree ways to pass
parameters in procedure:
1. IN parameters: The IN parameter can be referenced by the procedure or function. The value of the
parameter cannot be overwritten by the procedure or the function.
2. OUT parameters: The OUT parameter cannot be referenced by the procedure orfunction, but the value
of the parameter can be overwritten by the procedure or function.
3. INOUT parameters: The INOUT parameter can be referenced by the procedure or function and the
value of the parameter can be overwritten by the procedure or function.
NOTE: A procedure may or may not return any value.
PL/SQL Create Procedure
Syntax for creating procedure:
CREATE [OR REPLACE] PROCEDURE procedure_name[ (parameter [,parameter]) ]
IS
[declaration_section]
BEGIN
executable_section[EXCEPTION
exception_section]
END [procedure_name];
Create procedure example

In this example, we are going to insert record in user table. So you need to create user table first.

Table creation:
create table user(id number(10) primary key,name varchar2(100)); Now write theprocedure code
to insert record in user table.

Procedure Code:
create or replace procedure "INSERTUSER"(id IN NUMBER,
name IN VARCHAR2)
is begin
insert into user values(id,name);end;
/
Output:
Procedure created.
PL/SQL program to call procedure
Let's see the code to call above created procedure.
BEGIN
insertuser(101,'Rahul'); dbms_output.put_line('record inserted successfully');
END;
Now, see the "USER" table, you will see one record is inserted.

ID Name
101 Rahul
PL/SQL Drop Procedure
Syntax for drop procedure
DROP PROCEDURE procedure name;
Example of drop procedure
DROP PROCEDURE pro1;
DDL Triggers

As The Name suggests, DDL Triggers are related to DDL commands. DDL triggers respond
to DDL events like CREATE, ALTER, DROP, GRANT, DENY, REVOKE, or UPDATE
STATISTICS. For example, you can define a DDL trigger that records CREATE or ALTER
TABLE operations.
We can create these triggers at the database level or server level, depending on the type of
DDL events. It can also be executed in response to certain system-defined stored procedures
that do DDL-like operations.

The DDL triggers are useful in the following scenario:


1. Need to prevent Database schema from changing
2. To respond to any changes in schema
3. Audit changes made in the database schema

DDL Trigger Syntax

CREATE TRIGGER trigger_name


ON { DATABASE | ALL SERVER}
[WITH ddl_trigger_option]
FOR { event_type | event_group }
AS
{sql_statement}

DML Trigger
DML triggers are fired in response to DML events like INSERT, UPDATE, and DELETE
statements in the user’s table or view. It can also be executed in response to DML-like operations
performed by system-defined stored procedures.

Logon Trigger

Logon triggers are fired in response to a LOGON event. The LOGON event occurs when a user
session is generated with an SQL Server instance, which is made after the authentication process
of logging is completed but before establishing a user session. As a result, the SQL Server error
log will display all messages created by the trigger, including error messages and the PRINT
statement messages. If authentication fails, logon triggers do not execute. These triggers may
be used to audit and control server sessions, such as tracking login activity or limiting the
number of sessions for a particular login.

ADVANTAGES OF TRIGGERS
• Triggers set database object rules and roll back if any change does not satisfy those rules.
The trigger will inspect the data and make changes if necessary.
• Triggers help us to enforce data integrity.
• Triggers help us to validate data before inserted or updated.
• Triggers help us to keep a log of records.
• Triggers increase SQL queries' performance because they do not need to compile each time
they are executed.
• Triggers reduce the client-side code that saves time and effort.
• Triggers are easy to maintain.

DISADVANTAGES OF TRIGGERS

•Triggers are invoked automatically, and their execution is invisible to the user. Therefore, it
isn't easy to troubleshoot what happens in the database layer.
• Triggers may increase the overhead of the database server.
• We can define the same trigger action for multiple user actions such as INSERT and
UPDATE in the same CREATE TRIGGER statement.
• We can create a trigger in the current database only, but it can reference objects outside the
current database.

SQL Comparison Operators

The SQL Operators which compare the values of two columns in the database tables are called
as comparison operators.
In SQL, comparison operators are always used in the WHERE clause with the SELECT,
UPDATE, and DELETE statements.

The comparison operators in SQL are categorized into the following six operators
category:
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 (<=)

SQL Equal Operator (=)


This type of comparison operator selects only those data from the table which matches the
specified value.
This operator is highly used by the database users in Structured Query Language.
This operator returns TRUE rows from the database table if the value of the column is same as
the value specified in the query.

Syntax using SELECT & Delete Statement:


SELECT * FROM Table_Name WHERE Column_Name = Value;
DELETE FROM Table_Name WHERE Field_Name = Value;
Example to update & delete row using Equal Operator:
UPDATE Employee SET Emp_Salary = 35000 WHERE Emp_Bonus = 3000;
DELETE FROM Employee WHERE Emp_City = 'Goa';

SQL NOT Equal Operator (!=)


This type of comparison operator selects only those data from the table which does not match
with the specified value.
This operator returns TRUE rows from the database table if the value of the column is not same
as the value specified in the query.

Syntax using SELECT statement to access data from table:


SELECT * FROM Table_Name WHERE Column_Name != Value;
DELETE FROM Table_Name WHERE Field_Name != Value;

SQL Greater Than Operator (>)


This type of comparison operator selects, modifies, and deletes only those data from the table
which are greater than the value specified in the query.
Syntax using Select statement:
SELECT * FROM Table_Name WHERE Column_Name > Value;

SQL Greater Than Equals to Operator (>=)


This type of comparison operator retrieves, modifies, and deletes only those data from the table
which are greater than and equal to the given value.

Syntax using SELECT statement to access data from table:


SELECT Column_Name1, Column_Name2, ….., Column_NameN FROM Table_Name
WHERE Column_Name >= Value;

SQL Less Than Operator (<)


This type of comparison operator in SQL selects only those data from the table which are less
than the given value.
Syntax:
SELECT * FROM Table_Name WHERE Column_Name < Value;
UPDATE Table_Name SET Column_Name = Value WHERE Column_Name < Value;
DELETE FROM Table_Name WHERE Field_Name < Value;

SQL Less Than Equals to Operator (<=)


This type of comparison operator selects only those data from the table which are less than and
equal to the given value.
Syntax:
SELECT Column_Name1, Column_Name2, ….., Column_NameN FROM Table_Name W
HERE Column_Name <= Value;
UPDATE Table_Name SET Column_Name = Value WHERE Column_Name <= Value;
DELETE FROM Table_Name WHERE Column_Name <= Value;

Embedded SQL (Static SQL):

Static or Embedded SQL are SQL statements in an application that do not change at runtime
and, therefore, can be hard-coded into the application.
Embedded SQL is a technique where SQL statements are precompiled into a program before
execution. The SQL statements are fixed at compile time, so the execution time is much faster
than Dynamic SQL. This approach is ideal when the query criteria are known in advance,
such as when generating daily reports, or performing batch processing of large amounts of
data.

 In Static SQL, database access procedure is predetermined in the statement.


 Static SQL statements are more faster and efficient.
 Static SQL statements are compiled at compile time.
 In Static SQL, Application Plan parsing, validation, optimization and generation are
compile time activities.
 Static SQL is used in case of uniformly distributed data.
 Static SQL is less flexible.

The benefit of using this statement is that user know the path of execution of the
statements, so user can optimize the SQL query and then can execute the query in the
best and fastest possible way.

Dynamic SQL
Dynamic SQL is a programming technique that enables you to build SQL statements
dynamically at runtime.
Dynamic SQL is a technique used in database programming that allows SQL statements to be
constructed and executed at runtime. This approach offers more flexibility than Embedded SQL
because the SQL statement is constructed based on dynamic criteria that can change at runtime.
For example, if a user wants to search for products based on different criteria, Dynamic SQL
would be a suitable approach because the SQL statement can be constructed based on the user’s
inputs.
Since the dynamic SQL statement is constructed dynamically, it can pose a security risk if not
implemented properly. If an attacker is able to manipulate the input criteria, they can potentially
inject malicious SQL code and access or modify sensitive data in the database. Developers need
to take precautions such as validating inputs and using parameterized SQL statements to prevent
SQL injection attacks.

 In Dynamic SQL, how a database will be accessed, can be determine only at run time.
 Dynamic SQL statements are less efficient.
 Dynamic SQL statements are compiled at run time.
 In Dynamic SQL, Application Plan parsing, validation, optimization and generation are
run time activities.
 Dynamic SQL is used in case of non-uniformly distributed data.
 Dynamic SQL is highly flexible.
ODBC (Open Database Connectivity) and JDBC (Java Database Connectivity):-- These
both are Application Programming Interface (API) standards used for connecting applications
to databases and both ODBC & JDBC help the applications on the client side to access the
database on the server side.
Basically both are known as drivers to get connected with a database and are provided by the
vendors of RDBMS

ODBC (Open Database Connectivity): Open Database Connectivity, commonly known as


ODBC, was developed by Microsoft in 1992. Different applications use it as a general API to
access and manipulate databases.
It is widely used in window environment for database connectivity and provides a standard for
businesses and developers to access databases.

For example, Microsoft Office supports ODBC.

ODBC is a framework made up of four components that function together. ODBC enables
programs to use SQL queries to connect to databases without knowing the databases' specific
interfaces. The SQL query is handled by ODBC, which turns it into a request that each database
system recognizes.

The four different components of ODBC are:

 Application: The user sends its query to the database. Here the ODBC functions
are called, and SQL queries are sent.

 Data Manager: Loads drivers for each application.

 Driver: It handles ODBC function calls before submitting each SQL request to a
data source.
 Data Sources: The data source comprises the information that needs to be
accessed and the operating system, DBMS, and network platform used in
communication with the DBMS.

Features Of ODBC

 Interoperability: User may quickly switch/migrate his application from one


database to another using the ODBC driver.

 Rich metadata: ODBC supports metadata well. It includes functions for


obtaining information about both processes and data types.

 Attributes: ODBC additionally offers methods for obtaining information about


the characteristics and practices utilized by the drivers.

 Error code: It has an error code method for indicating problems encountered
while executing SQL statements.

Advantages of ODBC
 Cross-Platform : ODBC works on multiple platforms like Linux, Windows.
 Compatibility : ODBC provides compatibility with different data sources like
relational databases, files, etc.
 Support for non-Java languages : ODBC supports Java and different languages
like C, C++, C#, Perl, etc.
 Widely used : Since it is more flexible and compatible with other languages, that
make it such a widely used API.

Disadvantages of ODBC
 Performance: ODBC is much slower than JDBC since it has an additional layer
for abstraction.
 Complicated to construct: ODBC drivers are difficult to create and maintain.
 Slow with Large databases: It can not handle large databases like JDBC.
However, it is easy to use.
 Does not provide standardized: ODBC needs to be sufficiently standardized as
it is mainly used by clients, which is challenging to scale.

JDBC (Java Database Connectivity): JDBC is specifically designed for Java applications,
allowing them to interact easily with a wide variety of relational databases. JDBC defines an
API for JAVA programming environment that java programmers use to access relational
database and issue SQL statements.
It was introduced by Sun Microsystems in 1996.
JDBC stands for Java Database Connectivity and it is a part of JavaSE (Java Standard Edition).

It comprises a diverse set of classes, interfaces, and methods that allow a program to interact
with databases utilizing SQL queries. The JDBC API is composed of two layers. They are the
JDBC API Layer and JDBC Driver API Layer, respectively.
JDBC API Layer
It indicates which application uses the JDBC API to interact with the databases through JDBC
drivers. Java Application uses this JDBC driver to interact with and access the database.

JDBC Driver API layer


It acts as an interface between the Java application and the database. The driver sends the
request of the application to the database for accessing or manipulating the database. After
responding to the application's query, it prepares a result set that is sent back to the driver and
then to JDBC API Layer.

JDBC is Object Oriented. It has advanced features like Update and Scrollable Result set. It is
platform-independent. They can work on any operating system like Linux or Mac.

The key steps involved in working of JDBC are:


 Load the JDBC driver: The JDBC driver loads the database to Java Virtual
Machine (JVM).
 Establish a connection: A connection is built between the database to transfer
the queries through Driver Manger or Data Source objects.
 Create a statement: A statement object executes SQL statements using
connection objects.
 Execute SQL statements: ResultSet is created to store the executed SQL
statements result.
 Process the ResultSet: The data from the database is retrieved using the
ResultSet object.
 Close the ResultSet and Statement objects: To free up the resources they were
utilizing, the ResultSet and Statement object is closed.
 Close the database connection: When the database connection is no longer
required, it is closed to free up the resources it was consuming.

Features of JDBC
The main unique feature of ODBC is:

 JDBC is connected to the database through DriverManger or DataSource objects.

 It does not need to make connections again and again with databases. If you make a
connection again, it will be very costly and time-consuming, and some essential features
may be lost.
 It can manipulate large databases like BLOB and CLOB.

 It provides batch updates. It means it can send multiple updates in batches rather than
individually.

 It gives about two types of result sets. One of them is Scrollable Result sets. It provides
an ability to move forward and backward from a specific position. Another one is the
Updatable Result set. It helps in the modification of databases.

 It has a Save points interface. It saves a set of new savepoints and releases savepoints
when requested.
Advantages of JDBC
 Pure Java: It is purely dedicated to Java. It can work on any platform which
supports Java Programming language.
 Better performance : It performs better than ODBC in some cases. It can reuse
the used statements and support batch updates.
 Object-oriented: Since it is Object Oriented, it enables it to work with Java
more easily.
 Standardized : JDBC is a standard API that supports all major relational
databases.

Disadvantages of JDBC
 Complexity: JDBC is more complex to use than ODBC. It needs to manage the
database manually.
 Limited Functionality: Less functionality than other APIs like JPA or
Hibernate, which provide a higher level of abstraction.
 Platform-specific Driver: It is platform-specific. It can work on any platform
which supports Java Programming language.
JDBC ODBC

Stands for Java Database Stands for Java Database


Connectivity Connectivity

Introduced by Sun MicroSystems in


Introduced by Microsoft in 1992
1997

Uses only Java Programming Use any programming language like


language C, C++ etc.

Java based API C-based API

Platform Independent Platform Dependent

JDBC is Procedural ODBC is Object Oriented

Specially designed for Java It is designed for any applications


Applications written in C, C++, Java, Perl etc.

It requires Java Virtual Machine


It does not requires.
(JVM)

Slower in performance as Faster in performance as compared


compared to ODBC to ODBC

Active Databases:

An active Database is a database consisting of a set of triggers. These databases are very difficult
to be maintained because of the complexity that arises in understanding the effect of these
triggers. In such a database, DBMS initially verifies whether the particular trigger specified in
the statement that modifies the database) is activated or not, prior to executing the statement.

An active databases contain an event- driven architecture that can respond to conditions inside
and outside the database. An active database can therefore monitor and react to specific
situations related to the application.

These databases are very difficult to be maintained because of the complexity that arises in
understanding the effect of these triggers. In such a database, DBMS initially verifies whether
the particular trigger specified in the statement that modifies the database) is activated or not,
prior to executing the statement.

If the trigger is active then DBMS executes the condition part and then executes the action part
only if the specified condition is evaluated to true. It is possible to activate more than one trigger
within a single statement.

In such a situation, DBMS processes each of the triggers randomly. The execution of an active
part of a trigger may either activate other triggers or the same trigger that Initialized this action.
Such types of triggers that activate themselves are called ‘recursive triggers’. The DBMS
executes such chains of triggers in some pre-defined manner but it affects the concept of
understanding.

Examples of Active Databases:


1. Real-time Databases
2. In-Memory Databases
3. Transactional Databases
4. Time-series Databases

Features of Active Database


1. It possesses all the concepts of a conventional database i.e. data modeling
facilities, query language, etc.
2. It supports all the functions of a traditional database like data definition, data
manipulation, storage management, etc.
3. It supports the definition and management of ECA rules.
4. It detects event occurrence.
5. It must be able to evaluate conditions and execute actions.
6. It means that it has to implement rule execution.

Advantages of Active Database

1. It Enhances traditional database functionalities with powerful rule processing


capabilities.
2. Enable a uniform and centralized description of the business rules relevant to the
information system.
3. Avoids redundancy of checking and repair operations.
4. A suitable platform for building a large and efficient knowledge base and expert
systems.
Correlated nested query:
In correlated nested queries, the output of inner query depends on the row which is being
currently executed in outer query.
Correlated subqueries are used for row-by-row processing. Each subquery is executed once
for every row of the outer query.

 First, the outer query selects the first row.


 Inner query uses the value of the selected row. It executes its query and returns a result
set.
 Outer query uses the result set returned by the inner query. It determines whether the
selected row should be included in the final output.
 Steps 2 and 3 are repeated for each row in the outer query's result set.
 This process can be resource-intensive. It may lead to performance issues if the query
is not optimized properly.

A correlated subquery is evaluated once for each row processed by the parent statement. The
parent statement can be a SELECT, UPDATE, or DELETE statement.
Syntax:
SELECT column1, column2, ....
FROM table1 outer
WHERE column1 operator
(SELECT column1, column2
FROM table2
WHERE expr1 =
outer.expr2);

Operators Used in Correlated Nested Queries

In correlated nested queries, the following operators can be used

EXISTS Operator
This operator checks whether a subquery returns any row. If it returns at least one row. EXISTS
operator returns true, and the outer query continues to execute.
If the subquery returns no row, the EXISTS operator returns false, and the outer query stops
execution.

NOT EXISTS Operator


This operator checks whether a subquery returns no rows. If the subquery returns no row, the
NOT EXISTS operator returns true, and the outer query continues to execute. If the subquery
returns at least one row, the NOT EXISTS operator returns false, and the outer query stops
execution.

ANY Operator
This operator compares a value of the outer query's result with one or more values returned by
the inner query. If the comparison is true for any one of the values returned by the inner query,
the row is included in the final result.

ALL Operator
This operator compares a value of the outer query's result with all the values returned by the
inner query. Only if the comparison is true for all the values returned by the inner query, the
row is included in the final result.

Examples

Table: emp
e_id name
1 Arun
2 Ankita
3 Jenny
4 Shivani
5 Khush

Table: dept
dept_no name e_id
D1 IT 1
D2 HR 2
D3 R&D 3

Find the details of all emp who work in any department?

select * from emp where exists (select e_id from dept where emp.e_id=dept.e_id);

Here we take first row from emp table and match with each row of dept table and whenever
the comparison become true, it should be added in the output.
Here, the inner query is starts again and again as the value is compared with each value of the
the outer query.

Output:

e_id Name
1 Arun
2 Ankita
3 Jenny

You might also like