DBMS Lab 2-2
DBMS Lab 2-2
1. Creating, altering and dropping of tables and Inserting rows into a table.(Use Constraints while
Creating Tables) examples using SELECT Command.
AIM: By using SQL Queries, Creating, altering and dropping of tables and Inserting rows into a table.
DESCRIPTION:
TRUNCATE – Used to delete the data inside a table, but not the table itself.
SYNTAX: TRUNCATE TABLE TABLE_NAME;
2. DQL or Data Query Language. – Data query language (DQL) is a set of SQL commands
that are used to query data inside schema objects
SELECT – Retrieves data from a database
SYNTAX: SELECT COLUMN1, COLUMN2, COLUMN3 FROM TABLE_NAME;
3. DML or Data Manipulation Language. – Refers to SQL instructions that deal with the
alteration of information stored within a database.
INSERT – Adds new records to a table
SYNTAX: INSERT INTO TABLE_NAME (COLUMN1, COLUMN2) VALUES (VALUE1, VALUE2);
4. DCL or Data Control Language. – Which primarily interact with the database system’s
rights, permits, and other restrictions?
GRANT – Used to give specific privileges to users or roles.
SYNTAX: GRANT SELECT, INSERT ON TABLE_NAME TO USER_NAME;
SAVEPOINT - It creates a transaction save point. You can set a point within a
transaction to which you can later roll back. It does not rollback the entire
transaction but only up to a certain point.
Syntax: SAVEPOINT savepoint_name; /* Create a SAVEPOINT */
ROLLBACK TO SAVEPOINT savepoint_name; /* Rollback to the SAVEPOINT */
SQL QUERIES:
SQL>SELECT FirstName, LastName, Salary FROM Employees WHERE Salary > 50000;
(This will display the FirstName, LastName, and Salary for employees who have a salary greater
than 50,000)
7. Drop Table
SQL>DROP TABLE Employees;
2. Queries (along with Sub Queries) using ANY, ALL, IN, EXISTS, NOT EXISTS, UNION, INTERSECT,
Constraints. Example: - Select the Roll No. & Name of the student who Secured fourth rank in the
class.
DESCRIPTION:
SQL QUERIES:
We want to select the Roll No. & Name of the student who secured fourth rank in the class.
Let's assume you have a table Students with the following structure:
SQL>CREATE TABLE Students (
RollNo INT PRIMARY KEY,
Name VARCHAR(100),
Marks INT);
6. Using UNION
SQL> select RollNo,Name from Students UNION select EmployeeID, FirstName FROM Employees;
7. Using INTERSECT
SQL> select RollNo,Name from Students INTERSECT select EmployeeID, FirstName FROM
Employees;
R23_DBMS LAB Programs - 3
3. Queries using Aggregate Functions ( COUNT, SUM, AVG, MAX and MIN), GROUP BY, HAVING and
Creation and Dropping of Views.
DESCRIPTION:
Aggregate Functions: An aggregate function in SQL returns one value after calculating multiple column
values. We often use aggregate functions with the SELECT statement's GROUP BY and HAVING clauses.
SQL QUERIES:
>> Create table product(Pid int,Item_name varchar(30), Company varchar(30), Qty int,Rate
int, Cost int);
Command(s) completed successfully.
>> SELECT Company, COUNT(*) FROM product GROUP BY Company HAVING COUNT(*)>1;
>> SELECT COMPANY, SUM(COST) FROM product GROUP BY COMPANY HAVING SUM(COST)>=12000;
4. Queries using Conversion Functions (to_char, to_number and to_date), String Functions
(Concatenation, lpad, rpad, ltim, lower, upper, initcap, length, substr and instr), Date Functions
(Sysdate, next_day, add_months, last_day, months_between, least, greatest, trunk, round, to_char,
to_date)
Examples:
Converting Date to String:
SQL>SELECT TO_CHAR (SYSDATE, 'YYYY-MM-DD') AS "Formatted Date" FROM dual;
This converts the current date into the string YYYY-MM-DD.
Converting Number to String:
SQL>SELECT TO_CHAR (12345.678, '99999.99') AS "Formatted Number" FROM dual;
This converts the number 12345.678 into the string '12345.68' (formatted as 99999.99).
Date with Time:
SQL>SELECT TO_CHAR (SYSDATE, 'DD-Mon-YYYY HH24:MI:SS') AS "Date with Time"
FROM dual;
This will output the current date and time in the format DD-Mon-YYYY HH24:MI:SS, e.g., 10-
Feb-2025 14:30:45.
2. TO_NUMBER
Purpose: Converts a string or other value to a numeric type (e.g., integer, decimal). It is
commonly used to convert a string to a number for mathematical operations or comparisons.
Syntax: TO_NUMBER (value, 'format')
Examples:
Converting String to Number:
SQL>SELECT TO_NUMBER ('12345.67') AS "Converted Number" FROM dual;
This converts the string '12345.67' to a numeric value 12345.67.
With Formatting:
SQL>SELECT TO_NUMBER ('1,234,567.89', '9,999,999.99') AS "Formatted Number" FROM
dual;
This converts the string '1,234,567.89' to the number 1234567.89, removing the commas.
Handling Invalid Input: If the string is not numeric, Oracle throws an error. To handle non-
numeric strings, use TO_NUMBER with the DEFAULT parameter:
SQL>SELECT TO_NUMBER ('abc', '999') DEFAULT 0 ON CONVERSION ERROR FROM
dual;
This will return 0 when the conversion fails.
3. TO_DATE
Purpose: Converts a string to a date using a specified date format.
Syntax: TO_DATE (string, 'format')
Examples:
Converting String to Date:
SQL>SELECT TO_DATE ('2025-02-10', 'YYYY-MM-DD') AS "Converted Date" FROM dual;
This converts the string '2025-02-10' into a date value.
Using Time in the Date:
SQL>SELECT TO_DATE ('2025-02-10 14:30:00', 'YYYY-MM-DD HH24:MI:SS') AS "Date
with Time" FROM dual;
This converts the string '2025-02-10 14:30:00' into a date-time value.
Converting Date to String: While TO_DATE converts strings to dates, you can use TO_CHAR
to convert a date back to a string in your desired format.
1. ASCII (): This function is used to find the ASCII value of a character.
Syntax: SELECT ascii('t');
Output: 116
2. CHAR_LENGTH (): Doesn’t work for SQL Server. Use LEN () for SQL Server. This
function is used to find the length of a word.
Syntax: SELECT char_length ('Hello!');
Output: 6
3. CHARACTER_LENGTH (): Doesn’t work for SQL Server. Use LEN () for SQL Server.
This function is used to find the length of a line.
Syntax: SELECT CHARACTER_LENGTH ('geeks for geeks');
Output: 15
5. CONCAT_WS (): This function is used to add two words or strings with a symbol as
concatenating symbol.
Syntax: SELECT CONCAT_WS ('_', 'geeks', 'for', 'geeks');
Output: geeks_for_geeks
6. FIND_IN_SET (): This function is used to find a symbol from a set of symbols.
Syntax: SELECT FIND_IN_SET ('b', 'a, b, c, d, e, f');
Output: 2
7. FORMAT (): This function is used to display a number in the given format.
Syntax: Format ("0.981", "Percent");
Output: ‘98.10%’
8. INSERT (): This function is used to insert the data into a database.
Syntax: INSERT INTO database (geek_id, geek_name) VALUES (5000, 'abc');
Output: successfully updated
10. LCASE (): This function is used to convert the given string into lower case.
Syntax: LCASE ("GeeksFor Geeks To Learn");
Output: geeksforgeeks to learn
11. LEFT (): This function is used to SELECT a sub string from the left of given size or
characters.
Syntax: SELECT LEFT ('geeksforgeeks.org', 5);
Output: geeks
12. LENGTH (): This function is used to find the length of a word.
Syntax: LENGTH ('GeeksForGeeks');
Output: 13
13. LOCATE (): This function is used to find the nth position of the given word in a string.
Syntax: SELECT LOCATE ('for', 'geeksforgeeks', 1);
Output: 6
14. LOWER (): This function is used to convert the upper case string into lower case.
Syntax: SELECT LOWER ('GEEKSFORGEEKS.ORG');
Output: geeksforgeeks.org
15. LPAD (): This function is used to make the given string of the given size by adding the given
symbol.
Syntax: LPAD ('geeks', 8, '0');
Output: 000geeks
16. LTRIM (): This function is used to cut the given sub string from the original string.
Syntax: LTRIM ('123123geeks', '123');
Output: geeks
17. MID (): This function is to find a word from the given position and of the given size.
Syntax: Mid ("geeksforgeeks", 6, 2);
Output: for
18. POSITION (): This function is used to find position of the first occurrence of the given
alphabet.
Syntax: SELECT POSITION ('e' IN 'geeksforgeeks');
Output: 2
19. REPEAT (): This function is used to write the given string again and again till the number of
times mentioned.
Syntax: SELECT REPEAT ('geeks', 2);
Output: geeksgeeks
20. REPLACE (): This function is used to cut the given string by removing the given sub string.
Syntax: REPLACE ('123geeks123', '123');
Output: geeks
22. RIGHT (): This function is used to SELECT a sub string from the right end of the given size.
Syntax: SELECT RIGHT ('geeksforgeeks.org', 4);
Output: ‘.org’
23. RPAD (): This function is used to make the given string as long as the given size by adding
the given symbol on the right.
Syntax: RPAD ('geeks', 8, '0');
Output: ‘geeks000’
24. RTRIM (): This function is used to cut the given sub string from the original string.
Syntax: RTRIM ('geeksxyxzyyy', 'xyz');
Output: ‘geeks’
25. SPACE (): This function is used to write the given number of spaces.
Syntax: SELECT SPACE (7);
Output: ‘ ‘
27. SUBSTR (): This function is used to find a sub string from the a string from the given
position.
Syntax:SUBSTR('geeksforgeeks', 1, 5);
Output: ‘geeks’
28. SUBSTRING (): This function is used to find an alphabet from the mentioned size and the
given string.
Syntax: SELECT SUBSTRING ('GeeksForGeeks.org', 9, 1);
Output: ‘G’
29. SUBSTRING_INDEX (): This function is used to find a sub string before the given symbol.
Syntax: SELECT SUBSTRING_INDEX ('www.geeksforgeeks.org', '.', 1);
Output: ‘www’
30. TRIM (): This function is used to cut the given symbol from the string.
Syntax: TRIM (LEADING '0' FROM '000123');
Output: 123
31. UCASE (): This function is used to make the string in upper case.
Syntax: UCASE ("GeeksForGeeks");
Output: GEEKSFORGEEKS
Date functions are functions that help to format dates and carry out date-related calculations on
your data.
1. SYSDATE
Purpose: Returns the current date and time from the system where the database is running.
Syntax: SYSDATE
Example:
SQL>SELECT SYSDATE FROM dual;
This returns the current date and time (e.g., 2025-02-10 14:30:00).
2. NEXT_DAY
Purpose: Returns the date of the next specified day of the week after a given date.
Syntax: NEXT_DAY(date, 'day_of_week')
Example:
SQL>SELECT NEXT_DAY(SYSDATE, 'MONDAY') FROM dual;
This returns the next Monday after the current date.
3. ADD_MONTHS
Purpose: Adds a specified number of months to a date.
Syntax: ADD_MONTHS(date, num_months)
Example:
SQL>SELECT ADD_MONTHS(SYSDATE, 3) FROM dual;
This adds 3 months to the current date.
4. LAST_DAY
Purpose: Returns the last day of the month for a given date.
Syntax: LAST_DAY(date)
Example:
SQL>SELECT LAST_DAY(SYSDATE) FROM dual;
This returns the last day of the current month.
5. MONTHS_BETWEEN
Purpose: Returns the number of months between two dates.
Syntax: MONTHS_BETWEEN(date1, date2)
Example:
SQL>SELECT MONTHS_BETWEEN(SYSDATE, TO_DATE('2025-01-01', 'YYYY-MM-
DD')) FROM dual;
This returns the number of months between the current date and January 1st, 2025.
6. LEAST
Purpose: Returns the smallest (earliest) date from a list of dates.
Syntax: LEAST(date1, date2, ...)
Example:
SQL>SELECT LEAST(SYSDATE, TO_DATE('2025-01-01', 'YYYY-MM-DD'),
TO_DATE('2025-12-31', 'YYYY-MM-DD')) FROM dual;
This returns the earliest date from the given dates.
7. GREATEST
Purpose: Returns the largest (latest) date from a list of dates.
Syntax: GREATEST(date1, date2, ...)
Example:
SQL>SELECT GREATEST(SYSDATE, TO_DATE('2025-01-01', 'YYYY-MM-DD'),
TO_DATE('2025-12-31', 'YYYY-MM-DD')) FROM dual;
This returns the latest date from the given dates.
8. TRUNC
Purpose: Truncates a date to a specified unit (e.g., day, month, year).
Syntax: TRUNC(date, 'format')
Example:
SQL>SELECT TRUNC(SYSDATE, 'MM') FROM dual;
This truncates the current date to the first day of the current month.
9. ROUND
Purpose: Rounds a date to a specified unit (e.g., day, month).
Syntax: ROUND(date, 'format')
Example:
SQL>SELECT ROUND(SYSDATE, 'MONTH') FROM dual;
This rounds the current date to the nearest month.
10. TO_CHAR
Purpose: Converts a date to a string format.
Syntax: TO_CHAR (date, 'format')
Example:
SQL>SELECT TO_CHAR (SYSDATE, 'YYYY-MM-DD') FROM dual;
This converts the current date to a string in the format YYYY-MM-DD.
11. TO_DATE
Purpose: Converts a string to a date.
Syntax: TO_DATE (string, 'format')
Example:
SQL>SELECT TO_DATE ('2025-02-10', 'YYYY-MM-DD') FROM dual;
This converts the string '2025-02-10' into a date.
R23_DBMS LAB Programs - 5
5.
I) create a simple PL/SQL Program which includes declaration section, executable section and exception-
Handling section (Ex. Student Marks can be selected from the table and printed for those who secured
first class and an exception can be raised if no records were found).
II) Insert Data into student table and use COMMIT, ROLLBACK and SAVEPOINT in PL/SQL block.
DESCRIPTION:
PL/SQL:
PL/SQL is a block structured language. The programs of PL/SQL are logical blocks that
can contain any number of nested sub-blocks. Pl/SQL stands for "Procedural Language extension
of SQL" that is used in Oracle.
Typically, each block performs a logical action in the program. A block has the following
structure:
DECLARE
Declaration statements;
BEGIN
Executable statements
EXCEPTIONS
Exception handling statements
END;
Declare section starts with DECLARE keyword in which variables, constants, records as
cursors can be declared which stores data temporarily. It basically consists definition of
PL/SQL identifiers. This part of the code is optional.
Execution section starts with BEGIN and ends with END keyword. This is a mandatory
section and here the program logic is written to perform any task like loops and conditional
statements. It supports all DML commands, DDL commands and SQL*PLUS built-in
functions as well.
Exception section starts with EXCEPTION keyword. This section is optional which
contains statements that are executed when a run-time error occurs. Any exceptions can be
handled in this section.
SQL QUERIES
i) we have to create the student table and insert the records in to the table as follows:
PL/SQL CODE:
SQL>ed 5a
Enter the following code into the text editor and save the file with .sql format
set serveroutput on;
DECLARE
temp1 number(10);
temp2 varchar2 (10);
BEGIN
Select sid,sname into temp1,temp2 from student where rank='first';
dbms_output.put_line('Student No:'|| temp1 ||' Name:'||temp2||' got first rank');
Exception when no_data_found then
dbms_output.put_line ('********************************************');
dbms_output.put_line('# Error: there is no student got first rank');
END;
/
SQL> @5a;
**********************************
**********
# Error: there is no student got first rank
SQL> @5a
Student No:503 Name:Ramu got first rank
PL/SQL CODE:
SQL>ed 5b
Enter the following code into the text editor and save the file with .sql format
SQL> @5b
Enter value for sno: 504
Old 7 : Sno: = &sno;
New 7 : Sno: = 504;
Enter value for name: Naresh
Old 8: Name: = '&name';
New 8: Name: = 'Naresh';
Enter value for srank: first
Old 9: Srank: = '&srank';
New 9: Srank: = 'first';
One record inserted
6. Develop a Program that includes the features NESTED IF, CASE and CASE Expression.
The Program can be extended using the NULLIF and COALESCE functions.
A. NESTED IF:
A nested if-then is an if statement that is the target of another if statement. Nested if -then
statements mean an if statement inside another if statement
Syntax:-
if (condition1) then
-- Executes when condition1
is true if (condition2) then
-- Executes when condition2
is true end if;
end if;
PL/SQL CODE: PL/SQL Program to find biggest of three number using nested
if. SQL>ed 6a
Enter the following code into the text editor and save the file with .sql format
Declare
a number:=10;
b number:=12;
c number:=5;
begin
dbms_output.put_line('a='||a||' b='||b||' c='||c); if a>b AND a>c then
dbms_output.put_line('a is greatest');
else
if b>a AND b>c then
dbms_output.put_line('b is greatest');
else
dbms_output.put_line('c is greatest');
end if;
end if;
end;
/
SQL> @6a
a=10 b=12 c=5
b is greatest
CASE statement selects one sequence of statements to execute. However, to select the
sequence, the CASE statement uses a selector rather than multiple Boolean expressions.
A selector is an expression, the value of which is used to select one of several
alternatives.
Syntax:
CASE selector
WHEN 'value1' THEN S1;
WHEN 'value2' THEN S2;
WHEN 'value3' THEN S3;
...
ELSE Sn; -- default case
END CASE;
SQL> create table emp(eno number(5), ename varchar2(10), loc varchar(10), salary
number(10,2));
Table created.
SQL> insert into emp values (101,'ali','vja', 15000);
1 row created.
SQL> insert into emp values (102,'ravi','hyd', 25000);
1 row created.
SQL> insert into emp values (103,'raju','gnt', 35000);
1 row created.
SQL> insert into emp values (104,'rakesh','vja', 45000);
1 row created.
SQL> select *from emp;
vja 17000
hyd 26000
gnt 35000
vja 47000
PL/SQL CODE: PL/SQL CODE to demonstrate CASE
SQL> ed 6b
SQL> @6b
Enter value for grade: c
old 4: grade:='&grade';
new 4: grade:='c'; good
Example:
SQL> select ename, nullif('ali','ali1') from emp;
ENAME NUL
ali ali
ravi ali
raju ali
rakesh ali
ali
ravi
raju
rakesh
D. COALESCE: COALESCE () function accepts a list of arguments and returns the first one that
evaluates to a non-null value.
Syntax: coalesce ("expression1","expression2",...);
Example:
SQL> select coalesce (NULL,'CRRCOE','IT') from dual;
COALE
--------
CRRCOE
R23_DBMS LAB Program – 7
7. Program development using WHILE LOOPS, numeric FOR LOOPS, nested loops using
ERROR Handling, BUILT –IN Exceptions, USE defined Exceptions, RAISE- APPLICATION
ERROR.
AIM: Program development using WHILE LOOPS, numeric FOR LOOPS, nested loops using
ERROR Handling, BUILT –IN Exceptions, USE defined Exceptions, RAISEAPPLICATION ERROR.
WHILE LOOP: A WHILE LOOP statement in PL/SQL programming language repeatedly executes
a target statement as long as a given condition is true.
Syntax:
WHILE condition LOOP
sequence_of_statements
END LOOP;
PL/SQL Code: A PL/SQL Program to find sum of ODD number upto given number using While loop
SQL> ed 7a
SQL> @7a
Enter value for endval: 100
Old 7: endval: =&endval;
New 7 : endval: =100;
Sum of odd numbers between 1 and 100 is 2500
FOR Loop: A FOR LOOP is a repetition control structure that allows us to efficiently write a
loop that needs to execute a specific number of times.
Syntax
FOR counter IN initial_value .. final_value
LOOP sequence_of_statements;
END LOOP;
PL/SQL CODE: A PL/SQL code to print multiplication table using for loop
SQL> ed 7b
SQL> @7b
Enter value for var1: 2
Old 6: VAR1:=&VAR1;
New 6 : VAR1:=2;
Enter numer to print multiplication table 2X1=2
2X2=4
2X3=6
2X4=8
2X5=10
2X6=12
2X7=14
2X8=16
2X9=18
2X10=20
NESTED LOOP: PL/SQL allows using one loop inside another loop. It may be either basic, while or
for loop.
Syntax:
WHILE condition1 LOOP sequence_of_statements1
WHILE condition2 LOOP sequence_of_statements2
END LOOP;
END LOOP;
PL/SQL CODE: A PL/SQL program to print n prime number using nested loop.
SQL> ed 7c
Set Serveroutput on
DECLARE
i number(3);
j number(3);
BEGIN
i := 2;
LOOP
j:= 2;
LOOP
exit WHEN ((mod(i, j) = 0) or (j = i));
j := j +1;
END LOOP;
IF (j = i ) THEN
dbms_output.put_line(i || ' is prime');
END IF;
i := i + 1;
exit WHEN i = 50;
END LOOP;
END;
/
SQL> @7c
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
Description:
Procedures in SQL:
SQL procedures, also known as stored procedures, are precompiled SQL code that can be
executed multiple times without rewriting the entire SQL query. They help in improving
performance, managing tasks, and organizing code.
1. Create Procedure: You use CREATE PROCEDURE to define a procedure. For example:
2. Execute Procedure: Once created, you can call it with the EXEC command:
EXEC MyProcedure;
3. Parameters in Procedures: Procedures can accept input parameters to make them dynamic:
5. Delete Procedure: Procedures can be removed with the DROP PROCEDURE statement:
SQL> ed findname
SQL> ed pro8
SQL> @pro8
SQL> @pro8
Aim: A Program t o development using creation of stored functions, invoke functions in SQL
Statements and writing complex functions.
Description:
Stored Functions:
In SQL, a stored function is a database object that allows you to store reusable logic in the
database.
It is similar to a stored procedure but with a key difference: a function returns a value (while a
stored procedure does not).
Functions can be called from queries just like a regular expression, and can be used in SELECT,
WHERE, and other clauses.
Return Value: A stored function always returns a value. It can return a scalar value (e.g.,
INTEGER, VARCHAR, and DATE) or a table (in some databases).
Reusable Logic: Functions allow you to encapsulate complex logic and reuse it across
multiple queries.
Called from SQL Queries: Functions can be called directly in SQL expressions.
Suppose you want to create a function that calculates the square of a number. Here's how you
might write that:
Now, you can use the calculate_square function in your SQL queries:
You can also create functions with multiple parameters. For example, a function to calculate the
area of a rectangle:
Invoke Functions:
Invoking functions in SQL statements allows you to reuse logic and streamline data operations
efficiently.
SELECT function_name(parameters);
SQL Queries:
PL/SQL Code:
SQL> @getname
Function created.
SQL> ed pro9
SQL> @pro9
Enter value for deptno: 1001
old 5: deptno2:=&deptno;
new 5: deptno2:=1001;
declare
*
ERROR at line 1:
ORA-20100: Your entered Department number is not exists
ORA-06512: at "SYSTEM.GETNAME", line 9
ORA-06512: at line 6
Week 10
Aim: To develop programs using features parameters in a CURSOR, FOR UPDATE CURSOR, and
WHERE CURRENT of clause and CURSOR variables.
Description:
Cursors:
A cursor is a pointer to this context area.
PL/SQL controls the context area through a cursor.
A cursor holds the rows (one or more) returned by a SQL statement.
The set of rows the cursor holds is referred to as the active set.
Types of Cursors:
There are two types of cursors
1. Implicit Cursors
2. Explicit Cursors
1. Implicit Cursors:
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when there
is no explicit cursor for the statement.
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always has attributes
such as %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT.
The SQL cursor has additional attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS, designed
for use with the FORALL statement.
2. Explicit Cursors:
Explicit cursors are programmer-defined cursors for gaining more control over the context Area. An explicit
cursor should be defined in the declaration section of the PL/SQL Block.
Syntax:
CURSOR cursor_name IS select_statement;
Declaring the cursor defines the cursor with a name and the associated SELECT statement.
Syntax:
CURSOR c_customers IS
SELECT id, name, address FROM customers;
Opening the cursor allocates the memory for the cursor and makes it ready for fetching the rows returned
by the SQL statement into it.
Syntax:
OPEN c_customers;
SQL Queries:
4 rows selected.
Pl/SQL Code:
SQL> ed pro10
DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/
SQL> @pro10
1 Naresh Tirupati
2 Deepika Madanapalli
3 Dharani Raychoti
4 saikeerthi Kavali
Develop Programs using BEFORE and AFTER Triggers, Row and Statement Triggers and
INSTEAD OF Triggers
DESCRITION
Triggers in PL/SQL:
Triggers in oracle are blocks of PL/SQL code which oracle engine can execute
automatically based on some action or event.
These events can be:
DDL statements (CREATE, ALTER, DROP, TRUNCATE)
DML statements (INSERT, SELECT, UPDATE, DELETE)
Database operation like connecting or disconnecting to oracle (LOGON, LOGOFF,
SHUTDOWN)
Triggers are automatically and repeatedly called upon by oracle engine on satisfying certain
condition.
Triggers can be activated or deactivated depending on the requirements.
If triggers are activated then they are executed implicitly by oracle engine and if triggers are
deactivated then they are executed explicitly by oracle engine.
Level Triggers
There are 2 different types of level triggers, they are:
ROW LEVEL TRIGGERS
It fires for every record that got affected with the execution of DML statements like
INSERT, UPDATE, DELETE etc.
It always use a FOR EACH ROW clause in a triggering statement.
STATEMENT LEVEL TRIGGERS
It fires once for each statement that is executed.
Event Triggers
There are 3 different types of event triggers, they are:
DDL EVENT TRIGGER
It fires with the execution of every DDL statement(CREATE, ALTER, DROP,
TRUNCATE).
DML EVENT TRIGGER
It fires with the execution of every DML statement(INSERT, UPDATE, DELETE).
DATABASE EVENT TRIGGER
It fires with the execution of every database operation which can be LOGON, LOGOFF,
SHUTDOWN, SERVERERROR etc.
Timing Triggers
There are 2 different types of timing triggers, they are:
BEFORE TRIGGER
It fires before executing DML statement.
Triggering statement may or may not executed depending upon the before condition block.
AFTER TRIGGER
It fires after executing DML statement.
SQL Queries:
PL/SQL Code for creation of trigger while insert / update records into a table.
SQL>ed pro11
SQL> @pro11
Trigger created.
Create a table and perform the search operation on table using indexing and non-
indexing techniques.
SQL> Create Table Teacher(Staff_Id Varchar2(4) Primary Key, Staff_Name Varchar2(30), Qualification
Varchar2(10), Hiredate Date, Job Varchar2(30), Address Varchar2(15), Ph_Num Number(10), Salary
Number(7, 2), Department Varchar2(10));
Table created.