DBMS Unit - 2 Notes
DBMS Unit - 2 Notes
Relational Algebra is procedural query language, which takes Relation as input andgenerates relation as
output. Relational algebra mainly provides theoretical foundation for relational databases and SQL.
Relational algebra is a procedural query language, it means that it tells what data to beretrieved and how to be
retrieved.
Relational Algebra works on the whole table at once, so we do not have to use loopsetc to iterate over all the
rows (tuples) of data one by one.
All we have to do is specify the table name from which we need the data, and in a single line of command,
relational algebra will traverse the entire given table to fetchdata for you.
Basic/Fundamental Operations:
1. Select (σ)
2. Project (∏)
3. Union (𝖴)
4. Set Difference (-)
5. Cartesian product (X)
6. Rename (ρ)
Select Operation (σ) :This is used to fetch rows (tuples) from table(relation) which satisfies a given condition.
Syntax: σp(r)
σ is the predicate
r stands for relation which is the name of the table
p is prepositional logic ex: σage > 17 (Student)
This will fetch the tuples(rows) from table Student, for which age will be greater than 17. σage > 17 and gender
= 'Male' (Student)
This will return tuples(rows) from table Student with information of male students, of age more than 17.
Input:
σ BRANCH_NAME="perryride" (LOAN)
Output:
Input:
∏ NAME, CITY (CUSTOMER)
Output:
NAME CITY
Jones Harrison
Smith Rye
Hays Harrison
Curry Rye
Johnson Brooklyn
Brooks Brooklyn
This operation is used to fetch data from two relations(tables) or temporaryrelation(result of another
operation).For this operation to work, the relations(tables) specified should have same number of
attributes(columns) and same attribute domain. Also the duplicate tuples are autamatically eliminated
from the result.
Syntax: A 𝖴 B
∏Student(RegularClass) 𝖴 ∏Student(ExtraClass)
Example:
DEPOSITOR RELATION
CUSTOMER_NAME ACCOUNT_NO
Johnson A-101
Smith A-121
Mayes A-321
Turner A-176
Johnson A-273
Jones A-472
Lindsay A-284
BORROW RELATION
CUSTOMER_NAME LOAN_NO
Jones L-17
Smith L-23
Hayes L-15
Jackson L-14
Curry L-93
Smith L-11
Williams L-17
Input:
∏ CUSTOMER_NAME (BORROW) 𝖴 ∏ CUSTOMER_NAME (DEPOSITOR)
Output:
CUSTOMER_NAME
Johnson
Smith
Hayes
Turner
Jones
Lindsay
Jackson
Curry
Williams
Mayes
Set Difference (-):
This operation is used to find data present in one relation and not present in the secondrelation. This
operation is also applicable on two relations, just like Union operation.
Syntax: A - B
where A and B are relations.
For example, if we want to find name of students who attend the regular class but not theextra class,
then, we can use the below operation:
∏Student(RegularClass) - ∏Student(ExtraClass)
CUSTOMER_NAME
Smith
Jones
EMPLOYEE
EMP_ID EMP_NAME EMP_DEPT
1 Smith A
2 Harry C
3 John B
DEPARTMENT
DEPT_NO DEPT_NAME
A Marketing
B Sales
C Legal
Input:
EMPLOYEE X DEPARTMENT
Output:
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
The rename operation is used to rename the output relation. It is denoted by rho (ρ).
Example: We can use the rename operator to rename STUDENT relation to STUDENT1.
ρ(STUDENT1, STUDENT)
Join in DBMS:
A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.
Join in DBMS is a binary operation which allows you to combine join product andselection in
one single statement.
The goal of creating a join condition is that it helps you to combine the data from twoor more
DBMS tables.
The tables in DBMS are associated using the primary key and foreign keys.
2. LEFT JOIN
3. RIGHT JOIN
4. FULL JOIN
Table name: EMPLOYEE
PROJECT
PROJECT_NO EMP_ID DEPARTMENT
101 1 Testing
102 2 Development
103 3 Designing
104 4 Development
1. INNER JOIN
In SQL, INNER JOIN selects records that have matching values in both tables as long as thecondition is
satisfied.
It returns the combination of all rows from both the tables where the condition satisfies.
Syntax
SELECT table1.column1, table1.column2 FROM table1 INNER JOIN table2
ON table1.matching_column = table2.matching_column;
Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT FROM EMPLOYEE INNER JOIN
PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
2. LEFT JOIN
The SQL left join returns all the values from left table and the matching values from the righttable. If
there is no matching join value, it will return NULL.
Syntax
SELECT table1.column1, table1.column2 FROM table1LEFT JOIN table2
ON table1.matching_column = table2.matching_column;
Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT FROM EMPLOYEE LEFT JOIN
PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Marry NULL
3.RIGHT JOIN
In SQL, RIGHT JOIN returns all the values from the values from the rows of right table and the matched values
from the left table. If there is no matching in both tables, it will return NULL.
Syntax
SELECT table1.column1, table1.column2 FROM table1 RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;
Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT FROM EMPLOYEE RIGHT JOIN
PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
.
4. FULL JOIN
In SQL, FULL JOIN is the result of a combination of both left and right outer join. Join tables have
all the records from both tables. It puts NULL on the place of matches not found.
Syntax
SELECT table1.column1, table1.column2 FROM table1 FULL JOIN table2
ON table1.matching_column = table2.matching_column;
Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT FROM EMPLOYEE
FULL JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Marry NULL
Division Operator in SQL
Division Operator (÷): Division operator A÷B can be applied if and only if:
Attributes of B is proper subset of Attributes of A.
The relation returned by division operator will have attributes = (All attributes of A –All
Attributes of B)
The relation returned by division operator will return those tuples from relation Awhich are
associated to every B’s tuple.
The division operator is used when we have to evaluate queries which contain thekeyword ALL.
Table 1: Course_Taken → It consists of the names of Students against the courses that they have
taken.
Student_Name Course
Robert Databases
David Databases
Course
Databases
Programming Languages
Find all the students. Create a set of all students that have taken courses. This can be done easily using the
following command.
CREATE TABLE AllStudents AS SELECT DISTINCT Student_Name FROM Course_Taken
This command will return the table AllStudents, as the resultset:
Student_name
Robert
David
Hannah
Tom
Find all the students and the courses required to graduate
Next, we will create a set of students and the courses they need to graduate. We can express this in the
form of Cartesian Product of AllStudents and Course_Required using the following command.
CREATE table StudentsAndRequired AS
SELECT AllStudents.Student_Name, Course_Required.CourseFROM AllStudents,
Course_Required
Now, the new resultset - table Students And Required will be:
Student_Name Course
Robert Databases
David Databases
Hannah Databases
Tom Databases
Ajeet Singh 30
Chaitanya Singh 31
Rajeev Bhatia 27
Carl Pratap 28
Lets write relational calculus queries.
Query to display the last name of those students where age is greater than 30
{ t.Last_Name | Student(t) AND t.age > 30 }
In the above query you can see two parts separated by | symbol. The second part is where wedefine the
condition and in the first part we specify the fields which we want to display for the selected tuples.
The result of the above query would be:
Last_Name
Singh
Ajeet Singh 30
Chaitanya Singh 31
Ex:
Table-1: Customer
Customer name Street City
Saurabh A7 Patiala
Mehak B6 Jalandhar
Sumiti D9 Ludhiana
Ria A5 Patiala
Table-2: Branch
Branch name Branch city
ABC Patiala
DEF Ludhiana
GHI Jalandhar
Table-3: Account
Account number Branch name Balance
1111 ABC 50000
1112 DEF 10000
1113 GHI 9000
1114 ABC 7000
Table-4: Loan
Loan number Branch name Amount
L33 ABC 10000
L35 DEF 15000
L49 GHI 9000
L98 DEF 65000
Table-5: Borrower
Customer name Loan number
Saurabh L33
Mehak L49
Ria L98
Table-6: Depositor
Customer name Account number
Saurabh 1111
Mehak 1113
Sumiti 1114
Queries-1: Find the loan number, branch, amount of loans of greater than or equal to 10000 amount.
Ajeet Singh 30
Chaitanya Singh 31
Rajeev Bhatia 27
Carl Pratap 28
Ajeet 30
Chaitanya 31
Carl 28
The data returned is stored in a result table, called the result-set. To fetch the entire table or all the fields in
the table:
SELECT * FROM table_name;To fetch individual column data
SELECT column1,column2 FROM table_name
Example
Consider the CUSTOMERS table having the following records −
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
The following code is an example which would fetch the ID, Name and Salary fields fromthe
CUSTOMERS table, where the salary is greater than 2000 −
SQL> SELECT ID, NAME, SALARY
FROM CUSTOMERS
WHERE SALARY > 2000;
From clause:
From clause can be used to specify a sub-query expression in SQL. The relation producedby the
sub-query is then used as a new relation on which the outer query is applied.
Sub queries in the from clause are supported by most of the SQL implementations.
The correlation variables from the relations in from clause cannot be used in the sub-queries
in the from clause.
Syntax:
SELECT column1, column2 FROM
(SELECT column_x as C1, column_y FROM table WHERE PREDICATE_X)as table2
WHERE PREDICATE;
SET Operations
SQL supports few Set operations which can be performed on the table data. These are used to get
meaningful results from data stored in the table, under different special conditions.
In this tutorial, we will cover 4 different types of SET operations, along with example:
1. UNION
2. UNION ALL
3. INTERSECT
4. MINUS
1. Union
o The SQL Union operation is used to combine the result of two or more SQL SELECT
queries.
o In the union operation, all the number of datatype and columns must be same in boththe
tables on which UNION operation is being applied.
The union operation eliminates the duplicate rows from its resultset
Syntax
SELECT column_name FROM table1 UNION
SELECT column_name FROM table2;
The First table
ID NAME
1 Jack
2 Harry
3 Jackson
ID NAME
3 Jackson
4 Stephan
5 David
Union SQL query will be:SELECT * FROM First UNION
SELECT * FROM Second;
The resultset table will look like:
ID NAME
1 Jack
2 Harry
3 Jackson
4 Stephan
5 David
2. Union All
Union All operation is equal to the Union operation. It returns the set without removingduplication
and sorting the data.
Syntax:
SELECT column_name FROM table1 UNION ALL
SELECT column_name FROM table2;
Example: Using the above First and Second table. Union All query will be like:
SELECT * FROM First UNION ALL
SELECT * FROM Second;
-ID NAME
1 Jack
2 Harry
3 Jackson
3 Jackson
4 Stephan
5 David
3. Intersect
o It is used to combine two SELECT statements. The Intersect operation returns thecommon
rows from both the SELECT statements.
o In the Intersect operation, the number of data type and columns must be the same.
o It has no duplicates and it arranges the data in ascending order by default.
Syntax
SELECT column_name FROM table1 INTERSECT
SELECT column_name FROM table2;
Example:
Using the above First and second table, Intersect query will be:
ID NAME
3 Jackson
4. Minus
o It combines the result of two SELECT statements. Minus operator is used to displaythe rows
which are present in the first query but absent in the second query.
o It has no duplicates and data arranged in ascending order by default.
Syntax:
SELECT column_name FROM table1 MINUS
SELECT column_name FROM table2;
Example:
Using the above First and Second table, Minus query will be:
SELECT * FROM FirstMINUS
SELECT * FROM Second;
ID NAME
1 Jack
2 Harry
Aggregate functions in SQL
o SQL aggregation function is used to perform the calculations on multiple rows of asingle
column of a table. It returns a single value.
o It is also used to summarize the data.
Aggregate Functions
1) Count()
2) Sum()
3) Avg()
4) Min()
5) Max()
1. COUNT FUNCTION
o COUNT function is used to Count the number of rows in a database table. It can workon
both numeric and non-numeric data types.
o COUNT function uses the COUNT(*) that returns the count of all the rows in a specified
table. COUNT(*) considers duplicate and Null.
Count(*): Returns total number of records
PRODUCT_MAST
Example: COUNT()
SELECT COUNT(*) FROM PRODUCT_MAST;
Output: 10
Output:7
Output:3
2. SUM Function
Sum function is used to calculate the sum of all selected columns. It works on numeric fields only.
Syntax:
SUM()
or
SUM( [ALL|DISTINCT] expression )
Example: SUM()
SELECT SUM(COST) FROM PRODUCT_MAST;
Output:670
3. AVG function
The AVG function is used to calculate the average value of the numeric type. AVG functionreturns
the average of all non-Null values.
Syntax
AVG()
Example:
SELECT AVG(COST) FROM PRODUCT_MAST;
Output:
67.00
4. MAX Function
MAX function is used to find the maximum value of a certain column. This function determines the
largest value of all selected values of a column.
Syntax: MAX()
Example:
SELECT MAX(RATE) FROM PRODUCT_MAST;
30
5. MIN Function
MIN function is used to find the minimum value of a certain column. This function determines the
smallest value of all selected values of a column.
Syntax:MIN() )
Output:10
GROUP BY Statement
The GROUP BY statement groups rows that have the same values into summary rows, like"find the
number of customers in each country".
The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN, SUM,
AVG) to group the result-set by one or more columns.
Syntax:
Example:
Group By single column: Group By single column means, to place all the rows with same
value of only that particular column in one group. Consider the query as shown below:
SELECT NAME, SUM(SALARY) FROM Employee
GROUP BY NAME;
The above query will produce the below output:
Group By multiple columns: Group by multiple column is say for example, GROUP BY
column1, column2. This means to place all the rows with same values of both the columns
column1 and column2 in one group. Consider the below query:
SELECT SUBJECT, YEAR, Count(*)
FROM Student
GROUP BY SUBJECT, YEAR;
HAVING Clause:
We know that WHERE clause is used to place conditions on columns but what if we wantto place
conditions on groups?
This is where HAVING clause comes into use. We can use HAVING clause to place conditions to
decide which group will be the part of final result-set. Also we can not usethe aggregate functions
like SUM(), COUNT() etc. with WHERE clause. So we have to use HAVING clause if we want
to use any of these functions in the conditions.
Syntax:
SELECT column1, function_name(column2) FROM table_name
WHERE condition
GROUP BY column1, column2HAVING condition
ORDER BY column1, column2;
function_name: Name of the function used for example, SUM() , AVG().
table_name: Name of the table.
condition: Condition used.
Example:
SELECT NAME, SUM(SALARY) FROM EmployeeGROUP BY NAME
HAVING SUM(SALARY)>3000;
Example:
Consider the CUSTOMERS table having the following records.
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
Following is an example, which would display a record for a similar age count that would be more
than or equal to 2.
SQL > SELECT ID, NAME, AGE, ADDRESS, SALARY
FROM CUSTOMERS
GROUP BY age
HAVING COUNT(age) >= 2;
In nested queries, a query is written inside a query. The result of inner query is used inexecution
of outer query. We will use STUDENT, COURSE,
STUDENT_COURSE tables for understanding nested queries.
STUDENT
S_ID S_NAME S_ADDRESS S_PHONE S_AGE
S1 RAM DELHI 9455123451 18
S2 RAMESH GURGAON 9652431543 18
S3 SUJIT ROHTAK 9156253131 20
S4 SURESH DELHI 9156768971 18
COURSE
C_ID C_NAME
C1 DSA
C2 Programming
C3 DBMS
STUDENT_COURSE
S_ID C_ID
S1 C1
S1 C3
S2 C1
S3 C2
S4 C2
S4 C3
Example
Consider the CUSTOMERS table having the following records −
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
Now, let us check the following subquery with a SELECT statement.
SQL> SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500);
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
Students
id name class_id GPA
1 Jack Black 3 3.45
2 Daniel White 1 3.15
3 Kathrine Star 1 3.85
4 Helen Bright 2 3.10
5 Steve May 2 2.40
Teachers
id name subject class_id monthly_salary
1 Elisabeth Grey History 3 2,500
2 Robert Sun Literature [NULL] 2,000
3 John Churchill English 1 2,350
4 Sara Parker Math 2 3,000
Classes
id grade teacher_id number_of_students
1 10 3 21
2 11 4 25
3 12 1 28
SELECT *
FROM students WHERE GPA > (
SELECT AVG(GPA)
FROM students);
RESULT:
id name class_id GPA
1 Jack Black 3 3.45
3 Kathrine Star 1 3.85
SELECT AVG(number_of_students) FROM classes
WHERE teacher_id IN ( SELECT id
FROM teachers
WHERE subject = 'English' OR subject = 'History');
Views in SQL
o Views in SQL are considered as a virtual table. A view also contains rows and columns.
o To create the view, we can select the fields from one or more tables present in thedatabase.
o A view can either have specific rows based on certain condition or all the rows of atable.
Student_Detail
STU_ID NAME ADDRESS
1 Stephan Delhi
2 Kathrin Noida
3 David Ghaziabad
4 Alina Gurugram
Student_Marks
STU_ID NAME MARKS AGE
1 Stephan 97 19
2 Kathrin 86 21
3 David 74 18
4 Alina 90 20
5 John 96 18
1. Creating view
A view can be created using the CREATE VIEW statement. We can create a view from a single
table or multiple tables.
Syntax:
CREATE VIEW view_name ASSELECT column1, column2.....
FROM table_nameWHERE condition;
Just like table query, we can query the view to view the data. SELECT * FROM DetailsView;
Output:
NAME ADDRESS
Stephan Delhi
Kathrin Noida
David Ghaziabad
4. Deleting View
A view can be deleted using the Drop View statement.
Syntax:
DROP VIEW view_name;
Example:
If we want to delete the View MarksView, we can do this as:
DROP VIEW MarksView;
Uses of a View :
A good database should contain views due to the given reasons:
1. Restricting data access –
Views provide an additional level of table security by restricting access to apredetermined set
of rows and columns of a table.
2. Hiding data complexity –
A view can hide the complexity that exists in a multiple table join.
3. Simplify commands for the user –
Views allows the user to select information from multiple tables without requiring theusers to
actually know how to perform a join.
4. Store complex queries –
Views can be used to store complex queries.
5. Rename Columns –
Views can also be used to rename the columns without affecting the base tables provided the
number of columns in view must match the number of columns specified in select statement.
Thus, renaming helps to to hide the names of the columns of the base tables.
6. Multiple view facility –
Different views can be created on the same table for different users.
Advantages of Triggers:
Here,
o CREATE [OR REPLACE] TRIGGER trigger_name: It creates or replaces an existingtrigger
with the trigger_name.
o {BEFORE | AFTER | INSTEAD OF} : This specifies when the trigger would beexecuted.
The INSTEAD OF clause is used for creating trigger on a view.
o {INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML operation.
o [OF col_name]: This specifies the column name that would be updated.
o [ON table_name]: This specifies the name of the table associated with the trigger.
o [REFERENCING OLD AS o NEW AS n]: This allows you to refer new and old values for
various DML statements, like INSERT, UPDATE, and DELETE.
o [FOR EACH ROW]: This specifies a row level trigger, i.e., the trigger would be executed for
each row being affected. Otherwise the trigger will execute just once when the SQL statement
is executed, which is called a table level trigger.
o WHEN (condition): This provides a condition for rows for which the trigger would fire. This
clause is valid only for row level triggers.
Create trigger:
Let's take a program to create a row level trigger for the CUSTOMERS table that would fire for
INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. Thistrigger
will display the salary difference between the old values and new values:
CREATE OR REPLACE TRIGGER display_salary_changes BEFORE DELETE OR INSERT
OR UPDATE ON customersFOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary; dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);dbms_output.put_line('Salary difference: ' ||
sal_diff);
END;
After the execution of the above code at SQL Prompt, it produces the following result.
Trigger created.
Check the salary difference by procedure:
Use the following code to get the old salary, new salary and salary difference after the trigger
created.
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 5000;
IF sql%notfound THEN
dbms_output.put_line('no customers updated');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers updated ');
END IF;
END;
Old salary: 20000
New salary: 25000
Salary difference: 5000
Old salary: 22000
New salary: 27000
Salary difference: 5000
Old salary: 24000
New salary: 29000
Salary difference: 5000
Old salary: 26000
New salary: 31000
Salary difference: 5000
Old salary: 28000
New salary: 33000
Salary difference: 5000
Output:
Note: As many times you executed this code, the old and new both salary is incremented by5000
and hence the salary difference is always 5000.
After the execution of above code again, you will get the following result.
Old salary: 25000
New salary: 30000
Salary difference: 5000
Old salary: 27000
New salary: 32000
Salary difference: 5000
Old salary: 29000
New salary: 34000
Salary difference: 5000
Old salary: 31000
New salary: 36000
Salary difference: 5000
Old salary: 33000
New salary: 38000
Salary difference: 5000
Old salary: 35000
New salary: 40000
Salary difference: 5000
6 customers updated
Important Points:
Following are the two very important points and should be noted carefully.
o OLD and NEW references are used for record level triggers these are not available fortable level triggers.
o If you want to query the table in the same trigger, then you should use the AFTER keyword, because
triggers can query the table or change it again only after the initialchanges are applied and the table is back
in a consistent state.
Procedure
The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs oneor more specific
tasks. It is just like procedures in other programming languages.
The procedure contains a header and a body.
o Header: The header contains the name of the procedure and the parameters or variables passed to the
procedure.
o Body: The body contains a declaration section, execution section and exception section similar to a
general PL/SQL block.
In this example, we are going to insert record in user table. So you need to create user table first.
Table creation:
create table user(id number(10) primary key,name varchar2(100)); Now write theprocedure code
to insert record in user table.
Procedure Code:
create or replace procedure "INSERTUSER"(id IN NUMBER,
name IN VARCHAR2)
is begin
insert into user values(id,name);end;
/
Output:
Procedure created.
PL/SQL program to call procedure
Let's see the code to call above created procedure.
BEGIN
insertuser(101,'Rahul'); dbms_output.put_line('record inserted successfully');
END;
Now, see the "USER" table, you will see one record is inserted.
ID Name
101 Rahul
PL/SQL Drop Procedure
Syntax for drop procedure
DROP PROCEDURE procedure name;
Example of drop procedure
DROP PROCEDURE pro1;
DDL Triggers
As The Name suggests, DDL Triggers are related to DDL commands. DDL triggers respond
to DDL events like CREATE, ALTER, DROP, GRANT, DENY, REVOKE, or UPDATE
STATISTICS. For example, you can define a DDL trigger that records CREATE or ALTER
TABLE operations.
We can create these triggers at the database level or server level, depending on the type of
DDL events. It can also be executed in response to certain system-defined stored procedures
that do DDL-like operations.
DML Trigger
DML triggers are fired in response to DML events like INSERT, UPDATE, and DELETE
statements in the user’s table or view. It can also be executed in response to DML-like operations
performed by system-defined stored procedures.
Logon Trigger
Logon triggers are fired in response to a LOGON event. The LOGON event occurs when a user
session is generated with an SQL Server instance, which is made after the authentication process
of logging is completed but before establishing a user session. As a result, the SQL Server error
log will display all messages created by the trigger, including error messages and the PRINT
statement messages. If authentication fails, logon triggers do not execute. These triggers may
be used to audit and control server sessions, such as tracking login activity or limiting the
number of sessions for a particular login.
ADVANTAGES OF TRIGGERS
• Triggers set database object rules and roll back if any change does not satisfy those rules.
The trigger will inspect the data and make changes if necessary.
• Triggers help us to enforce data integrity.
• Triggers help us to validate data before inserted or updated.
• Triggers help us to keep a log of records.
• Triggers increase SQL queries' performance because they do not need to compile each time
they are executed.
• Triggers reduce the client-side code that saves time and effort.
• Triggers are easy to maintain.
DISADVANTAGES OF TRIGGERS
•Triggers are invoked automatically, and their execution is invisible to the user. Therefore, it
isn't easy to troubleshoot what happens in the database layer.
• Triggers may increase the overhead of the database server.
• We can define the same trigger action for multiple user actions such as INSERT and
UPDATE in the same CREATE TRIGGER statement.
• We can create a trigger in the current database only, but it can reference objects outside the
current database.
The SQL Operators which compare the values of two columns in the database tables are called
as comparison operators.
In SQL, comparison operators are always used in the WHERE clause with the SELECT,
UPDATE, and DELETE statements.
The comparison operators in SQL are categorized into the following six operators
category:
1. SQL Equal Operator (=)
2. SQL Not Equal Operator (!=)
3. SQL Greater Than Operator (>)
4. SQL Greater Than Equals to Operator (>=)
5. SQL Less Than Operator (<)
6. SQL Less Than Equals to Operator (<=)
Static or Embedded SQL are SQL statements in an application that do not change at runtime
and, therefore, can be hard-coded into the application.
Embedded SQL is a technique where SQL statements are precompiled into a program before
execution. The SQL statements are fixed at compile time, so the execution time is much faster
than Dynamic SQL. This approach is ideal when the query criteria are known in advance,
such as when generating daily reports, or performing batch processing of large amounts of
data.
The benefit of using this statement is that user know the path of execution of the
statements, so user can optimize the SQL query and then can execute the query in the
best and fastest possible way.
Dynamic SQL
Dynamic SQL is a programming technique that enables you to build SQL statements
dynamically at runtime.
Dynamic SQL is a technique used in database programming that allows SQL statements to be
constructed and executed at runtime. This approach offers more flexibility than Embedded SQL
because the SQL statement is constructed based on dynamic criteria that can change at runtime.
For example, if a user wants to search for products based on different criteria, Dynamic SQL
would be a suitable approach because the SQL statement can be constructed based on the user’s
inputs.
Since the dynamic SQL statement is constructed dynamically, it can pose a security risk if not
implemented properly. If an attacker is able to manipulate the input criteria, they can potentially
inject malicious SQL code and access or modify sensitive data in the database. Developers need
to take precautions such as validating inputs and using parameterized SQL statements to prevent
SQL injection attacks.
In Dynamic SQL, how a database will be accessed, can be determine only at run time.
Dynamic SQL statements are less efficient.
Dynamic SQL statements are compiled at run time.
In Dynamic SQL, Application Plan parsing, validation, optimization and generation are
run time activities.
Dynamic SQL is used in case of non-uniformly distributed data.
Dynamic SQL is highly flexible.
ODBC (Open Database Connectivity) and JDBC (Java Database Connectivity):-- These
both are Application Programming Interface (API) standards used for connecting applications
to databases and both ODBC & JDBC help the applications on the client side to access the
database on the server side.
Basically both are known as drivers to get connected with a database and are provided by the
vendors of RDBMS
ODBC is a framework made up of four components that function together. ODBC enables
programs to use SQL queries to connect to databases without knowing the databases' specific
interfaces. The SQL query is handled by ODBC, which turns it into a request that each database
system recognizes.
Application: The user sends its query to the database. Here the ODBC functions
are called, and SQL queries are sent.
Driver: It handles ODBC function calls before submitting each SQL request to a
data source.
Data Sources: The data source comprises the information that needs to be
accessed and the operating system, DBMS, and network platform used in
communication with the DBMS.
Features Of ODBC
Error code: It has an error code method for indicating problems encountered
while executing SQL statements.
Advantages of ODBC
Cross-Platform : ODBC works on multiple platforms like Linux, Windows.
Compatibility : ODBC provides compatibility with different data sources like
relational databases, files, etc.
Support for non-Java languages : ODBC supports Java and different languages
like C, C++, C#, Perl, etc.
Widely used : Since it is more flexible and compatible with other languages, that
make it such a widely used API.
Disadvantages of ODBC
Performance: ODBC is much slower than JDBC since it has an additional layer
for abstraction.
Complicated to construct: ODBC drivers are difficult to create and maintain.
Slow with Large databases: It can not handle large databases like JDBC.
However, it is easy to use.
Does not provide standardized: ODBC needs to be sufficiently standardized as
it is mainly used by clients, which is challenging to scale.
JDBC (Java Database Connectivity): JDBC is specifically designed for Java applications,
allowing them to interact easily with a wide variety of relational databases. JDBC defines an
API for JAVA programming environment that java programmers use to access relational
database and issue SQL statements.
It was introduced by Sun Microsystems in 1996.
JDBC stands for Java Database Connectivity and it is a part of JavaSE (Java Standard Edition).
It comprises a diverse set of classes, interfaces, and methods that allow a program to interact
with databases utilizing SQL queries. The JDBC API is composed of two layers. They are the
JDBC API Layer and JDBC Driver API Layer, respectively.
JDBC API Layer
It indicates which application uses the JDBC API to interact with the databases through JDBC
drivers. Java Application uses this JDBC driver to interact with and access the database.
JDBC is Object Oriented. It has advanced features like Update and Scrollable Result set. It is
platform-independent. They can work on any operating system like Linux or Mac.
Features of JDBC
The main unique feature of ODBC is:
It does not need to make connections again and again with databases. If you make a
connection again, it will be very costly and time-consuming, and some essential features
may be lost.
It can manipulate large databases like BLOB and CLOB.
It provides batch updates. It means it can send multiple updates in batches rather than
individually.
It gives about two types of result sets. One of them is Scrollable Result sets. It provides
an ability to move forward and backward from a specific position. Another one is the
Updatable Result set. It helps in the modification of databases.
It has a Save points interface. It saves a set of new savepoints and releases savepoints
when requested.
Advantages of JDBC
Pure Java: It is purely dedicated to Java. It can work on any platform which
supports Java Programming language.
Better performance : It performs better than ODBC in some cases. It can reuse
the used statements and support batch updates.
Object-oriented: Since it is Object Oriented, it enables it to work with Java
more easily.
Standardized : JDBC is a standard API that supports all major relational
databases.
Disadvantages of JDBC
Complexity: JDBC is more complex to use than ODBC. It needs to manage the
database manually.
Limited Functionality: Less functionality than other APIs like JPA or
Hibernate, which provide a higher level of abstraction.
Platform-specific Driver: It is platform-specific. It can work on any platform
which supports Java Programming language.
JDBC ODBC
Active Databases:
An active Database is a database consisting of a set of triggers. These databases are very difficult
to be maintained because of the complexity that arises in understanding the effect of these
triggers. In such a database, DBMS initially verifies whether the particular trigger specified in
the statement that modifies the database) is activated or not, prior to executing the statement.
An active databases contain an event- driven architecture that can respond to conditions inside
and outside the database. An active database can therefore monitor and react to specific
situations related to the application.
These databases are very difficult to be maintained because of the complexity that arises in
understanding the effect of these triggers. In such a database, DBMS initially verifies whether
the particular trigger specified in the statement that modifies the database) is activated or not,
prior to executing the statement.
If the trigger is active then DBMS executes the condition part and then executes the action part
only if the specified condition is evaluated to true. It is possible to activate more than one trigger
within a single statement.
In such a situation, DBMS processes each of the triggers randomly. The execution of an active
part of a trigger may either activate other triggers or the same trigger that Initialized this action.
Such types of triggers that activate themselves are called ‘recursive triggers’. The DBMS
executes such chains of triggers in some pre-defined manner but it affects the concept of
understanding.
A correlated subquery is evaluated once for each row processed by the parent statement. The
parent statement can be a SELECT, UPDATE, or DELETE statement.
Syntax:
SELECT column1, column2, ....
FROM table1 outer
WHERE column1 operator
(SELECT column1, column2
FROM table2
WHERE expr1 =
outer.expr2);
EXISTS Operator
This operator checks whether a subquery returns any row. If it returns at least one row. EXISTS
operator returns true, and the outer query continues to execute.
If the subquery returns no row, the EXISTS operator returns false, and the outer query stops
execution.
ANY Operator
This operator compares a value of the outer query's result with one or more values returned by
the inner query. If the comparison is true for any one of the values returned by the inner query,
the row is included in the final result.
ALL Operator
This operator compares a value of the outer query's result with all the values returned by the
inner query. Only if the comparison is true for all the values returned by the inner query, the
row is included in the final result.
Examples
Table: emp
e_id name
1 Arun
2 Ankita
3 Jenny
4 Shivani
5 Khush
Table: dept
dept_no name e_id
D1 IT 1
D2 HR 2
D3 R&D 3
select * from emp where exists (select e_id from dept where emp.e_id=dept.e_id);
Here we take first row from emp table and match with each row of dept table and whenever
the comparison become true, it should be added in the output.
Here, the inner query is starts again and again as the value is compared with each value of the
the outer query.
Output:
e_id Name
1 Arun
2 Ankita
3 Jenny