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

UNIT 3

This document provides an overview of SQL commands, including Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Transaction Control Language (TCL), and Data Query Language (DQL). It explains key SQL commands and their syntax, such as CREATE, ALTER, INSERT, UPDATE, DELETE, and various constraints like NOT NULL, UNIQUE, and FOREIGN KEY. Additionally, it covers SQL joins, set operations, and subqueries, providing examples for better understanding.

Uploaded by

Seshasayee
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

UNIT 3

This document provides an overview of SQL commands, including Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Transaction Control Language (TCL), and Data Query Language (DQL). It explains key SQL commands and their syntax, such as CREATE, ALTER, INSERT, UPDATE, DELETE, and various constraints like NOT NULL, UNIQUE, and FOREIGN KEY. Additionally, it covers SQL joins, set operations, and subqueries, providing examples for better understanding.

Uploaded by

Seshasayee
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 151

UNIT 3

SRM Institute of Science and Technology 1


SQL commands, Views, Case Study: PL-SQL,

SRM Institute of Science and Technology 2


DDL COMMANDS
• 1. Data Definition Language (DDL)
• DDL changes the structure of the table like creating a table, deleting a table, altering a table,
etc.
• All the command of DDL are auto-committed that means it permanently save all the
changes in the database.
• Here are some commands that come under DDL:
• CREATE
• ALTER
• DROP
• TRUNCATE
• a. CREATE It is used to create a new table in the database.
• Syntax:
1. CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);
b. DROP: It is used to delete both the structure and record stored in the table.
Syntax
DROP TABLE table_name;
Example
DROP TABLE EMPLOYEE;

c. ALTER: It is used to alter the structure of the database. This change could be either to
modify the characteristics of an existing attribute or probably to add a new attribute.
Syntax:
To add a new column in the table
ALTER TABLE table_name ADD column_name COLUMN-definition;
To modify existing column in the table:
ALTER TABLE table_name MODIFY(column_definitions....);
EXAMPLE
ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));
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:
TRUNCATE TABLE table_name;
Example:
TRUNCATE TABLE EMPLOYEE;
DML COMMANDS
• 2. Data Manipulation Language
• DML commands are used to modify the database. It is
responsible for all form of changes in the database.
• The command of DML is not auto-committed that means
it can't permanently save all the changes in the database.
They can be rollback.
• Here are some commands that come under DML:
• INSERT
• UPDATE
• 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] [W
HERE CONDITION]
For example:
1.UPDATE students
2.SET User_Name = 'Sonoo'
3.WHERE Student_Id = '3'
c. DELETE: It is used to remove one or more row from a
table.
Syntax:
1.DELETE FROM table_name [WHERE condition];
For example:
1.DELETE FROM javatpoint
2.WHERE Author="Sonoo";
3. Data Control Language

DCL commands are used to grant and take


back authority from any database user.
Here are some commands that come under
DCL:
•Grant
•Revoke
• a. Grant: It is used to give user access privileges
to a database.
• Example
1.GRANT SELECT, UPDATE ON MY_TABLE TO SOME_
USER, ANOTHER_USER;
• b. Revoke: It is used to take back permissions
from the user.
• Example
1.REVOKE SELECT, UPDATE ON MY_TABLE FROM US
ER1, USER2;
4.Transaction Control Language

• TCL commands can only use with DML commands


like INSERT, DELETE and UPDATE only.
• These operations are automatically committed in
the database that's why they cannot be used while
creating tables or dropping them.
• Here are some commands that come under TCL:
•COMMIT
•ROLLBACK
•SAVEPOINT
a. Commit: Commit command is used to save all the transactions to the database.
• Syntax:
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:
ROLLBACK;
• Example:
1. DELETE FROM CUSTOMERS
2. WHERE AGE = 25;
3. ROLLBACK;
• c. SAVEPOINT: It is used to roll the transaction
back to a certain point without rolling back the
entire transaction.
Syntax:
1.SAVEPOINT SAVEPOINT_NAME;
5. Data Query Language
• DQL is used to fetch the data from the database.
• It uses only one command:
• 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;


PL-SQL CASE STUDY
• Let's create a PL/SQL case study with an example.
• In this case study, let's assume we are building a simple
library management system.
• We want to create a stored procedure that calculates the
late fee for books that are returned past their due date.
• Here's the scenario:

1.We have a table named book_loans with columns


book_id, due_date, and return_date.

2.We need to calculate the late fee for each book based on
the number of days it is overdue.

3.The late fee is $0.50 per day for each book.


Let's write a PL/SQL stored procedure for this case:
-- Create the table for book loans
CREATE TABLE book_loans (
book_id INT,
due_date DATE,
return_date DATE
);

-- Insert some sample data


INSERT INTO book_loans VALUES (1, TO_DATE('2024-01-20', 'YYYY-MM-DD'),
TO_DATE('2024-01-25', 'YYYY-MM-DD'));
INSERT INTO book_loans VALUES (2, TO_DATE('2024-01-15', 'YYYY-MM-DD'),
TO_DATE('2024-01-22', 'YYYY-MM-DD'));
INSERT INTO book_loans VALUES (3, TO_DATE('2024-01-10', 'YYYY-MM-DD'),
TO_DATE('2024-01-18', 'YYYY-MM-DD'));

-- Create a stored procedure to calculate late fees


CREATE OR REPLACE PROCEDURE calculate_late_fee AS
CURSOR book_cursor IS
SELECT book_id, due_date, return_date
FROM book_loans;

v_book_id book_loans.book_id%TYPE;
v_due_date book_loans.due_date%TYPE;
v_return_date book_loans.return_date%TYPE;
v_days_late NUMBER;
v_late_fee NUMBER := 0.50;
BEGIN
OPEN book_cursor;
LOOP
FETCH book_cursor INTO v_book_id, v_due_date, v_return_date;
EXIT WHEN book_cursor%NOTFOUND;
-- Calculate the number of days late
v_days_late := v_return_date - v_due_date;
-- If the book is returned late, calculate and display the late fee
IF v_days_late > 0 THEN
DBMS_OUTPUT.PUT_LINE('Book ID ' || v_book_id || ' is ' || v_days_late || '
days late.');
DBMS_OUTPUT.PUT_LINE('Late Fee: $' || v_days_late * v_late_fee);
ELSE
DBMS_OUTPUT.PUT_LINE('Book ID ' || v_book_id || ' was returned on time.');
END IF;
END LOOP;

CLOSE book_cursor;
END calculate_late_fee;
/
-- Execute the stored procedure
EXEC calculate_late_fee
Explanation:
1.We create a table book_loans to store information about
book loans.
2.We insert some sample data into the table.
3.We create a stored procedure calculate_late_fee that
uses a cursor to iterate through each book loan record.
4.Inside the loop, we calculate the number of days the
book is overdue.
5.If the book is overdue, we print a message with the
book ID, days late, and the late fee.
6.If the book is returned on time, we print a message
indicating that.
Constraints with examples

• SQL constraints are used to specify rules for the data in a table.

• Constraints are used to limit the type of data that can go into a table. This ensures the accuracy
and reliability of the data in the table. If there is any violation between the constraint and the
data action, the action is aborted.

• Constraints can be column level or table level. Column level constraints apply to a column, and
table level constraints apply to the whole table.

The following constraints are commonly used in SQL:


•NOT NULL - Ensures that a column cannot have a NULL value
•UNIQUE - Ensures that all values in a column are different
•PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table
•FOREIGN KEY - Prevents actions that would destroy links between tables
•CHECK - Ensures that the values in a column satisfies a specific condition
•DEFAULT - Sets a default value for a column if no value is specified
•CREATE INDEX - Used to create and retrieve data from the database very quickly
SQL NOT NULL CONSTRAINT
• SQL NOT NULL on CREATE TABLE
• Example
• CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);

• SQL NOT NULL on ALTER TABLE


• ALTER TABLE Persons
ALTER COLUMN Age int NOT NULL;
2. UNIQUE –
This constraint helps to uniquely identify each row in the table. i.e. for a particular
column, all the rows should have unique values. We can have more than one
UNIQUE columns in a table.
For example, the below query creates a table Student where the field ID is
specified as UNIQUE. i.e, no two students can have the same ID.

CREATE TABLE Student


(
ID int(6) NOT NULL UNIQUE,
NAME varchar(10),
ADDRESS varchar(20)
);
3. PRIMARY KEY –
• Primary Key is a field which uniquely identifies each row in the table. If a field in a
table as primary key, then the field will not be able to contain NULL values as well
as all the rows should have unique values for this field. So, in other words we can
say that this is combination of NOT NULL and UNIQUE constraints.

A table can have only one field as primary key. Below query will create a table
named Student and specifies the field ID as primary key.

CREATE TABLE Student


(
ID int(6) NOT NULL UNIQUE,
NAME varchar(10),
ADDRESS varchar(20),
PRIMARY KEY(ID)
);
4. FOREIGN KEY –
Foreign Key is a field in a table which uniquely identifies each row of a another table. That is, this field points to
primary key of another table. This usually creates a kind of link between the tables.
Consider the two tables as shown below:

O_ID ORDER_NO C_ID


1 2253 3
2 3325 3
3 4521 2
4 8532 1

C_ID NAME ADDRESS


1 RAMESH DELHI
2 SURESH NOIDA
3 DHARMESH GURGAON
As we can see clearly that the field C_ID in Orders table is the primary key in
Customers table, i.e. it uniquely identifies each row in the Customers table.
Therefore, it is a Foreign Key in Orders table.
Syntax:

CREATE TABLE Orders


(
O_ID int NOT NULL,
ORDER_NO int NOT NULL,
C_ID int, PRIMARY KEY (O_ID),
FOREIGN KEY (C_ID)
REFERENCES Customers(C_ID)
)
(i) CHECK –
Using the CHECK constraint we can specify a condition for a field, which should
be satisfied at the time of entering values for this field.
For example, the below query creates a table Student and specifies the condition
for the field AGE as (AGE >= 18 ). That is, the user will not be allowed to enter
any record in the table with AGE < 18. Check constraint in detail

CREATE TABLE Student


(
ID int(6) NOT NULL,
NAME varchar(10) NOT NULL,
AGE int NOT NULL CHECK (AGE >= 18)
);
(ii) DEFAULT –
This constraint is used to provide a default value for the fields. That is, if at the time of
entering new records in the table if the user does not specify any value for these fields
then the default value will be assigned to them.
For example, the below query will create a table named Student and specify the
default value for the field AGE as 18.

CREATE TABLE Student


( ID int(6) NOT NULL,
NAME varchar(10) NOT NULL,
AGE int DEFAULT 18
);
JOINS AND ITS TYPES

• SQL Join statement is used to combine data or rows from two


or more tables based on a common field between
them. Different types of Joins are as follows:
• INNER JOIN
• LEFT JOIN
• RIGHT JOIN
• FULL JOIN
• NATURAL JOIN
A. INNER JOIN
• The INNER JOIN keyword selects all rows from both the tables
as long as the condition is satisfied. This keyword will create
the result-set by combining all rows from both the tables
where the condition satisfies i.e value of the common field will
be the same.
Example Queries(INNER JOIN)
This query will show the names and age of students enrolled in different courses.
B. LEFT JOIN
• This join returns all the rows of the table on the left side of the
join and matches rows for the table on the right side of the join.
For the rows for which there is no matching row on the right side,
the result-set will contain null. LEFT JOIN is also known as LEFT
OUTER JOIN.
• C. RIGHT JOIN
• RIGHT JOIN is similar to LEFT JOIN.
• This join returns all the rows of the table on the right side of the join and matching rows for
the table on the left side of the join.
• For the rows for which there is no matching row on the left side, the result-set will
contain null.
• RIGHT JOIN is also known as RIGHT OUTER JOIN.
• D. FULL JOIN
• FULL JOIN creates the result-set by combining results of both LEFT JOIN
and RIGHT JOIN.
• The result-set will contain all the rows from both tables.
• For the rows for which there is no matching, the result-set will
contain NULL values.
• E. Natural join (?)
• Natural join can join tables based on the common columns in the
tables being joined. A natural join returns all rows by matching
values in common columns having same name and data type of
columns and that column should be present in both tables.
• Both table must have at list one common column with same column
name and same data type.
• The two table are joined using Cross join.
• DBMS will look for a common column with same name and data
type Tuples having exactly same values in common columns are kept
in result.
SET OPERATIONS
• The SQL Set operation is used to combine the two or more SQL
SELECT statements.
• Types of Set Operation
1.Union
2.UnionAll
3.Intersect
4.Minus
1.Union
• The SQL Union operation is used to combine the result of two or
more SQL SELECT queries.
• 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.
• 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;
3. Intersect
• It is used to combine two SELECT statements. The Intersect operation
returns the common rows from both the SELECT statements.
• In the Intersect operation, the number of datatype and columns must
be the same.
• It has no duplicates and it arranges the data in ascending order by
default.
4. Minus
• 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.
• It has no duplicates and data arranged in ascending order by default.
Sub queries-Nested Queries
• A Subquery is a query within another SQL query and embedded within the
WHERE clause.
• Important Rule:
• A subquery can be placed in a number of SQL clauses like WHERE clause,
FROM clause, HAVING clause.
• You can use Subquery with SELECT, UPDATE, INSERT, DELETE statements
along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
• A subquery is a query within another query. The outer query is known as the
main query, and the inner query is known as a subquery.
• Subqueries are on the right side of the comparison operator.
• A subquery is enclosed in parentheses.
• In the Subquery, ORDER BY command cannot be used. But GROUP BY
command can be used to perform the same function as ORDER BY
command.
1. Subqueries with the Select Statement
• SQL subqueries are most frequently used with the Select statement.
Syntax
2. Subqueries with the INSERT Statement
• SQL subquery can also be used with the Insert statement.
• In the insert statement, data returned from the subquery is used to
insert into another table.In the subquery, the selected data can be
modified with any of the character, date functions.
3. Subqueries with the UPDATE Statement
• The subquery of SQL can be used in conjunction with the Update
statement. When a subquery is used with the Update statement,
then either single or multiple columns in a table can be updated.
• This would impact three rows, and finally, the EMPLOYEE table would
have the following records.
4. Subqueries with the DELETE Statement
• The subquery of SQL can be used in conjunction with the Delete
statement just like any other statements mentioned above.
Views
• Views in SQL are considered as a virtual table. A view also contains
rows and columns.
• To create the view, we can select the fields from one or more tables
present in the database.
• A view can either have specific rows based on certain condition or all
the rows of a table.
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 AS
SELECT column1, column2.....
FROM table_name
WHERE condition;
• 2. Creating View from a single table
• In this example, we create a View named DetailsView from the table
Student_Detail.
3. Creating View from multiple tables
• View from multiple tables can be created by simply include multiple tables in the SELECT
statement.
• In the given example, a view is created named MarksView from two tables Student_Detail
and Student_Marks.

QUERY

CREATE VIEW MarksView AS


SELECT Student_Detail.NAME, Student_Detail.ADDRESS, Student_Marks.MARKS
FROM Student_Detail, Student_Mark
WHERE Student_Detail.NAME = Student_Marks.NAME;
4. Deleting View
A view can be deleted using the Drop View statement.

DROP VIEW view_name; - SYNTAX


Fundamentals of PL/SQL
• Full-featured programming language
• Interpreted language
• Execute using Oracle 10g utilities
• SQL*Plus
• Forms Builder
• Combines SQL queries with procedural commands
• Reserved words

65
PL/SQL Variables and Data Types
• Variable names must follow the Oracle naming
standard (Example: current_s_id, not $current_s_id)
• Strongly typed language
• Explicitly declare each variable including data type before
using variable
• Variable declaration syntax:
variable_name data_type_declaration;
• Default value always NULL

66
Scalar Variables
• Reference single value such as number, date, string
• Data types correspond to Oracle 10g database data types
• VARCHAR2
• CHAR
• DATE
• NUMBER

• PL/SQL has other data types that do not correspond to database


data types

67
Composite Variables
• Data object made up of multiple individual data
elements
• Data structure contains multiple scalar variables
• Composite variable data types include:
A • RECORD (multiple scalar values similar to a table’s record)
R • TABLE (tabular structure with multiple columns and
R
A rows)
Y • VARRAY (variable-sized array. Tabular structure that
can expand or contract based on data values)

68
Reference Variables
• Directly reference specific database column or row
• Assume data type of associated column or row
• %TYPE data declaration syntax:
variable_name tablename.fieldname%TYPE;
• %ROWTYPE data declaration syntax:
variable_name tablename%ROWTYPE;

LOB Data Type


• Must be manipulated using programs in DBMS_LOB
package

69
PL/SQL Program Blocks
• Declaration section
• Optional
• Execution section
• Required
• Exception section
• Optional
• Comment statements
ØEnclosed within /* and */ for
several lines’ comments
Ø-- for single line comments /* Script: Student register
Purpose: to enroll students
in class */

-- Script: Student register


-- Purpose: to enroll
students

70
PL/SQL Arithmetic Operators in
Describing Order of Precedence

• Parentheses are used to force PL/SQL interpreter


to evaluate operations in a certain order
total_hours_worked - 40 * over_time_rate

(total_hours_worked – 40) * over_time_rate

Questions: 2 * 2 ** 2 = ? 100 / 2 * 5 = ?

71
Assignment Statements
DECLARE
variable1 NUMBER := 0;

• Assigns value to variable BEGIN


variable2 NUMBER := 0;

variable2 := variable1

• Operator: := +1;
END;

• Syntax: variable_name := value;


• String literal within single quotation mark
• Examples:
current_s_first_name := ‘Tammy’;
current_student_ID NUMBER := 100;
Q: What is
• Result of adding a value to a NULL value is another the final
value of
NULL value variable2?

• DEFAULT keyword can be used instead of


assignment operator

72
Displaying PL/SQL Program Output
in SQL*Plus
• PL/SQL output buffer
• Memory area on database server
• Stores program’s output values before they are displayed
to user
• Default buffer size is 2000 bytes
• Should increase size if you want to display more than a
few lines in SQL Plus to avoid buffer overflow error
• Syntax: SET SERVEROUTPUT ON SIZE buffer_size
• Example: SET SERVEROUTPUT ON SIZE 4000

73
Displaying PL/SQL Program Output
in SQL*Plus (continued)
• DBMS_OUTPUT
• is an Oracle built-in package
• Consists of a set of programs for processing output
• PUT_LINE is the DBMS_OUTPUT procedure for
displaying output
• Syntax: DBMS_OUTPUT.PUT_LINE('display_text');
• Example: DBMS_OUTPUT.PUT_LINE(current_s_first);
• Displays maximum of 255 characters of text data
• If try to display more than 255 characters, error occurs

74
Writing a PL/SQL Program
• Write PL/SQL program in Notepad or another text
editor
• Indenting commands within each section is a good
programming practice. Will loose points if code is not
indented
• Copy and paste program commands from text
editor into SQL*Plus
• Press Enter after last program command
• Type front slash ( / )
• Then press Enter again

75
PL/SQL Program Commands

76
PL/SQL Data Conversion Functions
WHERE O_DATE = TO_DATE (‘29/05/2006’,
• Implicit data conversions‘DD/MM/YYYY’)
WHERE O_DATE =
• Interpreter automatically converts value from one data
‘29/05/2006’

type to another
• If PL/SQL interpreter unable to implicitly convert value
error occurs
• Explicit data conversions
• Convert variables to different data types
• Using data conversion functions

77
Manipulating Character Strings
• Concatenating
• Joining two separate strings
• Operator: || (i.e. double bar)
• Syntax: new_string := string1 || string2;
• Example: s_fullname := s_first || s_last;
• Parse
• Separate single string consisting of two data items
separated by commas or spaces
s_fullname := s_first ||‘ ’|| s_last;

Variable Data type Valu


e room_message := bldg_code || ‘ Room ’ || room_num
|| ‘ has ’ || TO_CHAR(room_capacity) || ‘seats.’;
Bldg_code VARCHAR2 LH
Room_num VARCHAR2 101
Room_capacity Question:
NUMBER Write down150
the value of room_message after the above Assignment statement is executed.

78
Removing Blank Leading and Trailing
Spaces from Strings
• LTRIM function
• Remove blank leading spaces
• string := LTRIM(string_variable_name);
• RTRIM function
• Remove blank trailing spaces
• string := RTRIM(string_variable_name);

DECLARE
s_address CHAR(20) := ‘951 Raimbow Dr’;
BEGIN
s_address := RTRIM(s_address);
END;

Questions: How many characters will be removed from the string assigned to the
s_address variable when the RTRIM function in the avove PL/SQL block is executed

79
Finding the Length of Character
Strings
• LENGTH function syntax
• string_length := LENGTH(string_variable_name);
• Example:
• code_length as NUMBER(3):= LENGTH(bldg_code);

• Q1: What will be the value of code_length if bldg_code’s


value is ‘CR’?
• Q2: What will be the value of code_length if bldg_code’s
value is ‘BUS ’?

80
Character String Case Functions
• Modify case of character strings
• Functions and syntax:
• string := UPPER(string_variable_name);
• string := LOWER(string_variable_name);
• string := INITCAP(string_variable_name);
• Example:
• s_full_name := UPPER(s_full_name);

81
Parsing Character Strings
• INSTR function
• Searches string for specific substring
• Returns an integer representing starting position of the
substring within the original string
• Syntax:
curr_course_no
start_position := INSTR(original_string, := ‘MIS 101’
substring);
• Example: blank_position := INSTR(curr_course_no, ‘ ’);

• SUBSTR function
• Extracts specific number of characters from character string
starting at given point.
• Syntax: extracted_string :=
SUBSTR(string_variable,starting_point, number_of_characters);
• Example: curr_dept := SUBSTR(curr_course_no, 1, 3);

82
Parsing Character Strings
(continued)
• Q1: Assuming that curr_course_no contains ‘MIS 4200’, what
will be the value of curr_dept when the following statement is
executed? blank_space := INSTR(curr_course_no, ‘ ’);
curr_dept := SUBSTR((curr_course_no, 1, (blank_space – 1))

• Q2: Assuming that curr_course_no contains ‘MIS 4200’,


what will be the value of curr_number when the following
statement is executed? blank_space := INSTR(curr_course_no, ‘ ’);
curr_number := SUBSTR(curr_course_no, (blank_space + 1),
(LENGTH(curr_course_no) – blank_space));

83
Debugging PL/SQL Programs
• Syntax error
• Occurs when command does not follow guidelines of
programming language
• Generate compiler or interpreter error messages
• Logic error
• Does not stop program from running
• Results in incorrect result

84
Program with a Syntax Error

85
Program with a Logic Error

• Which of the following is the source of the error?


– LENGTH(curr_course_no) – blank_space));
– SUBSTR(curr_course_no, blank_space,

86
Finding Syntax Errors
• Often involve:
• Misspelling reserved word
• Omitting required character in command
• Using built-in function improperly
• Interpreter
• Flags line number
• Displays error code and message
• Example: PLS-00103: Encountered the symbol “Blank space” when
expecting one of the following …
• Error may actually be on preceding line
• To find error: (a) comment out suspect program lines using --,
REM, (b) modify suspect lines.
• Cascading errors
• One syntax error can generate many more errors

87
Finding Logic Errors
• Caused by:
• Not using proper order of operations in arithmetic
functions
• Passing incorrect parameter values to built-in functions
• Creating loops that do not terminate properly
• Using data values that are out of range or not of right
data type

88
Finding Logic Errors (continued)
• Debugger
• Program that enables software developers to pause
program execution and examine current variable
values
• Best way to find logic errors
• SQL*Plus environment does not provide PL/SQL
debugger
• Use DBMS_OUTPUT to print variable values

89
Finding Logic Errors (continued)

90
TRIGGERS
Triggers

 A trigger is a statement that is executed automatically


by the system as a side effect of a modification to the
database.
 To design a trigger mechanism, we must:
 Specify the conditions under which the trigger is to
be executed.
 Specify the actions to be taken when the trigger
executes.
 Triggers introduced to SQL standard in SQL:1999, but
supported even earlier using non-standard syntax by
most databases.
 Syntax illustrated here may not work exactly on your
database system; check the system manuals
Triggering Events and Actions in SQL

 Triggering event can be insert, delete or update


 Triggers on update can be restricted to specific attributes
 E.g., after update of takes on grade
 Values of attributes before and after an update can be
referenced
 referencing old row as : for deletes and updates
 referencing new row as : for inserts and updates
 Triggers can be activated before an event, which can serve as
extra constraints. E.g. convert blank grades to null.
create trigger setnull_trigger before update of takes
referencing new row as nrow
for each row
when (nrow.grade = ‘ ‘)
begin atomic
set nrow.grade = null;
end;
Trigger to Maintain credits_earned value

 create trigger credits_earned after update of takes on (grade)


referencing new row as nrow
referencing old row as orow
for each row
when nrow.grade <> ’F’ and nrow.grade is not null
and (orow.grade = ’F’ or orow.grade is null)
begin atomic
update student
set tot_cred= tot_cred +
(select credits
from course
where course.course_id= nrow.course_id)
where student.id = nrow.id;
end;
Statement Level Triggers

 Instead of executing a separate action for each affected


row, a single action can be executed for all rows affected
by a transaction
 Use for each statement instead of for each
row
 Use referencing old table or referencing new
table to refer to temporary tables (called transition
tables) containing the affected rows
 Can be more efficient when dealing with SQL
statements that update a large number of rows
When Not To Use Triggers

 Triggers were used earlier for tasks such as


 maintaining summary data (e.g., total salary of each department)
 Replicating databases by recording changes to special relations
(called change or delta relations) and having a separate process
that applies the changes over to a replica
 There are better ways of doing these now:
 Databases today provide built in materialized view facilities to
maintain summary data
 Databases provide built-in support for replication
 Encapsulation facilities can be used instead of triggers in many cases
 Define methods to update fields
 Carry out actions as part of the update methods instead of
through a trigger
When Not To Use Triggers

 Risk of unintended execution of triggers, for example, when


 loading data from a backup copy
 replicating updates at a remote site
 Trigger execution can be disabled before such actions.
 Other risks with triggers:
 Error leading to failure of critical transactions that set off the
trigger
 Cascading execution
Oracle Example 1

A trigger that corrects mixed-case state names


CREATE OR REPLACE TRIGGER vendors_before_update_state
BEFORE INSERT OR UPDATE OF vendor_state
ON vendors
FOR EACH ROW
WHEN (NEW.vendor_state != UPPER(NEW.vendor_state))
BEGIN
:NEW.vendor_state := UPPER(:NEW.vendor_state);
END;
/
Oracle Example 1

An UPDATE statement that fires the trigger


UPDATE vendors
SET vendor_state = 'wi'
WHERE vendor_id = 1;

A SELECT statement that shows the new row


SELECT vendor_name, vendor_state
FROM vendors
WHERE vendor_id = 1;

The result set


Oracle Example 2

A trigger that validates line item amounts


CREATE OR REPLACE TRIGGER invoices_before_update_total
BEFORE UPDATE OF invoice_total
ON invoices
FOR EACH ROW
DECLARE
sum_line_item_amount NUMBER;
BEGIN
SELECT SUM(line_item_amt)
INTO sum_line_item_amount
FROM invoice_line_items
WHERE invoice_id = :new.invoice_id;

IF sum_line_item_amount != :new.invoice_total THEN


RAISE_APPLICATION_ERROR(-20001,
'Line item total must match invoice total.');
END IF;
END;
/
Oracle Example 2

An UPDATE statement that fires the trigger


UPDATE invoices
SET invoice_total = 600
WHERE invoice_id = 100;

The response from the system


ORA-20001: Line item total must match invoice total.
Oracle Example 3

An AFTER trigger that inserts rows into the table


CREATE OR REPLACE TRIGGER invoices_after_dml
AFTER INSERT OR UPDATE OR DELETE
ON invoices
FOR EACH ROW
BEGIN
IF INSERTING THEN
INSERT INTO invoices_audit VALUES
(:new.vendor_id, :new.invoice_number,
:new.invoice_total, 'INSERTED', SYSDATE);
ELSIF UPDATING THEN
INSERT INTO invoices_audit VALUES
(:old.vendor_id, :old.invoice_number,
:old.invoice_total, 'UPDATED', SYSDATE);
ELSIF DELETING THEN
INSERT INTO invoices_audit VALUES
(:old.vendor_id, :old.invoice_number,
:old.invoice_total, 'DELETED', SYSDATE);
END IF;
END;
/
Oracle Example 3

An INSERT statement that fires the trigger


INSERT INTO invoices VALUES
(115, 34, 'ZXA-080', '30-AUG-14', 14092.59, 0, 0, 3,
'30-SEP-14', NULL);

A DELETE statement that fires the trigger


DELETE FROM invoices WHERE invoice_number = 'ZXA-080';

A statement that retrieves the audit table rows


SELECT * FROM invoices_deleted;

The result set


CURSOR
SELECT Statements in PL/SQL

Retrieve data from the database with a SELECT


statement.
Syntax:
SELECT select_list
INTO {variable_name[, variable_name]...
| record_name}
FROM table
[WHERE condition];
SELECT Statements in PL/SQL

• The INTO clause is required.


• Queries must return only one row.
Example
SET SERVEROUTPUT ON
DECLARE
fname VARCHAR2(25);
BEGIN
SELECT first_name INTO fname
FROM employees WHERE employee_id=200;
DBMS_OUTPUT.PUT_LINE(' First Name is : '||fname);
END;
/
Retrieve the hire_date and the salary for the specified employee.
Retrieving Data in PL/SQL

Retrieve the hire_date and the salary for the


specified employee.
Example
DECLARE
emp_hiredate employees.hire_date%TYPE;
emp_salary employees.salary%TYPE;
BEGIN
SELECT hire_date, salary
INTO emp_hiredate, emp_salary
FROM employees
WHERE employee_id = 100;
END;
/
Retrieving Data in PL/SQL

Return the sum of the salaries for all the employees in


the specified department.
Example
SET SERVEROUTPUT ON
DECLARE
sum_sal NUMBER(10,2);
deptno NUMBER NOT NULL := 60;
BEGIN
SELECT SUM(salary) -- group function
INTO sum_sal FROM employees
WHERE department_id = deptno;
DBMS_OUTPUT.PUT_LINE ('The sum of salary is '
|| sum_sal);
END;
/
Manipulating Data Using PL/SQL

Make changes to database tables by using DML


commands:
• INSERT DELETE
• UPDATE
• DELETE

INSERT

UPDATE
Inserting Data

Add new employee information to the EMPLOYEES


table.
Example
BEGIN
INSERT INTO employees
(employee_id, first_name, last_name, email,
hire_date, job_id, salary)
VALUES(employees_seq.NEXTVAL, 'Ruth', 'Cores',
'RCORES',sysdate, 'AD_ASST', 4000);
END;
/
Sequences in Oracle

create sequence test_oct8 start with 1 increment by 1;

Operators Nextval and currval :

select test_oct8.currval from dual;

select test_oct8.nextval from dual


SQL Cursor

• A cursor is a pointer to the private memory


area allocated by the Oracle server.
• There are two types of cursors:
– Implicit: Created and managed internally by
the Oracle server to process SQL statements
– Explicit: Explicitly declared by the
programmer
IMPLICIT CURSORS

-Any given PL/SQL block issues an implicit cursor


whenever an SQL statement is executed (as long as an
explicit cursor does not exist for that SQL statement)
-A cursor is automatically associated with every DML
statement
-All update and delete statements have cursors that identify
the set of rows that will be affected by the operation
-The most recently opened cursor is called ‘SQL%’ cursor.
SQL Cursor Attributes for Implicit Cursors

Using SQL cursor attributes, you can test the outcome


of your SQL statements.
SQL%FOUND Boolean attribute that evaluates to TRUE if the
most recent SQL statement returned at least one
row
SQL%NOTFOUND Boolean attribute that evaluates to TRUE if
the most recent SQL statement did not
return even one row
SQL%ROWCOUNT An integer value that represents the number of
rows affected by the most recent SQL statement
SQL Cursor Attributes for Implicit Cursors- an example - update

BEGIN
UPDATE S
SET status = 40
WHERE status = 30;
DBMS_OUTPUT.PUT_LINE('Number of updates = '||
SQL%ROWCOUNT);
END;
/
SQL Cursor Attributes for Implicit Cursors – another example -
delete

Delete rows that have the specified employee ID


from the employees table. Print the number of
rows deleted.
Example
VARIABLE rows_deleted VARCHAR2(30)
DECLARE
empno employees.employee_id%TYPE := 176;
BEGIN
DELETE FROM employees
WHERE employee_id = empno;
:rows_deleted := (SQL%ROWCOUNT ||
' row deleted.');
END;
/
PRINT rows_deleted
COMMIT, ROLLBACK, SAVEPOINT

Self – read !
Controlling Flow of Execution

for
loop

while
IF Statements

Syntax:
IF condition THEN
statements;
[ELSIF condition THEN
statements;]
[ELSE
statements;]
END IF;
IF ELSIF ELSE Clause

DECLARE
myage number:=31;
BEGIN
IF myage < 11
THEN
DBMS_OUTPUT.PUT_LINE(' I am a child ');
ELSIF myage < 20
THEN
DBMS_OUTPUT.PUT_LINE(' I am young ');
ELSIF myage < 30
THEN
DBMS_OUTPUT.PUT_LINE(' I am in my twenties');
ELSIF myage < 40
THEN
DBMS_OUTPUT.PUT_LINE(' I am in my thirties');
ELSE
DBMS_OUTPUT.PUT_LINE(' I am always young ');
END IF;
END;
/
CASE Expressions

• A CASE expression selects a result and returns it.


• To select the result, the CASE expression uses
expressions. The value returned by these
expressions is used to select one of several
alternatives.
CASE selector
WHEN expression1 THEN result1
WHEN expression2 THEN result2
...
WHEN expressionN THEN resultN
[ELSE resultN+1]
END;
/
CASE Expressions: Example

SET SERVEROUTPUT ON
SET VERIFY OFF
DECLARE
grade CHAR(1) := UPPER('&grade');
appraisal VARCHAR2(20);
BEGIN
appraisal :=
CASE grade
WHEN 'A' THEN 'Excellent'
WHEN 'B' THEN 'Very Good'
WHEN 'C' THEN 'Good'
ELSE 'No such grade'
END;
DBMS_OUTPUT.PUT_LINE ('Grade: '|| grade || '
Appraisal ' || appraisal);
END;
/
Iterative Control: LOOP Statements

• Loops repeat a statement or sequence of


statements multiple times.
• There are three loop types:
– Basic loop
– FOR loop
– WHILE loop
Basic Loops

Syntax:
LOOP
statement1;
. . .
EXIT [WHEN condition];
END LOOP;
Basic Loops

Example
DECLARE
countryid locations.country_id%TYPE := 'CA';
loc_id locations.location_id%TYPE;
counter NUMBER(2) := 1;
new_city locations.city%TYPE := 'Montreal';
BEGIN
SELECT MAX(location_id) INTO loc_id FROM locations
WHERE country_id = countryid;
LOOP
INSERT INTO locations(location_id, city, country_id)
VALUES((loc_id + counter), new_city, countryid);
counter := counter + 1;
EXIT WHEN counter > 3;
END LOOP;
END;
/
WHILE Loops

Syntax:
WHILE condition LOOP
statement1;
statement2;
. . .
END LOOP;

Use the WHILE loop to repeat statements while a


condition is TRUE.
Course Code 21CSC205P
Course name Database Management
Systems

Unit – :3 Session – :9

SRM Institute of Science and Technology 128


WHILE Loops

Example
DECLARE
countryid locations.country_id%TYPE := 'CA';
loc_id locations.location_id%TYPE;
new_city locations.city%TYPE := 'Montreal';
counter NUMBER := 1;
BEGIN
SELECT MAX(location_id) INTO loc_id FROM locations
WHERE country_id = countryid;
WHILE counter <= 3 LOOP
INSERT INTO locations(location_id, city, country_id)
VALUES((loc_id + counter), new_city, countryid);
counter := counter + 1;
END LOOP;
END;
/
FOR Loops

• Use a FOR loop to shortcut the test for the number


of iterations.
• Do not declare the counter; it is declared
implicitly.
• 'lower_bound .. upper_bound' is required
syntax.
FOR counter IN [REVERSE]
lower_bound..upper_bound LOOP
statement1;
statement2;
. . .
END LOOP;
FOR Loops

Example
DECLARE
countryid locations.country_id%TYPE := 'CA';
loc_id locations.location_id%TYPE;
new_city locations.city%TYPE := 'Montreal';
BEGIN
SELECT MAX(location_id) INTO loc_id
FROM locations
WHERE country_id = countryid;
FOR i IN 1..3 LOOP
INSERT INTO locations(location_id, city, country_id)
VALUES((loc_id + i), new_city, countryid );
END LOOP;
END;
/
Cursors

Every SQL statement executed by the Oracle server


has an associated individual cursor:
• Implicit cursors: Declared and managed by
PL/SQL for all DML and PL/SQL SELECT
statements
• Explicit cursors: Declared and managed by the
programmer
Explicit Cursor Operations

Table
100 King AD_PRES
101 Kochhar AD_VP
Active set
102 De Haan AD_VP
. . .
. . .
. . .
139 Seo ST_CLERK
140 Patel ST_CLERK
. . .
Controlling Explicit Cursors

No

Yes
DECLARE OPEN FETCH EMPTY? CLOSE

• Create a • Identify the • Load the • Test for • Release the


named active set. current existing active set.
SQL area. row into rows.
variables.
• Return to
FETCH if
rows are
found.
Controlling Explicit Cursors

1 Open the cursor.


Cursor
pointer

2 Fetch a row.
Cursor
pointer

Cursor
3 Close the cursor. pointer
Declaring the Cursor

Syntax:
CURSOR cursor_name IS
select_statement;

Examples
DECLARE
CURSOR emp_cursor IS
SELECT employee_id, last_name FROM employees
WHERE department_id =30;
DECLARE
locid NUMBER:= 1700;
CURSOR dept_cursor IS
SELECT * FROM departments
WHERE location_id = locid;
...
Opening the Cursor

DECLARE
CURSOR emp_cursor IS
SELECT employee_id, last_name FROM employees
WHERE department_id =30;
...
BEGIN
OPEN emp_cursor;
Fetching Data from the Cursor

SET SERVEROUTPUT ON
DECLARE
CURSOR emp_cursor IS
SELECT employee_id, last_name FROM employees
WHERE department_id =30;
empno employees.employee_id%TYPE;
lname employees.last_name%TYPE;
BEGIN
OPEN emp_cursor;
FETCH emp_cursor INTO empno, lname;
DBMS_OUTPUT.PUT_LINE( empno ||' '||lname);
...
END;
/
Fetching Data from the Cursor

SET SERVEROUTPUT ON
DECLARE
CURSOR emp_cursor IS
SELECT employee_id, last_name FROM employees
WHERE department_id =30;
empno employees.employee_id%TYPE;
lname employees.last_name%TYPE;
BEGIN
OPEN emp_cursor;
LOOP
FETCH emp_cursor INTO empno, lname;
EXIT WHEN emp_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE( empno ||' '||lname);
END LOOP;
...
END;
/
Closing the Cursor

...
LOOP
FETCH emp_cursor INTO empno, lname;
EXIT WHEN emp_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE( empno ||' '||lname);
END LOOP;
CLOSE emp_cursor;
END;
/
%TYPE and %ROWTYPE attributes

-%ROWTYPE is for records as %TYPE is for fields

-The %ROWTYPE attribute provides a record type that


represents a row in a database table. The record can
store an entire row of data selected from the table or
fetched from a cursor or cursor variable. Variables
declared using %ROWTYPE are treated like those
declared using a datatype name. You can use the
%ROWTYPE attribute in variable declarations as a
datatype specifier.
%TYPE and %ROWTYPE attributes

- Fields in a record and corresponding columns in a row


have the same names and datatypes. However, fields in a
%ROWTYPE record do not inherit constraints, such as the
NOT NULL column or check constraint, or default values

- Both %TYPE and %ROWTYPE are used to define variables


in PL/SQL as it is defined within the database. If the datatype
or precision of a column changes, the program
automatically picks up the new definition from the database
without having to make any code changes.

- The %TYPE and %ROWTYPE constructs provide data


independence, reduces maintenance costs, and allows
programs to adapt as the database changes to meet new
business needs.
Cursors and Records

Process the rows of the active set by fetching values


into a PL/SQL record.
DECLARE
CURSOR emp_cursor IS
SELECT employee_id, last_name FROM employees
WHERE department_id =30;
emp_record emp_cursor%ROWTYPE;
BEGIN
OPEN emp_cursor;
LOOP
FETCH emp_cursor INTO emp_record;
...
Cursor FOR Loops

Syntax:
FOR record_name IN cursor_name LOOP
statement1;
statement2;
. . .
END LOOP;

• The cursor FOR loop is a shortcut to process


explicit cursors.
• Implicit open, fetch, exit, and close occur.
• The record is implicitly declared.
Cursor FOR Loops

SET SERVEROUTPUT ON
DECLARE
CURSOR emp_cursor IS
SELECT employee_id, last_name FROM employees
WHERE department_id =30;
BEGIN
FOR emp_record IN emp_cursor
LOOP
DBMS_OUTPUT.PUT_LINE( emp_record.employee_id
||' ' ||emp_record.last_name);
END LOOP;
END;
/
Explicit Cursor Attributes

Obtain status information about a cursor.


Attribute Type Description

%ISOPEN Boolean Evaluates to TRUE if the cursor is


open
%NOTFOUN Boolea Evaluates to TRUE if the most
D n recent fetch does not return a row
%FOUN Boolea Evaluates to TRUE if the most
D n recent fetch returns a row;
complement of %NOTFOUND
%ROWCOUN Numbe Evaluates to the total number of
T r rows returned so far
%ISOPEN Attribute

• Fetch rows only when the cursor is open.


• Use the %ISOPEN cursor attribute before
performing a fetch to test whether the cursor is
open.
Example
IF NOT emp_cursor%ISOPEN THEN
OPEN emp_cursor;
END IF;
LOOP
FETCH emp_cursor...
%ROWCOUNT and %NOTFOUND: Example

SET SERVEROUTPUT ON
DECLARE
empno employees.employee_id%TYPE;
ename employees.last_name%TYPE;
CURSOR emp_cursor IS SELECT employee_id,
last_name FROM employees;
BEGIN
OPEN emp_cursor;
LOOP
FETCH emp_cursor INTO empno, ename;
EXIT WHEN emp_cursor%ROWCOUNT > 10 OR
emp_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(TO_CHAR(empno)
||' '|| ename);
END LOOP;
CLOSE emp_cursor;
END ;
/
Cursor FOR Loops Using Subqueries

There is no need to declare the cursor.


Example
SET SERVEROUTPUT ON
BEGIN
FOR emp_record IN (SELECT employee_id, last_name
FROM employees WHERE department_id =30)
LOOP
DBMS_OUTPUT.PUT_LINE( emp_record.employee_id ||'
'||emp_record.last_name);
END LOOP;
END;
/
Cursors with Parameters

Syntax:
CURSOR cursor_name
[(parameter_name datatype, ...)]
IS
select_statement;

• Pass parameter values to a cursor when the


cursor is opened and the query is executed.
• Open an explicit cursor several times with a
different active set each time.
OPEN cursor_name(parameter_value,.....) ;
Cursors with Parameters

SET SERVEROUTPUT ON
DECLARE
CURSOR emp_cursor (deptno NUMBER) IS
SELECT employee_id, last_name
FROM employees
WHERE department_id = deptno;
dept_id NUMBER;
lname VARCHAR2(15);
BEGIN
OPEN emp_cursor (10);
...
CLOSE emp_cursor;
OPEN emp_cursor (20);
...

You might also like