Professional Documents
Culture Documents
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.
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.
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.
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.
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.
o CREATE
o ALTER
o DROP
o TRUNCATE
Syntax:
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:
1. ALTER TABLE table_name ADD column_name COLUMN-definition;
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;
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'
Syntax:
1. DELETE FROM table_name [WHERE condition];
For example:
1. DELETE FROM javatpoint
2. WHERE Author="Sonoo";
o Grant
o Revoke
Example
1. GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;
Example
1. REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;
These operations are automatically committed in the database that's why they cannot be used while creating
tables or dropping them.
o COMMIT
o ROLLBACK
o SAVEPOINT
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;
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.
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.
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.
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));
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.
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;
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.
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 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
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. /
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
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
Customers
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.
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.
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.
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.
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
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:
* * * * * *
* * * * *
* * * *
* * *
* *
*
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
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
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
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.
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. }
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++;
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
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:
In the above code, we need to enter Ctrl + C command to terminate the infinite 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);
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.
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
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:
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.
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.
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
Output:
20
10
10.0
Output:
10.5
10
Output:
130
-126
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
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.
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;
1. CURSOR cursor_name IS select_statement;;
Steps:
You must follow these steps while working with an explicit cursor.
1. CURSOR name IS
2. SELECT statement;
1. OPEN cursor_name;
1. FETCH cursor_name INTO variable_list;
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 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 could be defined on the table, view, schema, or database with which the event is associated.
Advantages of Triggers
These are the following advantages of Triggers:
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 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.
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:
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.
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.
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.
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.
EMPLOYEE table:
14 John 7272826385, UP
9064738238
The decomposition of the EMPLOYEE table into 1NF has been shown below:
14 John 7272826385 UP
14 John 9064738238 UP
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
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
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:
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:
EMPLOYEE_ZIP table:
201010 UP Noida
02228 US Boston
60007 US Chicago
06389 UK Norwich
462007 MP Bhopal
Example: Let's assume there is a company where employees work in more than one department.
EMPLOYEE table:
1. EMP_ID → EMP_COUNTRY
2. EMP_DEPT → {DEPT_TYPE, EMP_DEPT_NO}
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_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:
Now, this is in BCNF because left side part of both the functional dependencies is a key.
Example
STUDENT
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.
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
Example
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
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);
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.
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.
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.
T1 T2
Read(A) Read(B)
A:= A-100 Y:= Y+100
Write(A) Write(B)
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 facilitates programmers to catch such conditions using exception block in the program and an appropriate
action is taken against the error condition.
o System-defined Exceptions
o User-defined Exceptions
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;
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.
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;
1. DECLARE
2. my-exception EXCEPTION;
For example: NO_DATA_FOUND is a pre-defined exception which is raised when a SELECT INTO statement
returns no rows.
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.
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.
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.
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.
1.Staff table
2.Payment table
1. SELECT Staff_ID, Staff_NAME, Staff_AGE, AMOUNT
2. FROM STAFF s, PAYMENT p
3. WHERE s.ID =p.STAFF_ID;
3 MONTY 25 2500
1 ARYAN 22 3000
4 AMIT 25 3500
1 ARYAN 22 3000
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.
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.
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:
1 ARYAN 51 56000
2 AROHI 21 25000
3 VINEET 24 31000
4 AJEET 23 32000
5 RAVI 23 42000
ORDER TABLE:
1. SQL SELECT ID, NAME, AMOUNT,DATE
2. FROM CUSTOMER
3. LEFT JOIN ORDER
4. ON CUSTOMER.ID = ORDER.CUSTOMER_ID;
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:
1 ARYAN 51 56000
2 AROHI 21 25000
3 VINEET 24 31000
4 AJEET 23 32000
5 RAVI 23 42000
ORDER TABLE:
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;
SQL full outer join and SQL join are same. generally it is known as SQL FULL 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
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.
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.
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.
Table 1: MatchScore
Franklin 1 2
Alan 1 3
Priyanka 2 2
Rajesh 3 5
Table 2: Departments
26.1M
446
Department_id Department_name
1 IT
2 HR
3 Marketing
Table 3: employee
Table 4: department
1 Production 1
2 Sales 3
3 Marketing 4
4 Accounts 5
Table 5: loan
2 B2 10000
3 B3 20000
4 B4 100000
Table 6: borrower
1 Sonakshi Dixit 1
2 Shital Garg 4
3 Swara Joshi 5
4 Isha Deshmukh 2
Table 7: customer
Table 8: orders
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:
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:
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:
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:
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,.....}
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)+
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.
1. Select Operation:
1. Notation: σ p(r)
Where:
Input:
1. σ BRANCH_NAME="perryride" (LOAN)
Output:
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
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
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
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
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
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:
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
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:
ID NAME
1 Jack
2 Harry
3 Jackson
3 Jackson
4 Stephan
5 David
1. SELECT * FROM First
2. UNION
3. SELECT * FROM Second;
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.
1. SELECT * FROM First
2. UNION ALL
3. SELECT * FROM Second;
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.
1. SELECT * FROM First
2. INTERSECT
3. SELECT * FROM Second;
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
1. SELECT * FROM First
2. MINUS
3. SELECT * FROM Second;
ID NAME
1 Jack
2 Harry