You are on page 1of 97

DBMS Architecture

o The DBMS design depends upon its architecture. The basic client/server architecture is used to deal with a
large number of PCs, web servers, database servers and other components that are connected with
networks.
o The client/server architecture consists of many PCs and a workstation which are connected via the network.
o DBMS architecture depends upon how users are connected to the database to get their request done.

Types of DBMS Architecture

Database architecture can be seen as a single tier or multi-tier. But logically, database architecture is of two types
like: 2-tier architecture and 3-tier architecture.

1-Tier Architecture

o In this architecture, the database is directly available to the user. It means the user can directly sit on the
DBMS and uses it.
o Any changes done here will directly be done on the database itself. It doesn't provide a handy tool for end
users.
o The 1-Tier architecture is used for development of the local application, where programmers can directly
communicate with the database for the quick response.

2-Tier Architecture

o The 2-Tier architecture is same as basic client-server. In the two-tier architecture, applications on the client
end can directly communicate with the database at the server side. For this interaction, API's
like: ODBC, JDBC are used.
o The user interfaces and application programs are run on the client-side.
o The server side is responsible to provide the functionalities like: query processing and transaction
management.
o To communicate with the DBMS, client-side application establishes a connection with the server side.

Fig: 2-tier Architecture

3-Tier Architecture

o The 3-Tier architecture contains another layer between the client and server. In this architecture, client can't
directly communicate with the server.
o The application on the client-end interacts with an application server which further communicates with the
database system.
o End user has no idea about the existence of the database beyond the application server. The database also
has no idea about any other user beyond the application.
o The 3-Tier architecture is used in case of large web application.

Fig: 3-tier Architecture

SQL Commands
o 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.
o SQL can perform various tasks like create a table, add data to tables, drop the table, modify the table, set
permission for users.

Types of SQL Commands


There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.
1. Data Definition Language (DDL)

o DDL changes the structure of the table like creating a table, deleting a table, altering a table, etc.
o All the command of DDL are auto-committed that means it permanently save all the changes in the
database.

Here are some commands that come under DDL:

o CREATE
o ALTER
o DROP
o TRUNCATE

a. CREATE It is used to create a new table in the database.

Syntax:

Hello Java Program for Beginners

1. CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);  
Example:

1. CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100), DOB DATE);  

b. DROP: It is used to delete both the structure and record stored in the table.

Syntax

1. DROP TABLE table_name;  

Example

1. DROP TABLE EMPLOYEE;  

c. ALTER: It is used to alter the structure of the database. This change could be either to modify the characteristics
of an existing attribute or probably to add a new attribute.

Syntax:

To add a new column in the table

1. ALTER TABLE table_name ADD column_name COLUMN-definition;    

To modify existing column in the table:

1. ALTER TABLE table_name MODIFY(column_definitions....);  

EXAMPLE

1. ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));  
2. ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));  

d. TRUNCATE: It is used to delete all the rows from the table and free the space containing the table.

Syntax:

1. TRUNCATE TABLE table_name;  

Example:

1. TRUNCATE TABLE EMPLOYEE;  

2. Data Manipulation Language


o DML commands are used to modify the database. It is responsible for all form of changes in the database.
o The command of DML is not auto-committed that means it can't permanently save all the changes in the
database. They can be rollback.

Here are some commands that come under DML:

o INSERT
o UPDATE
o DELETE

a. INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of a table.

Syntax:

1. INSERT INTO TABLE_NAME    
2. (col1, col2, col3,.... col N)  
3. VALUES (value1, value2, value3, .... valueN);  

Or

1. INSERT INTO TABLE_NAME    
2. VALUES (value1, value2, value3, .... valueN);    

For example:

1. INSERT INTO javatpoint (Author, Subject) VALUES ("Sonoo", "DBMS");  

b. UPDATE: This command is used to update or modify the value of a column in the table.

Syntax:

1. UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [WHERE CONDITION]   

For example:

1. UPDATE students    
2. SET User_Name = 'Sonoo'    
3. WHERE Student_Id = '3'  

c. DELETE: It is used to remove one or more row from a table.

Syntax:
1. DELETE FROM table_name [WHERE condition];  

For example:

1. DELETE FROM javatpoint  
2. WHERE Author="Sonoo";  

3. Data Control Language


DCL commands are used to grant and take back authority from any database user.

Here are some commands that come under DCL:

o Grant
o Revoke

a. Grant: It is used to give user access privileges to a database.

Example

1. GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;  

b. Revoke: It is used to take back permissions from the user.

Example

1. REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;  

4. Transaction Control Language


TCL commands can only use with DML commands like INSERT, DELETE and UPDATE only.

These operations are automatically committed in the database that's why they cannot be used while creating
tables or dropping them.

Here are some commands that come under TCL:

o COMMIT
o ROLLBACK
o SAVEPOINT

a. Commit: Commit command is used to save all the transactions to the database.


Syntax:

1. COMMIT;  

Example:

1. DELETE FROM CUSTOMERS  
2. WHERE AGE = 25;  
3. COMMIT;  

b. Rollback: Rollback command is used to undo transactions that have not already been saved to the database.

Syntax:

1. ROLLBACK;  

Example:

1. DELETE FROM CUSTOMERS  
2. WHERE AGE = 25;  
3. ROLLBACK;  

c. SAVEPOINT: It is used to roll the transaction back to a certain point without rolling back the entire transaction.

Syntax:

1. SAVEPOINT SAVEPOINT_NAME;  

5. Data Query Language


DQL is used to fetch the data from the database.

It uses only one command:

o SELECT

a. SELECT: This is the same as the projection operation of relational algebra. It is used to select the attribute
based on the condition described by WHERE clause.

Syntax:

1. SELECT expressions    
2. FROM TABLES    
3. WHERE conditions;  

For example:

1. SELECT emp_name  
2. FROM employee  
3. WHERE age > 20;  

Data Models
Data Model is the modeling of the data description, data semantics, and consistency constraints of the data. It
provides the conceptual tools for describing the design of a database at each level of data abstraction. Therefore,
there are following four data models used for understanding the structure of the database:

1) Relational Data Model: This type of model designs the data in the form of rows and columns within a table.
Thus, a relational model uses tables for representing data and in-between relationships. Tables are also called
relations. This model was initially described by Edgar F. Codd, in 1969. The relational data model is the widely
used model which is primarily used by commercial data processing applications.

2) Entity-Relationship Data Model: An ER model is the logical representation of data as objects and
relationships among them. These objects are known as entities, and relationship is an association among these
entities. This model was designed by Peter Chen and published in 1976 papers. It was widely used in database
designing. A set of attributes describe the entities. For example, student_name, student_id describes the 'student'
entity. A set of the same type of entities is known as an 'Entity set', and the set of the same type of relationships is
known as 'relationship set'.

3) Object-based Data Model: An extension of the ER model with notions of functions, encapsulation, and object
identity, as well. This model supports a rich type system that includes structured and collection types. Thus, in
1980s, various database systems following the object-oriented approach were developed. Here, the objects are
nothing but the data carrying its properties.

C++ vs Java

4) Semistructured Data Model: This type of data model is different from the other three data models (explained
above). The semistructured data model allows the data specifications at places where the individual data items of
the same type may have different attributes sets. The Extensible Markup Language, also known as XML, is widely
used for representing the semistructured data. Although XML was initially designed for including the markup
information to the text document, it gains importance because of its application in the exchange of data.

Mapping Constraints
o A mapping constraint is a data constraint that expresses the number of entities to which another entity can
be related via a relationship set.
o It is most useful in describing the relationship sets that involve more than two entity sets.
o For binary relationship set R on an entity set A and B, there are four possible mapping cardinalities. These
are as follows:
1. One to one (1:1)
2. One to many (1:M)
3. Many to one (M:1)
4. Many to many (M:M)

One-to-one
In one-to-one mapping, an entity in E1 is associated with at most one entity in E2, and an entity in E2 is associated
with at most one entity in E1.

One-to-many
In one-to-many mapping, an entity in E1 is associated with any number of entities in E2, and an entity in E2 is
associated with at most one entity in E1.

Many-to-one
In one-to-many mapping, an entity in E1 is associated with at most one entity in E2, and an entity in E2 is
associated with any number of entities in E1.

Many-to-many
In many-to-many mapping, an entity in E1 is associated with any number of entities in E2, and an entity in E2 is
associated with any number of entities in E1.

10 Sec
Hello Java Program for Beginners
PL/SQL Procedure
The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one or 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 is three 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 or function, 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.

A procedure may or may not return any value.

PL/SQL Create Procedure


Syntax for creating procedure:

Exception Handling in Java - Javatpoint

1. CREATE [OR REPLACE] PROCEDURE procedure_name  
2.     [ (parameter [,parameter]) ]  
3. IS  
4.     [declaration_section]  
5. BEGIN  
6.     executable_section  
7. [EXCEPTION  
8.     exception_section]  
9. 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:

1. create table user(id number(10) primary key,name varchar2(100));  

Now write the procedure code to insert record in user table.

Procedure Code:

1. create or replace procedure "INSERTUSER"    
2. (id IN NUMBER,    
3. name IN VARCHAR2)    
4. is    
5. begin    
6. insert into user values(id,name);    
7. end;    
8. /       

Output:

Procedure created.

PL/SQL program to call procedure


Let's see the code to call above created procedure.

1. BEGIN    
2.    insertuser(101,'Rahul');  
3.    dbms_output.put_line('record inserted successfully');    
4. END;    
5. /    

Now, see the "USER" table, you will see one record is inserted.

ID Name

101 Rahul
PL/SQL Drop Procedure
Syntax for drop procedure

1. DROP PROCEDURE procedure_name;   

Example of drop procedure

1. DROP PROCEDURE pro1;  

PL/SQL Function
The PL/SQL Function is very similar to PL/SQL Procedure. The main difference between procedure and a function
is, a function must always return a value, and on the other hand a procedure may or may not return a value.
Except this, all the other things of PL/SQL procedure are true for PL/SQL function too.

Syntax to create a function:

1. CREATE [OR REPLACE] FUNCTION function_name [parameters]  
2. [(parameter_name [IN | OUT | IN OUT] type [, ...])]  
3. RETURN return_datatype  
4. {IS | AS}  
5. BEGIN  
6.    < function_body >  
7. END [function_name];  

Here:

o Function_name: specifies the name of the function.


o [OR REPLACE] option allows modifying an existing function.
o The optional parameter list contains name, mode and types of the parameters.
o IN represents that value will be passed from outside and OUT represents that this parameter will be used to return a
value outside of the procedure.

The function must contain a return statement.

o RETURN clause specifies that data type you are going to return from the function.
o Function_body contains the executable part.
o The AS keyword is used instead of the IS keyword for creating a standalone function.
PL/SQL Function Example
Let's see a simple example to create a function.

10 Sec

Java Try Catch

1. create or replace function adder(n1 in number, n2 in number)    
2. return number    
3. is     
4. n3 number(8);    
5. begin    
6. n3 :=n1+n2;    
7. return n3;    
8. end;    
9. /    

Now write another program to call the function.

1. DECLARE    
2.    n3 number(2);    
3. BEGIN    
4.    n3 := adder(11,22);    
5.    dbms_output.put_line('Addition is: ' || n3);    
6. END;    
7. /    

Output:

Addition is: 33
Statement processed.
0.05 seconds

Another PL/SQL Function Example


Let's take an example to demonstrate Declaring, Defining and Invoking a simple PL/SQL function which will
compute and return the maximum of two values.

1. DECLARE  
2.    a number;  
3.    b number;  
4.    c number;  
5. FUNCTION findMax(x IN number, y IN number)   
6. RETURN number  
7. IS  
8.     z number;  
9. BEGIN  
10.    IF x > y THEN  
11.       z:= x;  
12.    ELSE  
13.       Z:= y;  
14.    END IF;  
15.   
16.    RETURN z;  
17. END;   
18. BEGIN  
19.    a:= 23;  
20.    b:= 45;  
21.   
22.    c := findMax(a, b);  
23.    dbms_output.put_line(' Maximum of (23,45): ' || c);  
24. END;  
25. /  

Output:

Maximum of (23,45): 45
Statement processed.
0.02 seconds

PL/SQL function example using table


Let's take a customer table. This example illustrates creating and calling a standalone function. This function will
return the total number of CUSTOMERS in the customers table.

Create customers table and have records in it.

Customers

Id Name Department Salary

1 alex web developer 35000


2 ricky program developer 45000

3 mohan web designer 35000

4 dilshad database manager 44000

Create Function:

1. CREATE OR REPLACE FUNCTION totalCustomers  
2. RETURN number IS  
3.    total number(2) := 0;  
4. BEGIN  
5.    SELECT count(*) into total  
6.    FROM customers;  
7.     RETURN total;  
8. END;  
9. /  

After the execution of above code, you will get the following result.

Function created.

Calling PL/SQL Function:

While creating a function, you have to give a definition of what the function has to do. To use a function, you will
have to call that function to perform the defined task. Once the function is called, the program control is
transferred to the called function.

After the successful completion of the defined task, the call function returns program control back to the main
program.

To call a function you have to pass the required parameters along with function name and if function returns a
value then you can store returned value. Following program calls the function totalCustomers from an anonymous
block:

1. DECLARE  
2.    c number(2);  
3. BEGIN  
4.    c := totalCustomers();  
5.    dbms_output.put_line('Total no. of Customers: ' || c);  
6. END;  
7. /  

After the execution of above code in SQL prompt, you will get the following result.

Total no. of Customers: 4


PL/SQL procedure successfully completed.

PL/SQL Recursive Function


You already know that a program or a subprogram can call another subprogram. When a subprogram calls itself,
it is called recursive call and the process is known as recursion.

Example to calculate the factorial of a number


Let's take an example to calculate the factorial of a number. This example calculates the factorial of a given
number by calling itself recursively.

1. DECLARE  
2.    num number;  
3.    factorial number;  
4.   
5. FUNCTION fact(x number)  
6. RETURN number   
7. IS  
8.    f number;  
9. BEGIN  
10.    IF x=0 THEN  
11.       f := 1;  
12.    ELSE  
13.       f := x * fact(x-1);  
14.    END IF;  
15. RETURN f;  
16. END;  
17.   
18. BEGIN  
19.    num:= 6;  
20.    factorial := fact(num);  
21.    dbms_output.put_line(' Factorial '|| num || ' is ' || factorial);  
22. END;  
23. /  

After the execution of above code at SQL prompt, it produces the following result.

Factorial 6 is 720
PL/SQL procedure successfully completed.

PL/SQL Drop Function


Syntax for removing your created function:

If you want to remove your created function from the database, you should use the following syntax.

1. DROP FUNCTION function_name;  

Loops in Java
The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is
recommended to use for loop.

There are three types of for loops in Java.


o Simple for Loop
o For-each or Enhanced for Loop
o Labeled for Loop

Java Simple for Loop


A simple for loop is the same as C/C++. We can initialize the variable, check condition and increment/decrement
value. It consists of four parts:

1. Initialization: It is the initial condition which is executed once when the loop starts. Here, we can initialize the
variable, or we can use an already initialized variable. It is an optional condition.
2. Condition: It is the second condition which is executed each time to test the condition of the loop. It continues
execution until the condition is false. It must return boolean value either true or false. It is an optional condition.
3. Increment/Decrement: It increments or decrements the variable value. It is an optional condition.
4. Statement: The statement of the loop is executed each time until the second condition is false.

Syntax:
10 Sec

HTML Tutorial

1. for(initialization; condition; increment/decrement){    
2. //statement or code to be executed    
3. }    

Flowchart:

Example:

ForExample.java

1. //Java Program to demonstrate the example of for loop  
2. //which prints table of 1  
3. public class ForExample {  
4. public static void main(String[] args) {  
5.     //Code of Java for loop  
6.     for(int i=1;i<=10;i++){  
7.         System.out.println(i);  
8.     }  
9. }  
10. }  
Test it Now

Output:

1
2
3
4
5
6
7
8
9
10

Java Nested for Loop


If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes completely
whenever outer loop executes.

Example:

NestedForExample.java

1. public class NestedForExample {  
2. public static void main(String[] args) {  
3. //loop of i  
4. for(int i=1;i<=3;i++){  
5. //loop of j  
6. for(int j=1;j<=3;j++){  
7.         System.out.println(i+" "+j);  
8. }//end of i  
9. }//end of j  
10. }  
11. }  

Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

Pyramid Example 1:

PyramidExample.java

1. public class PyramidExample {  
2. public static void main(String[] args) {  
3. for(int i=1;i<=5;i++){  
4. for(int j=1;j<=i;j++){  
5.         System.out.print("* ");  
6. }  
7. System.out.println();//new line  
8. }  
9. }  
10. }  

Output:

*
* *
* * *
* * * *
* * * * *

Pyramid Example 2:

PyramidExample2.java

1. public class PyramidExample2 {  
2. public static void main(String[] args) {  
3. int term=6;  
4. for(int i=1;i<=term;i++){  
5. for(int j=term;j>=i;j--){  
6.         System.out.print("* ");  
7. }  
8. System.out.println();//new line  
9. }  
10. }  
11. }  

Output:

* * * * * *
* * * * *
* * * *
* * *
* *
*

Java for-each Loop


The for-each loop is used to traverse array or collection in Java. It is easier to use than simple for loop because we
don't need to increment value and use subscript notation.

It works on the basis of elements and not the index. It returns element one by one in the defined variable.

Syntax:

1. for(data_type variable : array_name){    
2. //code to be executed    
3. }    

Example:

ForEachExample.java

1. //Java For-each loop example which prints the  
2. //elements of the array  
3. public class ForEachExample {  
4. public static void main(String[] args) {  
5.     //Declaring an array  
6.     int arr[]={12,23,44,56,78};  
7.     //Printing array using for-each loop  
8.     for(int i:arr){  
9.         System.out.println(i);  
10.     }  
11. }  
12. }  
Test it Now
Output:

12
23
44
56
78

Java Labeled For Loop


We can have a name of each Java for loop. To do so, we use label before the for loop. It is useful while using the
nested for loop as we can break/continue specific for loop.

Note: The break and continue keywords breaks or continues the innermost for loop respectively.

Syntax:

1. labelname:    
2. for(initialization; condition; increment/decrement){    
3. //code to be executed    
4. }    

Example:

LabeledForExample.java

1. //A Java program to demonstrate the use of labeled for loop  
2. public class LabeledForExample {  
3. public static void main(String[] args) {  
4.     //Using Label for outer and for loop  
5.     aa:  
6.         for(int i=1;i<=3;i++){  
7.             bb:  
8.                 for(int j=1;j<=3;j++){  
9.                     if(i==2&&j==2){  
10.                         break aa;  
11.                     }  
12.                     System.out.println(i+" "+j);  
13.                 }  
14.         }  
15. }  
16. }  
Output:

1 1
1 2
1 3
2 1

If you use break bb;, it will break inner loop only which is the default behaviour of any loop.

LabeledForExample2.java

1. public class LabeledForExample2 {  
2. public static void main(String[] args) {  
3.     aa:  
4.         for(int i=1;i<=3;i++){  
5.             bb:  
6.                 for(int j=1;j<=3;j++){  
7.                     if(i==2&&j==2){  
8.                         break bb;  
9.                     }  
10.                     System.out.println(i+" "+j);  
11.                 }  
12.         }  
13. }  
14. }  

Output:

1 1
1 2
1 3
2 1
3 1
3 2
3 3

Java Infinitive for Loop


If you use two semicolons ;; in the for loop, it will be infinitive for loop.

Syntax:

1. for(;;){  
2. //code to be executed  
3. }  

Example:

ForExample.java

1. //Java program to demonstrate the use of infinite for loop  
2. //which prints an statement  
3. public class ForExample {  
4. public static void main(String[] args) {  
5.     //Using no condition in for loop  
6.     for(;;){  
7.         System.out.println("infinitive loop");  
8.     }  
9. }  
10. }  

Output:

infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
ctrl+c

Now, you need to press ctrl+c to exit from the program.

Java for Loop vs while Loop vs do-while Loop

Comparison for loop while loop do-while loop

Introduction The Java for loop is a control flow The Java while loop is a control The Java do while loop is a control
statement that iterates a part of flow statement that executes a flow statement that executes a part
the programs multiple times. part of the programs repeatedly of the programs at least once and
on the basis of given boolean the further execution depends upon
condition. the given boolean condition.

When to use If the number of iteration is fixed, If the number of iteration is not If the number of iteration is not fixed
it is recommended to use for loop. fixed, it is recommended to use and you must have to execute the
while loop. loop at least once, it is
recommended to use the do-while
loop.

Syntax for(init;condition;incr/decr){ while(condition){ do{


// code to be executed //code to be executed //code to be executed
} } }while(condition);

Example //for loop //while loop //do-while loop


for(int i=1;i<=10;i++){ int i=1; int i=1;
System.out.println(i); while(i<=10){ do{
} System.out.println(i); System.out.println(i);
i++; i++;
} }while(i<=10);

Syntax for for(;;){ while(true){ do{


infinitive loop //code to be executed //code to be executed //code to be executed
} } }while(true);

Java While Loop


The Java while loop is used to iterate a part of the program repeatedly until the specified Boolean condition is
true. As soon as the Boolean condition becomes false, the loop automatically stops.

The while loop is considered as a repeating if statement. If the number of iteration is not fixed, it is recommended
to use the while loop.

Syntax:

1. while (condition){    
2. //code to be executed   
3. I ncrement / decrement statement  
4. }    

The different parts of do-while loop:

Prime Ministers of India | List of Prime Minister of India (1947-2020)

1. Condition: It is an expression which is tested. If the condition is true, the loop body is executed and control goes
to update expression. When the condition becomes false, we exit the while loop.

Example:

i <=100
2. Update expression: Every time the loop body is executed, this expression increments or decrements loop
variable.

Example:

i++;

Flowchart of Java While Loop

Here, the important thing about while loop is that, sometimes it may not even execute. If the condition to be
tested results into false, the loop body is skipped and first statement after the while loop will be executed.

Example:

In the below example, we print integer values from 1 to 10. Unlike the for loop, we separately need to initialize
and increment the variable used in the condition (here, i). Otherwise, the loop will execute infinitely.

WhileExample.java

1. public class WhileExample {  
2. public static void main(String[] args) {  
3.     int i=1;  
4.     while(i<=10){  
5.         System.out.println(i);  
6.     i++;  
7.     }  
8. }  
9. }  
Test it Now

Output:

1
2
3
4
5
6
7
8
9
10

Java Infinitive While Loop


If you pass true in the while loop, it will be infinitive while loop.

Syntax:

1. while(true){  
2. //code to be executed  
3. }  

Example:

WhileExample2.java

1. public class WhileExample2 {    
2. public static void main(String[] args) {   
3.  // setting the infinite while loop by passing true to the condition  
4.     while(true){    
5.         System.out.println("infinitive while loop");    
6.     }    
7. }    
8. }    
Output:

infinitive while loop


infinitive while loop
infinitive while loop
infinitive while loop
infinitive while loop
ctrl+c

In the above code, we need to enter Ctrl + C command to terminate the infinite loop.

Java do-while Loop


The Java do-while loop is used to iterate a part of the program repeatedly, until the specified condition is true. If
the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to
use a do-while loop.

Java do-while loop is called an exit control loop. Therefore, unlike while loop and for loop, the do-while check
the condition at the end of loop body. The Java do-while loop is executed at least once because condition is
checked after loop body.

Syntax:

1. do{    
2. //code to be executed / loop body  
3. //update statement   
4. }while (condition);    

The different parts of do-while loop:

SQL CREATE TABLE

1. Condition: It is an expression which is tested. If the condition is true, the loop body is executed and control goes
to update expression. As soon as the condition becomes false, loop breaks automatically.

Example:

i <=100

2. Update expression: Every time the loop body is executed, the this expression increments or decrements loop
variable.

Example:

i++;
Note: The do block is executed at least once, even if the condition is false.

Flowchart of do-while loop:

Example:

In the below example, we print integer values from 1 to 10. Unlike the for loop, we separately need to initialize
and increment the variable used in the condition (here, i). Otherwise, the loop will execute infinitely.

DoWhileExample.java

1. public class DoWhileExample {    
2. public static void main(String[] args) {    
3.     int i=1;    
4.     do{    
5.         System.out.println(i);    
6.     i++;    
7.     }while(i<=10);    
8. }    
9. }    
Test it Now

Output:

1
2
3
4
5
6
7
8
9
10

Java Infinitive do-while Loop


If you pass true in the do-while loop, it will be infinitive do-while loop.

Syntax:

1. do{  
2. //code to be executed  
3. }while(true);  

Example:

DoWhileExample2.java

1. public class DoWhileExample2 {  
2. public static void main(String[] args) {  
3.     do{  
4.         System.out.println("infinitive do while loop");  
5.     }while(true);  
6. }  
7. }  

Output:

infinitive do while loop


infinitive do while loop
infinitive do while loop
ctrl+c

In the above code, we need to enter Ctrl + C command to terminate the infinite loop.

Java Variables
A variable is a container which holds the value while the Java program is executed. A variable is assigned with a
data type.

Variable is a name of memory location. There are three types of variables in java: local, instance and static.

There are two types of data types in Java: primitive and non-primitive.

Variable
A variable is the name of a reserved area allocated in memory. In other words, it is a name of the memory
location. It is a combination of "vary + able" which means its value can be changed.

Competitive questions on Structures in Hindi

Keep Watching
1. int data=50;//Here data is variable  

Types of Variables
There are three types of variables in Java:

o local variable
o instance variable
o static variable
1) Local Variable

A variable declared inside the body of the method is called local variable. You can use this variable only within
that method and the other methods in the class aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable

A variable declared inside the class but outside the body of the method, is called an instance variable. It is not
declared as static.

It is called an instance variable because its value is instance-specific and is not shared among instances.

3) Static variable

A variable that is declared as static is called a static variable. It cannot be local. You can create a single copy of the
static variable and share it among all the instances of the class. Memory allocation for static variables happens
only once when the class is loaded in the memory.
Example to understand the types of variables in java

1. public class A  
2. {  
3.     static int m=100;//static variable  
4.     void method()  
5.     {    
6.         int n=90;//local variable    
7.     }  
8.     public static void main(String args[])  
9.     {  
10.         int data=50;//instance variable    
11.     }  
12. }//end of class   

Java Variable Example: Add Two Numbers


1. public class Simple{    
2. public static void main(String[] args){    
3. int a=10;    
4. int b=10;    
5. int c=a+b;    
6. System.out.println(c);    
7. }  
8. }    

Output:

20

Java Variable Example: Widening


1. public class Simple{  
2. public static void main(String[] args){  
3. int a=10;  
4. float f=a;  
5. System.out.println(a);  
6. System.out.println(f);  
7. }}  
Output:

10
10.0

Java Variable Example: Narrowing (Typecasting)


1. public class Simple{  
2. public static void main(String[] args){  
3. float f=10.5f;  
4. //int a=f;//Compile time error  
5. int a=(int)f;  
6. System.out.println(f);  
7. System.out.println(a);  
8. }}  

Output:

10.5
10

Java Variable Example: Overflow


1. class Simple{  
2. public static void main(String[] args){  
3. //Overflow  
4. int a=130;  
5. byte b=(byte)a;  
6. System.out.println(a);  
7. System.out.println(b);  
8. }}  

Output:

130
-126

Java Variable Example: Adding Lower Type


1. class Simple{  
2. public static void main(String[] args){  
3. byte a=10;  
4. byte b=10;  
5. //byte c=a+b;//Compile Time Error: because a+b=20 will be int  
6. byte c=(byte)(a+b);  
7. System.out.println(c);  
8. }}  

Output:

20

PL/SQL Cursor
When an SQL statement is processed, Oracle creates a memory area known as context area. A cursor is a pointer
to this context area. It contains all information needed for processing the statement. In PL/SQL, the context area is
controlled by Cursor. A cursor contains information on a select statement and the rows of data accessed by it.

A cursor is used to referred to a program to fetch and process the rows returned by the SQL statement, one at a
time. There are two types of cursors:

o Implicit Cursors
o Explicit Cursors

1) PL/SQL Implicit Cursors


The implicit cursors are automatically generated by Oracle while an SQL statement is executed, if you don't use an
explicit cursor for the statement.

These are created by default to process the statements when DML statements like INSERT, UPDATE, DELETE etc.
are executed.

C++ vs Java

Orcale provides some attributes known as Implicit cursor's attributes to check the status of DML operations. Some
of them are: %FOUND, %NOTFOUND, %ROWCOUNT and %ISOPEN.

For example: When you execute the SQL statements like INSERT, UPDATE, DELETE then the cursor attributes tell
whether any rows are affected and how many have been affected. If you run a SELECT INTO statement in PL/SQL
block, the implicit cursor attribute can be used to find out whether any row has been returned by the SELECT
statement. It will return an error if there no data is selected.

The following table soecifies the status of the cursor with each of its attribute.

Attribute Description
%FOUND Its return value is TRUE if DML statements like INSERT, DELETE and UPDATE affect at least one row or
more rows or a SELECT INTO statement returned one or more rows. Otherwise it returns FALSE.

%NOTFOUND Its return value is TRUE if DML statements like INSERT, DELETE and UPDATE affect no row, or a
SELECT INTO statement return no rows. Otherwise it returns FALSE. It is a just opposite of %FOUND.

%ISOPEN It always returns FALSE for implicit cursors, because the SQL cursor is automatically closed after
executing its associated SQL statements.

%ROWCOUN It returns the number of rows affected by DML statements like INSERT, DELETE, and UPDATE or
T returned by a SELECT INTO statement.

PL/SQL Implicit Cursor Example


Create customers 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

Let's execute the following program to update the table and increase salary of each customer by 5000. Here, SQL
%ROWCOUNT attribute is used to determine the number of rows affected:

Create procedure:

1. DECLARE   
2.    total_rows number(2);  
3. BEGIN  
4.    UPDATE  customers  
5.    SET salary = salary + 5000;  
6.    IF sql%notfound THEN  
7.       dbms_output.put_line('no customers updated');  
8.    ELSIF sql%found THEN  
9.       total_rows := sql%rowcount;  
10.       dbms_output.put_line( total_rows || ' customers updated ');  
11.    END IF;   
12. END;  
13. /  

Output:

6 customers updated
PL/SQL procedure successfully completed.

Now, if you check the records in customer table, you will find that the rows are updated.

1. select * from customers;  

ID NAME AGE ADDRESS SALARY

1 Ramesh 23 Allahabad 25000

2 Suresh 22 Kanpur 27000

3 Mahesh 24 Ghaziabad 29000

4 Chandan 25 Noida 31000

5 Alex 21 Paris 33000

6 Sunita 20 Delhi 35000

2) PL/SQL Explicit Cursors


The Explicit cursors are defined by the programmers to gain more control over the context area. These cursors
should be defined in the declaration section of the PL/SQL block. It is created on a SELECT statement which
returns more than one row.

Following is the syntax to create an explicit cursor:

Syntax of explicit cursor


Following is the syntax to create an explicit cursor:

1. CURSOR cursor_name IS select_statement;;  
Steps:
You must follow these steps while working with an explicit cursor.

1. Declare the cursor to initialize in the memory.


2. Open the cursor to allocate memory.
3. Fetch the cursor to retrieve data.
4. Close the cursor to release allocated memory.

1) Declare the cursor:


It defines the cursor with a name and the associated SELECT statement.

Syntax for explicit cursor decleration

1. CURSOR name IS  
2.  SELECT statement;   

2) Open the cursor:


It is used to allocate memory for the cursor and make it easy to fetch the rows returned by the SQL statements
into it.

Syntax for cursor open:

1. OPEN cursor_name;  

3) Fetch the cursor:


It is used to access one row at a time. You can fetch rows from the above-opened cursor as follows:

Syntax for cursor fetch:

1. FETCH cursor_name INTO variable_list;  

4) Close the cursor:


It is used to release the allocated memory. The following syntax is used to close the above-opened cursors.

Syntax for cursor close:

1. Close cursor_name;  
PL/SQL Explicit Cursor Example
Explicit cursors are defined by programmers to gain more control over the context area. It is defined in the
declaration section of the PL/SQL block. It is created on a SELECT statement which returns more than one row.

Let's take an example to demonstrate the use of explicit cursor. In this example, we are using the already created
CUSTOMERS table.

Create customers 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 procedure:

Execute the following program to retrieve the customer name and address.

1. DECLARE  
2.    c_id customers.id%type;  
3.    c_name customers.name%type;  
4.    c_addr customers.address%type;  
5.    CURSOR c_customers is  
6.       SELECT id, name, address FROM customers;  
7. BEGIN  
8.    OPEN c_customers;  
9.    LOOP  
10.       FETCH c_customers into c_id, c_name, c_addr;  
11.       EXIT WHEN c_customers%notfound;  
12.       dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);  
13.    END LOOP;  
14.    CLOSE c_customers;  
15. END;  
16. /  

Output:

1 Ramesh Allahabad
2 Suresh Kanpur
3 Mahesh Ghaziabad
4 Chandan Noida
5 Alex Paris
6 Sunita Delhi
PL/SQL procedure successfully completed.

PL/SQL Trigger
Trigger is invoked by Oracle engine automatically whenever a specified event occurs.Trigger is stored into
database and invoked repeatedly, when specific condition match.

Triggers are stored programs, which are automatically executed or fired when some event occurs.

Triggers are written to be executed in response to any of the following events.

o A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).


o A database definition (DDL) statement (CREATE, ALTER, or DROP).
o A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).

Triggers could be defined on the table, view, schema, or database with which the event is associated.

Competitive questions on Structures

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 transactions
Creating a trigger:
Syntax for creating trigger:

1. CREATE [OR REPLACE ] TRIGGER trigger_name   
2. {BEFORE | AFTER | INSTEAD OF }   
3. {INSERT [OR] | UPDATE [OR] | DELETE}   
4. [OF col_name]   
5. ON table_name   
6. [REFERENCING OLD AS o NEW AS n]   
7. [FOR EACH ROW]   
8. WHEN (condition)    
9. DECLARE  
10.    Declaration-statements  
11. BEGIN   
12.    Executable-statements  
13. EXCEPTION  
14.    Exception-handling-statements  
15. END;  

Here,

o CREATE [OR REPLACE] TRIGGER trigger_name: It creates or replaces an existing trigger with the
trigger_name.
o {BEFORE | AFTER | INSTEAD OF} : This specifies when the trigger would be executed. 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. This trigger will display the salary difference between
the old values and new values:

1. CREATE OR REPLACE TRIGGER display_salary_changes  
2. BEFORE DELETE OR INSERT OR UPDATE ON customers  
3. FOR EACH ROW  
4. WHEN (NEW.ID > 0)  
5. DECLARE  
6.    sal_diff number;  
7. BEGIN  
8.    sal_diff := :NEW.salary  - :OLD.salary;  
9.    dbms_output.put_line('Old salary: ' || :OLD.salary);  
10.    dbms_output.put_line('New salary: ' || :NEW.salary);  
11.    dbms_output.put_line('Salary difference: ' || sal_diff);  
12. END;  
13. /  

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.

1. DECLARE   
2.    total_rows number(2);  
3. BEGIN  
4.    UPDATE  customers  
5.    SET salary = salary + 5000;  
6.    IF sql%notfound THEN  
7.       dbms_output.put_line('no customers updated');  
8.    ELSIF sql%found THEN  
9.       total_rows := sql%rowcount;  
10.       dbms_output.put_line( total_rows || ' customers updated ');  
11.    END IF;   
12. END;  
13. /  

Output:

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
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 by 5000 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 point and should be noted carefully.

o OLD and NEW references are used for record level triggers these are not avialable for table 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 initial changes are applied and the table is
back in a consistent state.

Normalization
o Normalization is the process of organizing the data in the database.
o Normalization is used to minimize the redundancy from a relation or set of relations. It is also used to
eliminate the undesirable characteristics like Insertion, Update and Deletion Anomalies.
o Normalization divides the larger table into the smaller table and links them using relationship.
o The normal form is used to reduce redundancy from the database table.

Types of Normal Forms


There are the four types of normal forms:
Normal Description
Form

1NF A relation is in 1NF if it contains an atomic value.

2NF A relation will be in 2NF if it is in 1NF and all non-key attributes are fully functional dependent on the
primary key.

3NF A relation will be in 3NF if it is in 2NF and no transition dependency exists.

4NF A relation will be in 4NF if it is in Boyce Codd normal form and has no multi-valued dependency.

5NF A relation is in 5NF if it is in 4NF and not contains any join dependency and joining should be
lossless.

First Normal Form (1NF)


o A relation will be 1NF if it contains an atomic value.
o It states that an attribute of a table cannot hold multiple values. It must hold only single-valued attribute.
o First normal form disallows the multi-valued attribute, composite attribute, and their combinations.

Example: Relation EMPLOYEE is not in 1NF because of multi-valued attribute EMP_PHONE.

EMPLOYEE table:

EMP_ID EMP_NAME EMP_PHONE EMP_STATE

14 John 7272826385, UP
9064738238

20 Harry 8574783832 Bihar

12 Sam 7390372389, Punjab


8589830302

The decomposition of the EMPLOYEE table into 1NF has been shown below:

EMP_ID EMP_NAME EMP_PHONE EMP_STATE

14 John 7272826385 UP

14 John 9064738238 UP

20 Harry 8574783832 Bihar

12 Sam 7390372389 Punjab

12 Sam 8589830302 Punjab

Second Normal Form (2NF)


o In the 2NF, relational must be in 1NF.
o In the second normal form, all non-key attributes are fully functional dependent on the primary key

Example: Let's assume, a school can store the data of teachers and the subjects they teach. In a school, a teacher
can teach more than one subject.

TEACHER table

TEACHER_ID SUBJECT TEACHER_AGE

25 Chemistry 30

25 Biology 30

47 English 35

83 Math 38

83 Computer 38
In the given table, non-prime attribute TEACHER_AGE is dependent on TEACHER_ID which is a proper subset of a
candidate key. That's why it violates the rule for 2NF.

To convert the given table into 2NF, we decompose it into two tables:

10 Sec
Hello Java Program for Beginners

TEACHER_DETAIL table:

TEACHER_ID TEACHER_AGE

25 30

47 35

83 38

TEACHER_SUBJECT table:

TEACHER_ID SUBJECT

25 Chemistry

25 Biology

47 English

83 Math

83 Computer

Third Normal Form (3NF)


o A relation will be in 3NF if it is in 2NF and not contain any transitive partial dependency.
o 3NF is used to reduce the data duplication. It is also used to achieve the data integrity.
o If there is no transitive dependency for non-prime attributes, then the relation must be in third normal
form.

A relation is in third normal form if it holds atleast one of the following conditions for every non-trivial function
dependency X → Y.

1. X is a super key.
2. Y is a prime attribute, i.e., each element of Y is part of some candidate key.

Example:

EMPLOYEE_DETAIL table:

EMP_ID EMP_NAME EMP_ZIP EMP_STATE EMP_CITY

222 Harry 201010 UP Noida

333 Stephan 02228 US Boston

444 Lan 60007 US Chicago

555 Katharine 06389 UK Norwich

666 John 462007 MP Bhopal

Super key in the table above:

1. {EMP_ID}, {EMP_ID, EMP_NAME}, {EMP_ID, EMP_NAME, EMP_ZIP}....so on  

Candidate key: {EMP_ID}

Non-prime attributes: In the given table, all attributes except EMP_ID are non-prime.

Here, EMP_STATE & EMP_CITY dependent on EMP_ZIP and EMP_ZIP dependent on EMP_ID. The non-prime
attributes (EMP_STATE, EMP_CITY) transitively dependent on super key(EMP_ID). It violates the rule of third
normal form.

That's why we need to move the EMP_CITY and EMP_STATE to the new <EMPLOYEE_ZIP> table, with
EMP_ZIP as a Primary key.

EMPLOYEE table:

EMP_ID EMP_NAME EMP_ZIP

222 Harry 201010

333 Stephan 02228

444 Lan 60007

555 Katharine 06389


666 John 462007

EMPLOYEE_ZIP table:

EMP_ZIP EMP_STATE EMP_CITY

201010 UP Noida

02228 US Boston

60007 US Chicago

06389 UK Norwich

462007 MP Bhopal

Boyce Codd normal form (BCNF)


o BCNF is the advance version of 3NF. It is stricter than 3NF.
o A table is in BCNF if every functional dependency X → Y, X is the super key of the table.
o For BCNF, the table should be in 3NF, and for every FD, LHS is super key.

Example: Let's assume there is a company where employees work in more than one department.

EMPLOYEE table:

EMP_ID EMP_COUNTRY EMP_DEPT DEPT_TYPE EMP_DEPT_NO

264 India Designing D394 283

264 India Testing D394 300

364 UK Stores D283 232

364 UK Developing D283 549

In the above table Functional dependencies are as follows:

1. EMP_ID  →  EMP_COUNTRY  
2. EMP_DEPT  →   {DEPT_TYPE, EMP_DEPT_NO}  

Candidate key: {EMP-ID, EMP-DEPT}


Java Try Catch

The table is not in BCNF because neither EMP_DEPT nor EMP_ID alone are keys.

To convert the given table into BCNF, we decompose it into three tables:

EMP_COUNTRY table:

EMP_ID EMP_COUNTRY

264 India

264 India

EMP_DEPT table:

EMP_DEPT DEPT_TYPE EMP_DEPT_NO

Designing D394 283

Testing D394 300

Stores D283 232

Developing D283 549

EMP_DEPT_MAPPING table:

EMP_ID EMP_DEPT

D394 283

D394 300

D283 232

D283 549

Functional dependencies:

1. EMP_ID   →    EMP_COUNTRY  
2. EMP_DEPT   →   {DEPT_TYPE, EMP_DEPT_NO}  
Candidate keys:

For the first table: EMP_ID


For the second table: EMP_DEPT
For the third table: {EMP_ID, EMP_DEPT}

Now, this is in BCNF because left side part of both the functional dependencies is a key.

Fourth normal form (4NF)


o A relation will be in 4NF if it is in Boyce Codd normal form and has no multi-valued dependency.
o For a dependency A → B, if for a single value of A, multiple values of B exists, then the relation will be a
multi-valued dependency.

Example
STUDENT

STU_ID COURSE HOBBY

21 Computer Dancing

21 Math Singing

34 Chemistry Dancing

74 Biology Cricket

59 Physics Hockey

The given STUDENT table is in 3NF, but the COURSE and HOBBY are two independent entity. Hence, there is no
relationship between COURSE and HOBBY.

In the STUDENT relation, a student with STU_ID, 21 contains two courses, Computer and Math and two


hobbies, Dancing and Singing. So there is a Multi-valued dependency on STU_ID, which leads to unnecessary
repetition of data.

So to make the above table into 4NF, we can decompose it into two tables:

STUDENT_COURSE

STU_ID COURSE
21 Computer

21 Math

34 Chemistry

74 Biology

59 Physics

STUDENT_HOBBY

STU_ID HOBBY

21 Dancing

21 Singing

34 Dancing

74 Cricket

59 Hockey

Fifth normal form (5NF)


o A relation is in 5NF if it is in 4NF and not contains any join dependency and joining should be lossless.
o 5NF is satisfied when all the tables are broken into as many tables as possible in order to avoid
redundancy.
o 5NF is also known as Project-join normal form (PJ/NF).

Example

SUBJECT LECTURER SEMESTER

Computer Anshika Semester 1

Computer John Semester 1

Math John Semester 1

Math Akash Semester 2


Chemistry Praveen Semester 1

In the above table, John takes both Computer and Math class for Semester 1 but he doesn't take Math class for
Semester 2. In this case, combination of all these fields required to identify a valid data.

Suppose we add a new Semester as Semester 3 but do not know about the subject and who will be taking that
subject so we leave Lecturer and Subject as NULL. But all three columns together acts as a primary key, so we
can't leave other two columns blank.

So to make the above table into 5NF, we can decompose it into three relations P1, P2 & P3:

P1

Prime Ministers of India | List of Prime Minister of India (1947-2020)

SEMESTER SUBJECT

Semester 1 Computer

Semester 1 Math

Semester 1 Chemistry

Semester 2 Math

P2

SUBJECT LECTURER

Computer Anshika

Computer John

Math John

Math Akash

Chemistry Praveen

P3

SEMSTER LECTURER
Semester 1 Anshika

Semester 1 John

Semester 1 John

Semester 2 Akash

Semester 1 Praveen

Transaction
o The transaction is a set of logically related operation. It contains a group of tasks.
o A transaction is an action or series of actions. It is performed by a single user to perform operations for accessing the
contents of the database.

Example: Suppose an employee of bank transfers Rs 800 from X's account to Y's account. This small transaction
contains several low-level tasks:

X's Account

1. Open_Account(X)  
2. Old_Balance = X.balance  
3. New_Balance = Old_Balance - 800  
4. X.balance = New_Balance  
5. Close_Account(X)  

Y's Account

1. Open_Account(Y)  
2. Old_Balance = Y.balance  
3. New_Balance = Old_Balance + 800  
4. Y.balance = New_Balance  
5. Close_Account(Y)  

Operations of Transaction:
Following are the main operations of transaction:

Read(X): Read operation is used to read the value of X from the database and stores it in a buffer in main
memory.
Write(X): Write operation is used to write the value back to the database from the buffer.

Let's take an example to debit transaction from an account which consists of following operations:

1. 1.  R(X);  
2. 2.  X = X - 500;  
3. 3.  W(X);  

Let's assume the value of X before starting of the transaction is 4000.

o The first operation reads X's value from database and stores it in a buffer.
o The second operation will decrease the value of X by 500. So buffer will contain 3500.
o The third operation will write the buffer's value to the database. So X's final value will be 3500.

But it may be possible that because of the failure of hardware, software or power, etc. that transaction may fail
before finished all the operations in the set.

For example: If in the above transaction, the debit transaction fails after executing operation 2 then X's value will
remain 4000 in the database which is not acceptable by the bank.

To solve this problem, we have two important operations:

Commit: It is used to save the work done permanently.

Rollback: It is used to undo the work done.

Transaction property
The transaction has the four properties. These are used to maintain consistency in a database, before and after the
transaction.

Property of Transaction
1. Atomicity
2. Consistency
3. Isolation
4. Durability
Atomicity
o It states that all operations of the transaction take place at once if not, the transaction is aborted.
o There is no midway, i.e., the transaction cannot occur partially. Each transaction is treated as one unit and either run
to completion or is not executed at all.

Atomicity involves the following two operations:

Abort: If a transaction aborts then all the changes made are not visible.

Commit: If a transaction commits then all the changes made are visible.

Prime Ministers of India | List of Prime Minister of India (1947-2020)


Example: Let's assume that following transaction T consisting of T1 and T2. A consists of Rs 600 and B consists of
Rs 300. Transfer Rs 100 from account A to account B.

T1 T2

Read(A) Read(B)
A:= A-100 Y:= Y+100
Write(A) Write(B)

After completion of the transaction, A consists of Rs 500 and B consists of Rs 400.

If the transaction T fails after the completion of transaction T1 but before completion of transaction T2, then the
amount will be deducted from A but not added to B. This shows the inconsistent database state. In order to
ensure correctness of database state, the transaction must be executed in entirety.

Consistency
o The integrity constraints are maintained so that the database is consistent before and after the transaction.
o The execution of a transaction will leave a database in either its prior stable state or a new stable state.
o The consistent property of database states that every transaction sees a consistent database instance.
o The transaction is used to transform the database from one consistent state to another consistent state.

For example: The total amount must be maintained before or after the transaction.

1. Total before T occurs = 600+300=900  
2. Total after T occurs= 500+400=900  

Therefore, the database is consistent. In the case when T1 is completed but T2 fails, then inconsistency will occur.

Isolation
o It shows that the data which is used at the time of execution of a transaction cannot be used by the second
transaction until the first one is completed.
o In isolation, if the transaction T1 is being executed and using the data item X, then that data item can't be accessed
by any other transaction T2 until the transaction T1 ends.
o The concurrency control subsystem of the DBMS enforced the isolation property.

Durability
o The durability property is used to indicate the performance of the database's consistent state. It states that the
transaction made the permanent changes.
o They cannot be lost by the erroneous operation of a faulty transaction or by the system failure. When a transaction is
completed, then the database reaches a state known as the consistent state. That consistent state cannot be lost,
even in the event of a system's failure.
o The recovery subsystem of the DBMS has the responsibility of Durability property.

States of Transaction
In a database, the transaction can be in one of the following states -

Active state

o The active state is the first state of every transaction. In this state, the transaction is being executed.
o For example: Insertion or deletion or updating a record is done here. But all the records are still not saved to the
database.

Partially committed

o In the partially committed state, a transaction executes its final operation, but the data is still not saved to the
database.
o In the total mark calculation example, a final display of the total marks step is executed in this state.

Committed
A transaction is said to be in a committed state if it executes all its operations successfully. In this state, all the
effects are now permanently saved on the database system.

Failed state

o If any of the checks made by the database recovery system fails, then the transaction is said to be in the failed state.
o In the example of total mark calculation, if the database is not able to fire a query to fetch the marks, then the
transaction will fail to execute.

Aborted

o If any of the checks fail and the transaction has reached a failed state then the database recovery system will make
sure that the database is in its previous consistent state. If not then it will abort or roll back the transaction to bring
the database into a consistent state.
o If the transaction fails in the middle of the transaction then before executing the transaction, all the executed
transactions are rolled back to its consistent state.
o After aborting the transaction, the database recovery module will select one of the two operations:
1. Re-start the transaction
2. Kill the transaction

PL/SQL Exception Handling


What is Exception
An error occurs during the program execution is called Exception in PL/SQL.

PL/SQL facilitates programmers to catch such conditions using exception block in the program and an appropriate
action is taken against the error condition.

There are two type of exceptions:

o System-defined Exceptions
o User-defined Exceptions

PL/SQL Exception Handling


Syntax for exception handling:

SQL CREATE TABLE


Following is a general syntax for exception handling:

1. DECLARE  
2.    <declarations section>  
3. BEGIN  
4.    <executable command(s)>  
5. EXCEPTION  
6.    <exception handling goes here >  
7.    WHEN exception1 THEN   
8.        exception1-handling-statements   
9.    WHEN exception2  THEN   
10.       exception2-handling-statements   
11.    WHEN exception3 THEN   
12.       exception3-handling-statements  
13.    ........  
14.    WHEN others THEN  
15.       exception3-handling-statements  
16. END;  

Example of exception handling


Let's take a simple example to demonstrate the concept of exception handling. Here we are using the already
created CUSTOMERS table.

SELECT* FROM COUSTOMERS;

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

1. DECLARE  
2.    c_id customers.id%type := 8;  
3.    c_name  customers.name%type;  
4.    c_addr customers.address%type;  
5. BEGIN  
6.    SELECT  name, address INTO  c_name, c_addr  
7.    FROM customers  
8.    WHERE id = c_id;  
9. DBMS_OUTPUT.PUT_LINE ('Name: '||  c_name);  
10.  DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);  
11. EXCEPTION  
12.    WHEN no_data_found THEN  
13.       dbms_output.put_line('No such customer!');  
14.    WHEN others THEN  
15.       dbms_output.put_line('Error!');  
16. END;  
17. /   

After the execution of above code at SQL Prompt, it produces the following result:

No such customer!
PL/SQL procedure successfully completed.

The above program should show the name and address of a customer as result whose ID is given. But there is no
customer with ID value 8 in our database, so the program raises the run-time exception NO_DATA_FOUND, which
is captured in EXCEPTION block.

Note: You get the result "No such customer" because the customer_id used in the above example is 8 and
there is no cutomer having id value 8 in that table.

If you use the id defined in the above table (i.e. 1 to 6), you will get a certain result. For a demo example: here, we
are using the id 5.

1. DECLARE  
2.    c_id customers.id%type := 5;  
3.    c_name  customers.name%type;  
4.    c_addr customers.address%type;  
5. BEGIN  
6.    SELECT  name, address INTO  c_name, c_addr  
7.    FROM customers  
8.    WHERE id = c_id;  
9. DBMS_OUTPUT.PUT_LINE ('Name: '||  c_name);  
10.  DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);  
11. EXCEPTION  
12.    WHEN no_data_found THEN  
13.       dbms_output.put_line('No such customer!');  
14.    WHEN others THEN  
15.       dbms_output.put_line('Error!');  
16. END;  
17. /   

After the execution of above code at SQL prompt, you will get the following result:

Name: alex
Address: paris
PL/SQL procedure successfully completed.

Raising Exceptions
In the case of any internal database error, exceptions are raised by the database server automatically. But it can
also be raised explicitly by programmer by using command RAISE.

Syntax for raising an exception:

1. DECLARE  
2.    exception_name EXCEPTION;  
3. BEGIN  
4.    IF condition THEN  
5.       RAISE exception_name;  
6.    END IF;  
7. EXCEPTION  
8.    WHEN exception_name THEN  
9.    statement;  
10. END;  

PL/SQL User-defined Exceptions


PL/SQL facilitates their users to define their own exceptions according to the need of the program. A user-defined
exception can be raised explicitly, using either a RAISE statement or the procedure
DBMS_STANDARD.RAISE_APPLICATION_ERROR.

Syntax for user define exceptions

1. DECLARE  
2. my-exception EXCEPTION;   

PL/SQL Pre-defined Exceptions


There are many pre-defined exception in PL/SQL which are executed when any database rule is violated by the
programs.

For example: NO_DATA_FOUND is a pre-defined exception which is raised when a SELECT INTO statement
returns no rows.

Following is a list of some important pre-defined exceptions:

Exception Oracle SQL Description


Error Code

ACCESS_INTO_NULL 06530 -6530 It is raised when a NULL object is automatically assigned a value.

CASE_NOT_FOUND 06592 -6592 It is raised when none of the choices in the "WHEN" clauses of a CASE
statement is selected, and there is no else clause.

COLLECTION_IS_NULL 06531 -6531 It is raised when a program attempts to apply collection methods other than
exists to an uninitialized nested table or varray, or the program attempts to
assign values to the elements of an uninitialized nested table or varray.

DUP_VAL_ON_INDEX 00001 -1 It is raised when duplicate values are attempted to be stored in a column with
unique index.

INVALID_CURSOR 01001 -1001 It is raised when attempts are made to make a cursor operation that is not
allowed, such as closing an unopened cursor.

INVALID_NUMBER 01722 -1722 It is raised when the conversion of a character string into a number fails
because the string does not represent a valid number.

LOGIN_DENIED 01017 -1017 It is raised when s program attempts to log on to the database with an invalid
username or password.

NO_DATA_FOUND 01403 +100 It is raised when a select into statement returns no rows.

NOT_LOGGED_ON 01012 -1012 It is raised when a database call is issued without being connected to the
database.

PROGRAM_ERROR 06501 -6501 It is raised when PL/SQL has an internal problem.

ROWTYPE_MISMATC 06504 -6504 It is raised when a cursor fetches value in a variable having incompatible data
H type.

SELF_IS_NULL 30625 -30625 It is raised when a member method is invoked, but the instance of the object
type was not initialized.

STORAGE_ERROR 06500 -6500 It is raised when PL/SQL ran out of memory or memory was corrupted.

TOO_MANY_ROWS 01422 -1422 It is raised when a SELECT INTO statement returns more than one row.

VALUE_ERROR 06502 -6502 It is raised when an arithmetic, conversion, truncation, or size-constraint error
occurs.

ZERO_DIVIDE 01476 1476 It is raised when an attempt is made to divide a number by zero.

SQL JOIN
As the name shows, JOIN means to combine something. In case of SQL, JOIN means "to combine two or more
tables".

The SQL JOIN clause takes records from two or more tables in a database and combines it together.

ANSI standard SQL defines five types of JOIN :

1. inner join,
2. left outer join,
3. right outer join,
4. full outer join, and
5. cross join.
In the process of joining, rows of both tables are combined in a single table.

Why SQL JOIN is used?


If you want to access more than one table through a select statement.

If you want to combine two or more table then SQL JOIN statement is used .it combines rows of that tables in one
table and one can retrieve the information by a SELECT statement.

The joining of two or more tables is based on common field between them.

SQL INNER JOIN also known as simple join is the most common type of join.

How to use SQL join or SQL Inner Join?


Let an example to deploy SQL JOIN process:

1.Staff table

ID Staff_NAME Staff_AGE STAFF_ADDRESS Monthley_Package

1 ARYAN 22 MUMBAI 18000

2 SUSHIL 32 DELHI 20000

3 MONTY 25 MOHALI 22000

4 AMIT 20 ALLAHABAD 12000

2.Payment table

Payment_ID DATE Staff_ID AMOUNT

101 30/12/2009 1 3000.00

102 22/02/2010 3 2500.00


103 23/02/2010 4 3500.00

So if you follow this JOIN statement to join these two tables ?

1. SELECT Staff_ID, Staff_NAME, Staff_AGE, AMOUNT   
2.    FROM STAFF s, PAYMENT p  
3.    WHERE s.ID =p.STAFF_ID;  

This will produce the result like this:

STAFF_ID NAME Staff_AGE AMOUNT

3 MONTY 25 2500

1 ARYAN 22 3000

4 AMIT 25 3500

1 ARYAN 22 3000

SQL OUTER JOIN


In the SQL outer JOIN all the content of the both tables are integrated together either they are matched or not.

If you take an example of employee table

Outer join of two types:

1.Left outer join (also known as left join): this join returns all the rows from left table combine with the matching
rows of the right table. If you get no matching in the right table it returns NULL values.

Features of Java - Javatpoint

2.Right outer join (also known as right join): this join returns all the rows from right table are combined with the
matching rows of left table .If you get no column matching in the left table .it returns null value.

This diagram shows the different type of joins:

SQL LEFT JOIN


The SQL left join returns all the values from the left table and it also includes matching values from right table, if
there are no matching join value it returns NULL.

BASIC SYNTAX FOR LEFT JOIN:

1. SELECT table1.column1, table2.column2....  
2. FROM table1   
3. LEFTJOIN table2  
4. ON table1.column_field = table2.column_field;  

let us take two tables in this example to elaborate all the things:

CUSTOMER TABLE:

ID NAME AGE SALARY

1 ARYAN 51 56000

2 AROHI 21 25000

3 VINEET 24 31000

4 AJEET 23 32000

5 RAVI 23 42000

This is second table

ORDER TABLE:

O_ID DATE CUSTOMER_ID AMOUNT

001 20-01-2012 2 3000

002 12-02-2012 2 2000

003 22-03-2012 3 4000

004 11-04-2012 4 5000


join these two tables with LEFT JOIN:

1. SQL SELECT ID, NAME, AMOUNT,DATE  
2. FROM CUSTOMER  
3. LEFT JOIN ORDER  
4. ON CUSTOMER.ID = ORDER.CUSTOMER_ID;  

This will produce the following result:

ID NAME AMOUNT DATE

1 ARYAN NULL NULL

2 AROHI 3000 20-01-2012

2 AROHI 2000 12-02-2012

3 VINEET 4000 22-03-2012

4 AJEET 5000 11-04-2012

5 RAVI NULL NULL

SQL RIGHT JOIN


The SQL right join returns all the values from the rows of right table. It also includes the matched values from left
table but if there is no matching in both tables, it returns NULL.

Basic syntax for right join:

1. SELECT table1.column1, table2.column2.....  
2. FROM table1   
3. RIGHT JOIN table2  
4. ON table1.column_field = table2.column_field;  

let us take an example with 2 tables table1 is CUSTOMERS table and table2 is ORDERS table.
CUSTOMER TABLE:

Exception Handling in Java - Javatpoint

ID NAME AGE SALARY

1 ARYAN 51 56000

2 AROHI 21 25000

3 VINEET 24 31000

4 AJEET 23 32000

5 RAVI 23 42000

and this is the second table:

ORDER TABLE:

DATE O_ID CUSTOMER_ID AMOUNT

20-01-2012 001 2 3000

12-02-2012 002 2 2000

22-03-2012 003 3 4000

11-04-2012 004 4 5000

Here we will join these two tables with SQL RIGHT JOIN:

1. SQL> SELECT ID,NAME,AMOUNT,DATE  
2. FROM CUSTOMER  
3. RIGHT JOIN ORDER  
4. ON CUSTOMER.ID = ORDER.CUSTOMER_ID;  

ID NAME AMOUNT DATE


2 AROHI 3000 20-01-2012

2 AROHI 2000 12-02-2012

3 VINEET 4000 22-03-2012

4 AJEET 5000 11-04-2012

SQL FULL JOIN


The SQL full join is the result of combination of both left and right outer join and the join tables have all the records from
both tables. It puts NULL on the place of matches not found.

SQL full outer join and SQL join are same. generally it is known as SQL FULL JOIN.

SQL full outer join:


What is SQL full outer join?

SQL full outer join is used to combine the result of both left and right outer join and returns all rows (don't care its matched
or unmatched) from the both participating tables.

C++ vs Java

Syntax for full outer join:

1. SELECT *  
2. FROM table1  
3. FULL OUTER JOIN table2  
4. ON table1.column_name = table2.column_name;  

Note:here table1 and table2 are the name of the tables participating in joining and column_name is the column of the
participating tables.

Let us take two tables to demonstrate full outer join:

table_A

A M

1 m
2 n

4 o

table_B

A N

2 p

3 q

5 r

Resulting table

A M A N

2 n 2 p

1 m - -

4 o - -

- - 3 q

- - 5 r

Because this is a full outer join so all rows (both matching and non-matching) from both tables are included in the output.
Here only one row of output displays values in all columns because there is only one match between table_A and table_B.

Pictorial representation of full outer join:

SQL Cross Join


o Join operation in SQL is used to combine multiple tables together into a single table.
o If we use the cross join to combine two different tables, then we will get the Cartesian product of the sets of rows
from the joined table. When each row of the first table is combined with each row from the second table, it is known
as Cartesian join or cross join.
o After performing the cross join operation, the total number of rows present in the final table will be equal to the
product of the number of rows present in table 1 and the number of rows present in table 2.
o For example:
If there are two records in table 1 and three records in table 2, then after performing cross join operation, we will get
six records in the final table.
o Let us take a look at the syntax of writing a query to perform the cross join operation in SQL.

1. SELECT TableName1.columnName1, TableName2.columnName2 FROM TableName1 CROSS JOIN TableNa
me2 ON TableName1.ColumnName = TableName2.ColumnName;    

Now let us see take a deeper dive into the cross join in SQL with the help of examples. All the queries in the
examples will be written using the MySQL database.

Consider we have the following tables with the given data:

Table 1: MatchScore

Player Department_id Goals

Franklin 1 2

Alan 1 3

Priyanka 2 2

Rajesh 3 5

Table 2: Departments

26.1M

446

Hello Java Program for Beginners

Department_id Department_name
1 IT

2 HR

3 Marketing

Table 3: employee

EmployeeID Employee_Name Employee_Salary

1 Arun Tiwari 50000

2 Sachin Rathi 64000

3 Harshal Pathak 48000

4 Arjun Kuwar 46000

5 Sarthak Gada 62000

Table 4: department

DepartmentID Department_Name Employee_ID

1 Production 1

2 Sales 3

3 Marketing 4

4 Accounts 5

Table 5: loan

LoanID Branch Amount


1 B1 15000

2 B2 10000

3 B3 20000

4 B4 100000

Table 6: borrower

CustID CustName LoanID

1 Sonakshi Dixit 1

2 Shital Garg 4

3 Swara Joshi 5

4 Isha Deshmukh 2

Table 7: customer

Customer_ID Name Age Salary

1 Aryan Jain 51 56000

2 Arohi Dixit 21 25000

3 Vineet Garg 24 31000

Table 8: orders

Order_ID Order_Date Cutomer_ID Amount

1 2012-01-20 2 3000
2 2012-05-18 2 2000

3 2012-06-28 3 4000

Example 1:
Write a query to perform the cross join operation considering the MatchScore table as the left table and the
Departments table as the right table.

Query:

1. SELECT * FROM MatchScore CROSS JOIN Departments;  

We have used the SELECT command with the asterisk to retrieve all the columns present in the MatchScore and
Departments table. Then we have used the CROSS JOIN keyword to perform the cross join operation on the
MatchScore and Departments table. Since there are 4 records in the MatchScore and 3 records in the
Departments table, after performing the cross join operation, we will get 12 rows.

After executing this query, you will find the following result:

Player Department_id Goals Depatment_id Department_name

Franklin 1 2 1 IT

Alan 1 3 1 IT

Priyanka 2 2 1 IT

Rajesh 3 5 1 IT

Franklin 1 2 2 HR

Alan 1 3 2 HR

Priyanka 2 2 2 HR

Rajesh 3 5 2 HR

Franklin 1 2 3 Marketing
Alan 1 3 3 Marketing

Priyanka 2 2 3 Marketing

Rajesh 3 5 3 Marketing

Each row from the MatchScore table is combined with each row of the Departments table. Since there are four
records in the MatchScore and three records in the Departments table, we have got 12 rows in the final table after
performing the cross join operation.

Example 2:
Write a query to perform the cross join operation considering the employee table as the left table and the
department table as the right table.

Query:

1. mysql> SELECT *FROM employee CROSS JOIN department;  

We have used the SELECT command with the asterisk to retrieve all the columns present in the employee and
department table. Then we have used the CROSS JOIN keyword to perform the cross join operation on the
employee and department table. Since there are five records in the employee and four records in the department
table, after performing the cross join operation, we will get 20 rows.

After executing this query, you will find the following result:

EmployeeID Employee_Name Employee_Salary DepartmentID Department_Name Employee_ID

1 Arun Tiwari 50000 1 Production 1

1 Arun Tiwari 50000 2 Sales 3

1 Arun Tiwari 50000 3 Marketing 4

1 Arun Tiwari 50000 4 Accounts 5

2 Sachin Rathi 64000 1 Production 1

2 Sachin Rathi 64000 2 Sales 3


2 Sachin Rathi 64000 3 Marketing 4

2 Sachin Rathi 64000 4 Accounts 5

3 Harshal Pathak 48000 1 Production 1

3 Harshal Pathak 48000 2 Sales 3

3 Harshal Pathak 48000 3 Marketing 4

3 Harshal Pathak 48000 4 Accounts 5

4 Arjun Kuwar 46000 1 Production 1

4 Arjun Kuwar 46000 2 Sales 3

4 Arjun Kuwar 46000 3 Marketing 4

4 Arjun Kuwar 46000 4 Accounts 5

5 Sarthak Gada 62000 1 Production 1

5 Sarthak Gada 62000 2 Sales 3

5 Sarthak Gada 62000 3 Marketing 4

5 Sarthak Gada 62000 4 Accounts 5

Each row from the employee table is combined with each row of the department table. Since there are five
records in the employee table and four records in the department table, we have got 20 rows in the final table
after performing the cross join operation.

Example 3:

Write a query to perform the cross join operation considering the loan table as the left table and the borrower
table as the right table.

Query:

1. mysql> SELECT *FROM loan CROSS JOIN borrower;  
We have used the SELECT command with the asterisk to retrieve all the columns present in the loan and the
borrower table. Then we have used the CROSS JOIN keyword to perform the cross join operation on the loan and
the borrower table. Since there are four records in the loan table and four records in the borrower table, after
performing the cross join operation, we will get 16 rows.

After executing this query, you will find the following result:

LoanID Branch Amount CustID CustName LoanID

1 B1 15000 1 Sonakshi Dixit 1

2 B2 10000 1 Sonakshi Dixit 1

3 B3 20000 1 Sonakshi Dixit 1

4 B4 100000 1 Sonakshi Dixit 1

1 B1 15000 2 Shital Garg 4

2 B2 10000 2 Shital Garg 4

3 B3 20000 2 Shital Garg 4

4 B4 100000 2 Shital Garg 4

1 B1 15000 3 Swara Joshi 5

2 B2 10000 3 Swara Joshi 5

3 B3 20000 3 Swara Joshi 5

4 B4 100000 3 Swara Joshi 5

1 B1 15000 4 Isha Deshmukh 2

2 B2 10000 4 Isha Deshmukh 2

3 B3 20000 4 Isha Deshmukh 2


4 B4 100000 4 Isha Deshmukh 2

Each row from the loan table is combined with each row of the borrower table. Since there are four records in the
loan table and four records in the borrower table, after performing the cross join operation, we have got 16 rows.

Example 4:
Write a query to perform the cross join operation considering the customer table as the left table and the orders
table as the right table.

Query:

1. mysql> SELECT *FROM customer CROSS JOIN orders;  

We have used the SELECT command with the asterisk to retrieve all the columns present in the customer and
orders table. Then we have used the CROSS JOIN keyword to perform the cross join operation on the customer
table and the orders table. Since there are three records in the loan table and three records in the orders table,
after performing the cross join operation, we will get 9 rows.

After executing this query, you will find the following result:

Customer_ID Name Age Salary Order_ID Order_Date Customer_ID Amount

1 Aryan Jain 51 56000 1 2012-01-20 2 3000

2 Arohi Dixit 21 25000 1 2012-01-20 2 3000

3 Vineet Garg 24 31000 1 2012-01-20 2 3000

1 Aryan Jain 51 56000 2 2012-05-18 2 2000

2 Arohi Dixit 21 25000 2 2012-05-18 2 2000

3 Vineet Garg 24 31000 2 2012-05-18 2 2000

1 Aryan Jain 51 56000 3 2012-06-28 3 4000

2 Arohi Dixit 21 25000 3 2012-06-28 3 4000


3 Vineet Garg 24 31000 3 2012-06-28 3 4000

Each row from the customers' table is combined with each row of the orders table. Since there are three records in
the loan table and three records in the orders table, after performing the cross join operation, we will get 9 rows.

Regular expression
o Regular expression is a sequence of pattern that defines a string. It is used to denote regular languages.
o It is also used to match character combinations in strings. String searching algorithm used this pattern to find the
operations on string.
o In regular expression, x* means zero or more occurrence of x. It can generate {e, x, xx, xxx, xxxx,.....}
o In regular expression, x+ means one or more occurrence of x. It can generate {x, xx, xxx, xxxx,.....}

Operations on Regular Language


The various operations on regular language are:

Union: If L and M are two regular languages then their union L U M is also a union.

1. L U M = {s | s is in L or s is in M}  

Intersection: If L and M are two regular languages then their intersection is also an intersection.

1. L ⋂ M = {st | s is in L and t is in M}  

Kleene closure: If L is a regular language then its kleene closure L1* will also be a regular language.

HTML Tutorial

1. L* = Zero or more occurrence of language L.  

Example
Write the regular expression for the language:

L = {abn w:n ≥ 3, w ∈ (a,b)+}

Solution:
The string of language L starts with "a" followed by atleast three b's. Itcontains atleast one "a" or one "b" that is
string are like abbba, abbbbbba, abbbbbbbb, abbbb.....a
So regular expression is:

r= ab3b* (a+b)+

Here + is a positive closure i.e. (a+b)+ = (a+b)* - ∈

Relational Algebra
Relational algebra is a procedural query language. It gives a step by step process to obtain the result of the query.
It uses operators to perform queries.

Types of Relational operation

1. Select Operation:

o The select operation selects tuples that satisfy a given predicate.


o It is denoted by sigma (σ).

1. Notation:  σ p(r)  

Where:

σ is used for selection prediction


r is used for relation
p is used as a propositional logic formula which may use connectors like: AND OR and NOT. These relational can
use as relational operators like =, ≠, ≥, <, >, ≤.

For example: LOAN Relation


Hello Java Program for Beginners

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:

1. σ BRANCH_NAME="perryride" (LOAN)  

Output:

BRANCH_NAME LOAN_NO AMOUNT

Perryride L-15 1500

Perryride L-16 1300

2. Project Operation:

o This operation shows the list of those attributes that we wish to appear in the result. Rest of the attributes are
eliminated from the table.
o It is denoted by ∏.

1. Notation: ∏ A1, A2, An (r)   
Where

A1, A2, A3 is used as an attribute name of relation r.

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:

1. ∏ NAME, CITY (CUSTOMER)  

Output:

NAME CITY

Jones Harrison

Smith Rye

Hays Harrison

Curry Rye

Johnson Brooklyn
Brooks Brooklyn

3. Union Operation:

o Suppose there are two tuples R and S. The union operation contains all the tuples that are either in R or S or both in
R & S.
o It eliminates the duplicate tuples. It is denoted by ∪.

1. Notation: R ∪ S   

A union operation must hold the following condition:

o R and S must have the attribute of the same number.


o Duplicate tuples are eliminated automatically.

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:

1. ∏ CUSTOMER_NAME (BORROW) ∪ ∏ CUSTOMER_NAME (DEPOSITOR)  

Output:

CUSTOMER_NAME

Johnson

Smith

Hayes

Turner

Jones

Lindsay

Jackson
Curry

Williams

Mayes

4. Set Intersection:

o Suppose there are two tuples R and S. The set intersection operation contains all tuples that are in both R & S.
o It is denoted by intersection ∩.

1. Notation: R ∩ S   

Example: Using the above DEPOSITOR table and BORROW table

Input:

1. ∏ CUSTOMER_NAME (BORROW) ∩ ∏ CUSTOMER_NAME (DEPOSITOR)  

Output:

CUSTOMER_NAME

Smith

Jones

5. Set Difference:

o Suppose there are two tuples R and S. The set intersection operation contains all tuples that are in R but not in S.
o It is denoted by intersection minus (-).

1. Notation: R - S  

Example: Using the above DEPOSITOR table and BORROW table

Input:

1. ∏ CUSTOMER_NAME (BORROW) - ∏ CUSTOMER_NAME (DEPOSITOR)  
Output:

CUSTOMER_NAME

Jackson

Hayes

Willians

Curry

6. Cartesian product

o The Cartesian product is used to combine each row in one table with each row in the other table. It is also known as
a cross product.
o It is denoted by X.

1. Notation: E X D  

Example:
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:

1. 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

7. Rename Operation:
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.
1. ρ(STUDENT1, STUDENT)  
Note: Apart from these common operations Relational algebra can be used in Join operations.

Next →← Prev

SQL Set Operation


The SQL Set operation is used to combine the two or more SQL SELECT statements.

Types of Set Operation

1. Union
2. UnionAll
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 both the tables on which UNION
operation is being applied.
o The union operation eliminates the duplicate rows from its resultset.

Syntax

1. SELECT column_name FROM table1  
2. UNION  
3. SELECT column_name FROM table2;  

Example:

The First table

How to find Nth Highest Salary in SQL

ID NAME

1 Jack

2 Harry

3 Jackson

The Second table


ID NAME

3 Jackson

4 Stephan

5 David

Union SQL query will be:

1. SELECT * FROM First   
2. UNION  
3. 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 removing duplication and sorting
the data.

Syntax:

1. SELECT column_name FROM table1  
2. UNION ALL  
3. SELECT column_name FROM table2;  
Example: Using the above First and Second table.

Union All query will be like:

1. SELECT * FROM First   
2. UNION ALL  
3. 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 the common rows from both the
SELECT statements.
o In the Intersect operation, the number of datatype and columns must be the same.
o It has no duplicates and it arranges the data in ascending order by default.

Syntax

1. SELECT column_name FROM table1  
2. INTERSECT  
3. SELECT column_name FROM table2;  

Example:
Using the above First and Second table.

Intersect query will be:

1. SELECT * FROM First   
2. INTERSECT  
3. SELECT * FROM Second;  

The resultset table will look like:

ID NAME

3 Jackson

4. Minus

o It combines the result of two SELECT statements. Minus operator is used to display the 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:

1. SELECT column_name FROM table1  
2. MINUS  
3. SELECT column_name FROM table2;  

Example

Using the above First and Second table.

Minus query will be:

1. SELECT * FROM First   
2. MINUS  
3. SELECT * FROM Second;  

The resultset table will look like:

ID NAME
1 Jack

2 Harry

You might also like