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

SQL Advance

The document provides examples of defining SQL functions and procedures. It discusses defining functions using SQL to return a single value or a table. It also shows how to define a procedure using SQL. Functions and procedures allow storing reusable logic in the database to be invoked from SQL statements. This avoids duplicating code and provides a single point of change if business rules change.

Uploaded by

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

SQL Advance

The document provides examples of defining SQL functions and procedures. It discusses defining functions using SQL to return a single value or a table. It also shows how to define a procedure using SQL. Functions and procedures allow storing reusable logic in the database to be invoked from SQL statements. This avoids duplicating code and provides a single point of change if business rules change.

Uploaded by

Shruti Shinde
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Write the following inserts, deletes or updates in SQL, using the university

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

Fig. Schema for University Database


VJTI, Mumbai
Increase the salary of each instructor in the Comp. Sci. department by 10%.
4
update instructor
set salary = salary * 1.10
where dept name = ’Comp. Sci.’

VJTI, Mumbai
5 Delete all courses that have never been offered (that is, do not occur in the section
relation).

delete from course


where course id not in
(select course id from section)

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.

Insert into instructor


(select ID, name, dept name, 10000
from student
where tot cred > 100)

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.

c. Find the ID and the grade-point average of every student.

VJTI, Mumbai
8

Fig. Schema for University Database


VJTI, Mumbai
a. select sum(credits * points)
9 from (course natural join takes) natural join grade points
Where ID = ’12345’

b. select sum(credits * points)/sum(credits) as GPA


from (takes natural join course) natural join grade points
where ID = ’12345’

c. select ID, sum(credits * points)/sum(credits) as GPA


from (takes natural join course) natural join grade points
group by ID

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

WHEN website_id = 1 THEN ‘google.com'


WHEN website_id = 2 THEN ‘facebook.com'
ELSE 'BigActivities.com'

END
FROM contacts;

VJTI, Mumbai
1 With Clause
2

🠶 allows you to give a sub-query block a name


🠶 a process also called sub-query refactoring which can be referenced in several
places
within the main SQL query.

WITH <alias_name> AS (sql_subquery_statement)

SELECT column_list FROM <alias_name>


[WHERE <join_condition>]

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

when score < 40 then ’F’


when score < 60 then ’C’
when score < 80 then ’B’
else ’A’

end
from marks

VJTI, Mumbai
Find the number of students with each grade.
1
5 select grade, count(ID)

from {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}
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

🠶 SQL allows the definition of functions, procedures, and


methods.
1. These can be defined either by the procedural component of SQL,
2. or by an external programming language such as Java, C, or C++.

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;

select count(*) into d_count


from instructor
where instructor.dept_name= dept_name
return d_count;
end
VJTI, Mumbai
🠶 This function can be used in a query that returns names and budgets of all departments with more than 12
instructors:
select dept name, budget
21
from instructor
where dept_count(dept_name) > 12;
Table Functions in SQL-------------------------------
🠶 The SQL standard supports functions that can return tables as results; such functions are called table
functions.
create function instructors_of (dept_name varchar(20))
returns table (
ID varchar (5),
name varchar (20),
Dept_name varchar (20),
salary numeric (8,2))

return table
(select ID, name, dept_name, salary
from instructor
where instructor.dept name = instructors_of.dept name);
VJTI, Mumbai
22

🠶 The function can be used in a query as follows:


select *
from table(instructor_of (’Finance’));
🠶 This query returns all instructors of the ’Finance’ department.
🠶 In the above simple case it is straightforward to write this query without using
table-valued functions.
🠶 In general, however, table-valued functions can be thought of a parameterized views that
generalize the regular notion of views by allowing parameters.

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

select count(*) into d_count


from instructor
where instructor.dept name= dept_count_proc.dept name
end
🠶 The keywords in and out indicate, respectively, parameters that are expected to have values assigned to
them and parameters whose values are set in the procedure in order to return results.
🠶 Procedures
either fromcan
an be
embedded
invokedSQL or from a dynamic SQL by the call statement:
declare d_count integer;
call dept_count_proc(’Physics’, d_count);

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

🠶 Triggers can be written for the following purposes



1. Enforcing referential integrity
2. Event logging and storing information on table access
3. Auditing
4. Synchronous replication of tables
5. Imposing security authorizations
6. Preventing invalid transactions
VJTI, Mumbai
Syntax of
29 Trigger
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE

Declaration-statements
BEGIN
Executable-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)

create trigger timeslot_check1 after insert on section


referencing new row as nrow
for each row
when (nrow.time_slot_id not in (
select time_slot_id
from time_slot)) /* time_slot_id not present in time_slot */
begin
rollback
end;

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

🠶 Both are used to keep database consistence.


🠶 But triggers optimize the execution of queries.
🠶 A constraint also prevents the data from being made inconsistent by any kind of statement,
whereas a trigger is activated by a specific kind of statement (e.g., an insert or delete
statement).
🠶 Along with applying constraints triggers allow us to specify the actions.

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

You might also like