SQL Advance
SQL Advance
schema.
2
a. Increase the salary of each instructor in the Comp. Sci. department by
10%.
b. Delete all courses that have never been offered (that is, do not occur in the section relation).
c. Insert every student whose tot cred attribute is greater than 100 as an instructor in the same
department, with a salary of $10,000.
VJTI, Mumbai
3
VJTI, Mumbai
5 Delete all courses that have never been offered (that is, do not occur in the section
relation).
VJTI, Mumbai
6 Insert every student whose tot cred attribute is greater than 100 as an instructor in
the same department, with a salary of $10,000.
VJTI, Mumbai
🠶 Suppose you are given a relation grade_points(grade, points), which provides a conversion from
7 letter grades in the takes relation to numeric scores; for example an “A” grade could be specified to
correspond to 4 points, an “A−” to 3.7 points, a “B+” to 3.3 points, a “B” to 3 points, and so on. The
grade points earned by a student for a course offering (section) is defined as the number of credits
for the course multiplied by the numeric points for the grade that the student received.
🠶 Given the above relation, and our university schema, write each of the following queries in SQL.
You
can assume for simplicity that no takes tuple has the null value for grade.
a. Find the total grade-points earned by the student with ID 12345, across all courses taken by the
student.
b.Find the grade-point average (GPA) for the above student, that is, the total grade-points divided by the
total credits for the associated courses.
VJTI, Mumbai
8
VJTI, Mumbai
Case Expression & With
10
🠶
Clause
The simple CASE expression compares an expression to a set of simple expressions to
determine the result. Works as a If then else clause.
CASE
WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
...
WHEN condition_n THEN result_n
ELSE result
END
You can use CASE in statements such as SELECT, UPDATE, DELETE and SET, and in
clauses such as IN, WHERE, ORDER BY, and HAVING.
VJTI, Mumbai
SELECT contact_id,
1 CASE website_id
1 WHEN 1 THEN ‘google.com'
WHEN 2 THEN ‘facebook.com'
ELSE 'BigActivities.com'
END as website_name
FROM contacts;
SELECT contact_id,
CASE
END
FROM contacts;
VJTI, Mumbai
1 With Clause
2
VJTI, Mumbai
🠶Suppose that we have a relation marks(ID, score) and we wish to
1
3 assign grades to students based on the score as follows: grade F if
score < 40, grade C if 40 ≤ score < 60, grade B if 60 ≤ score <
80, and grade A if 80 ≤ score. Write SQL queries to do the
following:
a. Display the grade for each student, based on the marks relation.
b. Find the number of students with each grade.
VJTI, Mumbai
🠶 a. Display the grade for each student, based on the marks relation.
14
select ID,
case
end
from marks
VJTI, Mumbai
Find the number of students with each grade.
1
5 select grade, count(ID)
case
when score < 40 then ’F’
when score < 60 then ’C’
when score < 80 then ’B’
else ’A’
end as grade
from marks}
group by grade
VJTI, Mumbai
with grades as
(
1
6 select ID,
case
when score < 40 then ’F’
when score < 60 then ’C’
when score < 80 then ’B’
else ’A’
end as grade
from marks
)
select grade, count(ID)
from grades
group by grade
VJTI, Mumbai
17 SQL Functions and Procedures
🠶 Inbuilt functions available in SQL are:
LOWER, UPPER, LTRIM, RTRIM, SUBSTRING, LEN, CONCAT
🠶 developers can write their own functions and procedures, store them in the database, and then
invoke them from SQL statements.
🠶 Functions are particularly useful with specialized data types such as images and geometric
objects.
🠶 For e.g. an image data type may have associated functions to compare two images for
similarity.
🠶 Procedures and functions allow “business logic” to be stored in the database, and executed
from
SQL statements.
🠶 For example, universities usually have many rules about how many courses a student can take in
a given semester, the minimum number of courses a full-time instructor must teach in a year,
VJTI, Mumbai
18 Need of Stored Procedures in SQL
🠶 Instead of storing functions in prog language, define them as stored procedures in the
database.
🠶 It allows multiple applications to access the procedures, and it allows a single point of
change in case the business rules change, without changing other parts of the application.
🠶 Application code can then call the stored procedures, instead of directly updating database
relations.
VJTI, Mumbai
19 2 Ways of Defining Functions
VJTI, Mumbai
Defining Function Using SQL
20
🠶 Although parts of the syntax presented here may not be supported on such systems, the concepts
described are applicable across implementations, although with a different syntax.
🠶 Suppose that we want a function that, given the name of a department, returns the count of the number of
instructors in that department. We can define the function as:
create function dept_count (dept_name varchar(20))
returns integer
begin
declare d_count integer;
return table
(select ID, name, dept_name, salary
from instructor
where instructor.dept name = instructors_of.dept name);
VJTI, Mumbai
22
VJTI, Mumbai
Creating Procedures in SQL
23 🠶 SQL also supports procedures. The dept count function could instead be written as a procedure:
create procedure dept_count_proc(in dept_name varchar(20), out d_count integer)
begin
VJTI, Mumbai
24 Procedures/Functions with same name
Allowed
🠶 SQL permits more than one procedure of the same name, so long as the number of
arguments of the procedures with the same name is different.
🠶 The name, along with the number of arguments, is used to identify the procedure.
🠶 SQL also permits more than one function with the same name, so long as the different
functions with the same name either have different numbers of arguments, or for functions
with the same number of arguments, they differ in the type of at least one argument.
VJTI, Mumbai
25 Functions Stored Procedures
🠶 But Function is compiled and executed every 🠶 are pre-compile objects which are compiled for
time when it is called. first time and its compiled format is saved which
🠶 Function must return a value executes (compiled code) whenever it is called.
🠶 Functions can have only input parameters for 🠶 Stored Procedure it is optional( Procedure can
it return zero or n values).
🠶 Functions can be called from Procedure. 🠶 Procedures can have input/output parameters .
🠶 Try-catch block cannot be used in a 🠶 Procedures cannot be called from Function.
Function.
🠶 Exception can be handled by try-catch block in a
🠶 Function allows only SELECT statement in it. Procedure.
🠶 Syntax to call function on standalone SQL is: 🠶 Procedure allows SELECT as well as
Select Function_name(parameter) DML(INSERT/UPDATE/DELETE) statement
in it
🠶 Mostly used to perform calculations
🠶 Syntax to call procedure on standalone SQL is:
EXEC Stored_proc_name(parameter)
VJTI, Mumbai
🠶 Used to execute the process.
26 Triggers
🠶 A trigger is a statement that the system executes automatically as a side effect of a modification
to the database. To design a trigger mechanism, we must meet
🠶 Two requirements:
1.Specify when a trigger is to be executed. This is broken up into an event that causes the trigger to
be checked and a condition that must be satisfied for trigger execution to proceed.
2. Specify the actions to be taken when the trigger executes.
Once we enter a trigger into the database, the database system takes on the responsibility of
executing it whenever the specified event occurs and the corresponding condition is satisfied.
VJTI, Mumbai
27 Need of triggers
🠶 Triggers can be used to implement certain integrity constraints that cannot be specified
using the constraint mechanism of SQL.
🠶 Triggers are also useful mechanisms for alerting humans or for starting certain tasks
automatically when certain conditions are met.
🠶 For e.g. we could design a trigger that, whenever a tuple is inserted into the takes relation,
updates the tuple in the student relation for the student taking the course by adding the
number of credits for the course to the student’s total credits.
🠶 Note that trigger systems cannot usually perform updates outside the database,
VJTI, Mumbai
🠶 Triggers are, in fact, written to be executed in response to any of the following events −
28 🠶 A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
🠶 A database definition (DDL) statement (CREATE, ALTER, or DROP).
🠶 A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).
🠶 Triggers can be defined on the table, view, schema, or database with which the event is associated.
Benefits
of Triggers
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
VJTI, Mumbai
This trigger will display the salary difference
30
between the old values and new values
CREATE OR REPLACE TRIGGER display_salary_changes
AFTER INSERT ON customers
REFERENCING OLD as OLD, NEW as NEW
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
END;
🠶 When the above code is executed at the SQL prompt, it produces the following result
−
🠶 Trigger created.
VJTI, Mumbai
Example of Trigger: To ensure referential integrity on the time_slot_id
attribute of the section relation (Section has time_slot_id as a foreign
31
key)
VJTI, Mumbai
34 Considers the case of deletes
to time_slot.
create trigger timeslot check2 after delete on timeslot
referencing old row as orow
for each row
when ( orow.time_slot_id in (
select time_slot_id
from section)) /* and time_slot_id still referenced from section*/
begin
rollback
end;
VJTI, Mumbai
36 Triggers for Update Operation
🠶 For updates, the trigger can specify attributes whose update causes the trigger to
execute.
🠶 For example, to specify that a trigger executes after an update to the grade attribute of the
takes relation, we write:
after update of grade on takes table
🠶 The referencing old row as clause can be used to create a variable storing the old value of
an updated or deleted row.
🠶 The referencing new row as clause can be used with updates in addition to inserts.
VJTI, Mumbai
A trigger can be used to keep the tot cred attribute value of student tuples up-to-date when the grade attribute is
updated for a tuple in the takes relation.
37
The trigger is executed only when the grade attribute is updated from a value that is either null or ’F’, to a grade that
indicates the course is successfully completed.
The update statement is normal SQL syntax except for the use of the variable nrow.
VJTI, Mumbai
3
8
VJTI, Mumbai
39 Insertion of Null value for absence of value
🠶 suppose the value of an inserted grade is blank, presumably to indicate the absence of a
grade. We can define a trigger that replaces the value by the null value.
🠶 The set statement can be used to carry out such modifications.
VJTI, Mumbai
41 Disabling of
🠶
Trigger
Triggers can be disabled or enabled; by default they are enabled when they are created, but
can be disabled by using
1. alter trigger trigger_name disable;
2. disable trigger trigger_name;
3. drop trigger trigger_name;
VJTI, Mumbai
42 Difference between Constraints and triggers
VJTI, Mumbai
43 Applications of
Triggers
🠶 Many database systems support a variety of other triggering events, such as when a user
(application) logs on to the database (that is, opens connection), the system shuts down, or
changes are made to system settings.
🠶 Triggers can be activated before the event (insert, delete, or update) instead of after the
event.
🠶 Triggers that execute before an event can serve as extra constraints that can prevent
invalid updates, inserts, or deletes.
🠶 Instead of letting the invalid action proceed and cause an error, the trigger might take
action to correct the problem so that the update, insert, or delete becomes valid.
VJTI, Mumbai