UNIT 3
UNIT 3
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
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
2.We need to calculate the late fee for each book based on
the number of days it is overdue.
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.
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
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
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;
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 */
70
PL/SQL Arithmetic Operators in
Describing Order of Precedence
Questions: 2 * 2 ** 2 = ? 100 / 2 * 5 = ?
71
Assignment Statements
DECLARE
variable1 NUMBER := 0;
variable2 := variable1
• Operator: := +1;
END;
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;
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);
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))
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
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
INSERT
UPDATE
Inserting Data
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
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
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
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;
Unit – :3 Session – :9
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
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
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
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
Syntax:
FOR record_name IN cursor_name LOOP
statement1;
statement2;
. . .
END LOOP;
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
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
Syntax:
CURSOR cursor_name
[(parameter_name datatype, ...)]
IS
select_statement;
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);
...