Unit-3 DBMS Notes
Unit-3 DBMS Notes
Unit-3 DBMS Notes
SQL
o SQL stands for Structured Query Language. It is used for storing and
managing data in relational database management system (RDMS).
o It is a standard language for Relational Database System. It enables a user to
create, read, update and delete relational databases and tables.
o All the RDBMS like MySQL, Informix, Oracle, MS Access and SQL Server use
SQL as their standard database language.
o SQL allows users to query the database in a number of ways, using English-like
statements.
Rules:
SQL follows the following rules:
o Structure query language is not case sensitive. Generally, keywords of SQL are
written in uppercase.
o Statements of SQL are dependent on text lines. We can use a single SQL
statement on one or multiple text line.
o Using the SQL statements, you can perform most of the actions in a
database. o SQL depends on tuple relational calculus and relational algebra.
SQL process:
8. When an SQL command is executing for any RDBMS, then the system figure out
the best way to carry out the request and the SQL engine determines that how
to interpret the task.
9. In the process, various components are included. These components can
be optimization Engine, Query engine, Query dispatcher, classic, etc.
10. All the non-SQL queries are handled by the classic query engine, but SQL query
engine won't handle logical files.
Characteristics of SQL
o SQL is easy to learn.
o SQL is used to access data from relational database management
systems. o SQL can execute queries against the database.
o SQL is used to describe the data.
o SQL is used to define the data in the database and manipulate it when needed.
o SQL is used to create and drop the database and table.
o SQL is used to create a view, stored procedure, function in a database.
o SQL allows users to set permissions on tables, procedures, and views.
next →← prev
Advantages of SQL
There are the following advantages of SQL:
High speed
Using the SQL queries, the user can quickly and efficiently retrieve a large amount of
records from a database.
No coding needed
In the standard SQL, it is very easy to manage the database system. It doesn't require a
substantial amount of code to manage the database system.
Portability
SQL can be used in laptop, PCs, server and even some mobile phones.
Interactive language
SQL is a domain language used to communicate with the database. It is also used
to receive answers to the complex questions in seconds.
Multiple data view
Using the SQL language, the users can make different views of the database structure.
SQL Datatype
o SQL Datatype is used to define the values that a column can contain.
o Every column is required to have a name and data type in the database table.
Datatype of SQL:
1. Binary Datatypes
There are Three types of binary Datatypes which are given below:
Data Description
type
Data Description
type
Datatype Description
timestamp It stores the year, month, day, hour, minute, and the
second value.
SQL Commands
o SQL commands are instructions. It is used to communicate with the database.
It is also used to perform specific tasks, functions, and queries of data.
o SQL can perform various tasks like create a table, add data to tables, drop the
table, modify the table, set permission for users.
11. CREATE
12. ALTER
13. DROP
14. TRUNCATE
Syntax:
Syntax
5. DROP TABLE
; Example
Syntax:
d. TRUNCATE: It is used to delete all the rows from the table and free the space
containing the table.
Syntax:
o TRUNCATE TABLE
table_name; Example:
3. INSERT
4. UPDATE
5. DELETE
a. INSERT: The INSERT statement is a SQL query. It is used to insert data into the
row of a table.
Syntax:
For example:
Syntax:
2. UPDATE students
3. SET User_Name = 'Sonoo'
Syntax:
o Grant
o Revoke
database. Example
Example
o COMMIT o
ROLLBACK o
SAVEPOINT
a. Commit: Commit command is used to save all the transactions to the database.
Syntax:
1. COMMIT;
Example:
o COMMIT;
b. Rollback: Rollback command is used to undo transactions that have not already
been saved to the database.
Syntax:
o
ROLLBACK
; Example:
o ROLLBACK;
c. SAVEPOINT: It is used to roll the transaction back to a certain point without
rolling back the entire transaction.
Syntax:
o SAVEPOINT SAVEPOINT_NAME;
o SELECT
Syntax:
o SELECT expressions
o FROM TABLES
o WHERE conditions;
For example:
o SELECT emp_name
o FROM employee
SQL Operator
There are various types of SQL operator:
Operator Description
SQL Table
o SQL Table is a collection of data which is organized in terms of rows and columns.
In DBMS, the table is known as relation and row as a tuple.
o Table is a simple form of data storage. A table is also considered as a convenient
representation of relations.
Operation on Table
o Create table
o Drop table o
Delete table o
Rename table
Syntax
19. ...
20. "columnN" "data type");
Example
17. );
If you create the table successfully, you can verify the table by looking at the message
by the SQL server. Else you can use DESC command as follows:
Now you have an EMPLOYEE table in the database, and you can use the
stored information related to the employees.
Drop table
A SQL drop table is used to delete a table definition and all the data from a table.
When this command is executed, all the information available in the table is lost
forever, so you have to very careful while using this command.
Syntax
Firstly, you need to verify the EMPLOYEE table using the following command:
This table shows that EMPLOYEE table is available in the database, so we can drop it
as follows:
o SQL>DROP TABLE EMPLOYEE;
Now, we can check whether the table exists or not using the following command:
Syntax
Washington
5 Robert 9367238263 350000
If you don't specify the WHERE condition, it will remove all the rows from the table.
Syntax
Here, the expression is the field name of the table that you want to select data from.
Use the following syntax to select all the fields available in the table:
EMPLOYEE
To fetch the EMP_ID of all the employees, use the following query:
EMPLOYEE; Output
EMP_ID
EMP_NAME SALARY
Kristen 150000
Russell 200000
Angelina 600000
Robert 350000
Christian 260000
To fetch all the fields from the EMPLOYEE table, use the following query:
o SELECT * FROM
EMPLOYEE Output
Sample Table
EMPLOYEE
EMP_ID EMP_NAME CITY SALARY AGE
Syntax
Query
22. INSERT INTO EMPLOYEE VALUES (6, 'Marry', 'Canada', 600000, 48);
Output: After executing this query, the EMPLOYEE table will look like:
Syntax
Query
Syntax
o UPDATE table_name
o SET column1 = value1, column2 = value2, ...
o WHERE condition;
Sample Table
EMPLOYEE
Syntax
o UPDATE table_name
o SET column_name = value
o WHERE condition;
Query
Output: After executing this query, the EMPLOYEE table will look like:
EMP_ID EMP_NAME CITY SALARY AGE
Syntax
Query
o UPDATE EMPLOYEE
o SET EMP_NAME = 'Kevin', City = 'Boston'
o WHERE EMP_ID = 5;
Output
Syntax
7. UPDATE table_name
8. SET column_name = value1;
Query
o UPDATE EMPLOYEE
o SET EMP_NAME = 'Harry';
Output
Syntax
Sample Table
EMPLOYEE
Query
Output: After executing this query, the EMPLOYEE table will look like:
EMP_ID EMP_NAME CITY SALARY AGE
Query
Output: After executing this query, the EMPLOYEE table will look like:
Syntax
25. DELETE * FROM table_name;
26. or
table_name; Query
Output: After executing this query, the EMPLOYEE table will look like:
Views in SQL
o Views in SQL are considered as a virtual table. A view also contains rows
and columns.
o To create the view, we can select the fields from one or more tables present
in the database.
o A view can either have specific rows based on certain condition or all the rows
of a table.
Sample table:
Student_Detail
1 Stephan Delhi
2 Kathrin Noida
3 David Ghaziabad
4 Alina Gurugram
Student_Marks
1 Stephan 97 19
2 Kathrin 86 21
3 David 74 18
4 Alina 90 20
5 John 96 18
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:
o FROM table_name
o WHERE condition;
Query:
NAME ADDRESS
Stephan Delhi
Kathrin Noida
David Ghaziabad
3. Creating View from multiple tables
View from multiple tables can be created by simply include multiple tables in the
SELECT statement.
Query:
Stephan Delhi 97
Kathrin Noida 86
David Ghaziabad 74
Alina Gurugram 90
4. Deleting View
A view can be deleted using the Drop View statement.
Syntax
SQL Index
o Indexes are special lookup tables. It is used to retrieve data from the
database very fast.
o An Index is used to speed up select queries and where clauses. But it shows
down the data input with insert and update statements. Indexes can be created
or dropped without affecting the data.
o An index in a database is just like an index in the back of a book.
o For example: When you reference all pages in a book that discusses a certain
topic, you first have to refer to the index, which alphabetically lists all the topics
and then referred to one or more specific page numbers.
Syntax
value. Syntax
Syntax
Important Rule:
o A subquery can be placed in a number of SQL clauses like WHERE clause, FROM
clause, HAVING clause.
o You can use Subquery with SELECT, UPDATE, INSERT, DELETE statements along
with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
o 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.
o Subqueries are on the right side of the comparison
operator. o A subquery is enclosed in parentheses.
o 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.
Syntax
o SELECT column_name
o FROM table_name
Example
1 John 20 US 2000.00
4 Alina 29 UK 6500.00
33. SELECT *
34. FROM EMPLOYEE
4 Alina 29 UK 6500.00
Syntax:
o FROM table_name
o WHERE VALUE OPERATOR
Example
Now use the following syntax to copy the complete EMPLOYEE table into
the EMPLOYEE_BKP table.
Syntax
o UPDATE table
o SET column_name = new_value
o FROM TABLE_NAME
o WHERE condition);
Example
8. UPDATE EMPLOYEE
9. SET SALARY = SALARY * 0.25
This would impact three rows, and finally, the EMPLOYEE table would have the
following records.
1 John 20 US 2000.00
4 Alina 29 UK 1625.00
5 Kathrin 34 Bangalore 2125.00
Syntax
o (SELECT COLUMN_NAME
o FROM TABLE_NAME
o WHERE condition);
Example
This would impact three rows, and finally, the EMPLOYEE table would have the
following records.
1 John 20 US 2000.00
SQL Clauses
The following are the various SQL clauses:
1. GROUP BY
o SQL GROUP BY statement is used to arrange identical data into groups. The
GROUP BY statement is used with the SQL SELECT statement.
o The GROUP BY statement follows the WHERE clause in a SELECT statement
and precedes the ORDER BY clause.
o The GROUP BY statement is used with aggregation function.
Syntax
o SELECT column
o FROM table_name
o WHERE conditions
o GROUP BY column
o ORDER BY column
Sample table:
PRODUCT_MAST
PRODUCT COMPANY QTY RATE COST
Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Cpm1 3 25 75
Item8 Com1 3 10 30
Item9 Com2 2 25 50
Example:
Output:
Com1 5
Com2 3
Com3 2
2. HAVING
33. HAVING clause is used to specify a search condition for a group or an aggregate.
34. Having is used in a GROUP BY clause. If you are not using GROUP BY clause
then you can use HAVING function like a WHERE clause.
Syntax:
o WHERE conditions
o GROUP BY column1, column2
o HAVING conditions
o ORDER BY column1, column2;
Example:
Output:
Com1 5
Com2 3
3. ORDER BY
o The ORDER BY clause sorts the result-set in ascending or descending order.
o It sorts the records in ascending order by default. DESC keyword is used to sort
the records in descending order.
Syntax:
Where
CUSTOMER
12 Kathrin US
23 David Bangkok
34 Alina Dubai
45 John UK
56 Harry US
o SELECT *
o FROM CUSTOMER
o ORDER BY NAME;
Output:
34 Alina Dubai
23 David Bangkok
56 Harry US
45 John UK
12 Kathrin US
Example: Sorting Results in Descending Order
Using the above CUSTOMER table
11. SELECT *
12. FROM CUSTOMER
Output:
12 Kathrin US
45 John UK
56 Harry US
23 David Bangkok
34 Alina Dubai
1. COUNT FUNCTION
o COUNT function is used to Count the number of rows in a database table. It can
work on both numeric and non-numeric data types.
o COUNT function uses the COUNT(*) that returns the count of all the rows in
a specified table. COUNT(*) considers duplicate and Null.
Syntax
41. COUNT(*)
42. or
PRODUCT_MAST
Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Cpm1 3 25 75
Item8 Com1 3 10 30
Item9 Com2 2 25 50
Example: COUNT()
10
Example: COUNT with WHERE
o SELECT COUNT(*)
o FROM PRODUCT_MAST;
o WHERE RATE>=20;
Output:
7
Example: COUNT() with DISTINCT
3
Example: COUNT() with GROUP BY
o GROUP BY COMPANY;
Output:
Com1 5
Com2 3
Com3 2
Example: COUNT() with HAVING
Com1 5
Com2 3
2. SUM Function
Sum function is used to calculate the sum of all selected columns. It works on numeric
fields only.
Syntax
o SUM()
o or
670
Example: SUM() with WHERE
o SELECT SUM(COST)
o FROM PRODUCT_MAST
o WHERE QTY>3;
Output:
320
6. SELECT SUM(COST)
7. FROM PRODUCT_MAST
8. WHERE QTY>3
9. GROUP BY COMPANY;
Output:
Com1 150
Com2 170
Example: SUM() with HAVING
o GROUP BY COMPANY
o HAVING SUM(COST)>=170;
Output:
Com1 335
Com3 170
3. AVG function
The AVG function is used to calculate the average value of the numeric type.
AVG function returns the average of all non-Null values.
Syntax
6. AVG()
7. or
5. SELECT AVG(COST)
6. FROM PRODUCT_MAST;
Output:
67.00
4. MAX Function
MAX function is used to find the maximum value of a certain column. This
function determines the largest value of all selected values of a column.
Syntax
o MAX()
o or
o SELECT MAX(RATE)
o FROM PRODUCT_MAST;
30
5. MIN Function
MIN function is used to find the minimum value of a certain column. This function
determines the smallest value of all selected values of a column.
Syntax
o MIN()
o or
5. SELECT MIN(RATE)
6. FROM PRODUCT_MAST;
Output:
10
SQL JOIN
As the name shows, JOIN means to combine something. In case of SQL, JOIN means "to
combine two or more tables".
In SQL, JOIN clause is used to combine the records from two or more tables in a
database.
Sample Table
EMPLOYEE
PROJECT
101 1 Testing
102 2 Development
103 3 Designing
104 4 Development
1. INNER JOIN
In SQL, INNER JOIN selects records that have matching values in both tables as long
as the condition is satisfied. It returns the combination of all rows from both the tables
where the condition satisfies.
Syntax
Query
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
2. LEFT JOIN
The SQL left join returns all the values from left table and the matching values from the
right table. If there is no matching join value, it will return NULL.
Syntax
Query
o SELECT EMPLOYEE.EMP_NAME,
PROJECT.DEPARTMENT o FROM EMPLOYEE
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Marry NULL
3. RIGHT JOIN
In SQL, RIGHT JOIN returns all the values from the values from the rows of right table
and the matched values from the left table. If there is no matching in both tables, it
will return NULL.
Syntax
Query
o SELECT EMPLOYEE.EMP_NAME,
PROJECT.DEPARTMENT o FROM EMPLOYEE
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
4. FULL JOIN
In SQL, FULL JOIN is the result of a combination of both left and right outer join. Join
tables have all the records from both tables. It puts NULL on the place of matches
not found.
Syntax
Query
o SELECT EMPLOYEE.EMP_NAME,
PROJECT.DEPARTMENT o FROM EMPLOYEE
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Marry NULL
1. Union
o The SQL Union operation is used to combine the result of two or more
SQL SELECT queries.
o 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.
o The union operation eliminates the duplicate rows from its resultset.
Syntax
48. SELECT column_name FROM table1
49. UNION
table2; Example:
ID NAME
1 Jack
2 Harry
3 Jackson
ID NAME
3 Jackson
4 Stephan
5 David
ID NAME
1 Jack
2 Harry
3 Jackson
4 Stephan
5 David
2. Union All
Union All operation is equal to the Union operation. It returns the set without removing
duplication and sorting the data.
Syntax:
ID NAME
1 Jack
2 Harry
3 Jackson
3 Jackson
4 Stephan
5 David
3. Intersect
o It is used to combine two SELECT statements. The Intersect operation returns
the common rows from both the SELECT statements.
o In the Intersect operation, the number of datatype and columns must be the
same.
o It has no duplicates and it arranges the data in ascending order by default.
Syntax
table2; Example:
ID NAME
3 Jackson
4. Minus
16. 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.
17. It has no duplicates and data arranged in ascending order by default.
Syntax:
table2; Example
ID NAME
1 Jack
2 Harry
What is 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. PL/SQL is integrated with Oracle
database (since version 7). The functionalities of PL/SQL usually extended after each
release of Oracle database. Although PL/SQL is closely integrated with SQL language,
yet it adds some programming constraints that are not available in SQL.
PL/SQL Functionalities
PL/SQL includes procedural language elements like conditions and loops. It allows
declaration of constants and variables, procedures and functions, types and variable of
those types and triggers. It can support Array and handle exceptions (runtime errors).
After the implementation of version 8 of Oracle database have included features
associated with object orientation. You can create PL/SQL units like procedures,
functions, packages, types and triggers, etc. which are stored in the database for reuse
by applications.
With PL/SQL, you can use SQL statements to manipulate Oracle data and flow of
control statements to process the data.
The PL/SQL is known for its combination of data manipulating power of SQL with
data processing power of procedural languages. It inherits the robustness, security,
and portability of the Oracle Database.
PL/SQL is not case sensitive so you are free to use lower case letters or upper case
letters except within string and character literals. A line of PL/SQL text contains
groups of characters known as lexical units. It can be classified as follows:
o Delimeters
o Identifiers o
Literals
o Comments
PL/SQL Variables
A variable is a meaningful name which facilitates a programmer to store data
temporarily during the execution of code. It helps you to manipulate data in
PL/SQL programs. It is nothing except a name given to a storage area. Each
variable in the PL/SQL has a specific data type which defines the size and layout of
the variable's memory.
A variable should not exceed 30 characters. Its letter optionally followed by more letters,
dollar signs, numerals, underscore etc.
You can also specify NOT NULL constraint to avoid NULL value. If you specify the
NOT NULL constraint, you must assign an initial value for that variable.
o DECLARE
o a integer := 30;
o b integer := 40;
o c integer;
o f real;
o BEGIN
o c := a + b;
o dbms_output.put_line('Value of c: ' || c);
o f := 100.0/3.0;
o dbms_output.put_line('Value of f: ' || f);
o END;
28. Value of c: 70
29. Value of f: 33.333333333333333333
30.
31. PL/SQL procedure successfully completed.
o Local Variable: Local variables are the inner block variables which are not
accessible to outer blocks.
o Global Variable: Global variables are declared in outermost block.
27. DECLARE
28. -- Global variables
31. BEGIN
32. dbms_output.put_line('Outer Variable num1: ' || num1);
41. END;
42. END;
43. /
o
o PL/SQL procedure successfully completed.
PL/SQL If
PL/SQL supports the programming language features like conditional statements
and iterative statements. Its programming constructs are similar to how you use in
programming languages like Java and C++.
o IF condition
o THEN
This syntax is used when you want to execute statements only when condition is TRUE.
o IF condition
o THEN
This syntax is used when you want to execute one set of statements when condition is
TRUE or a different set of statements when condition is FALSE.
57. THEN
58. {...statements to execute when condition2 is TRUE...}
This syntax is used when you want to execute one set of statements when condition1
is TRUE or a different set of statements when condition2 is TRUE.
46. IF condition1
47. THEN
50. THEN
51. {...statements to execute when condition2 is TRUE...}
52. ELSE
53. {...statements to execute when both condition1 and condition2 are FALSE...}
It is the most advance syntax and used if you want to execute one set of statements
when condition1 is TRUE, a different set of statement when condition2 is TRUE or a
different set of statements when both the condition1 and condition2 are FALSE.
PL/SQL Loop
The PL/SQL loops are used to repeat the execution of one or more statements for
specified number of times. These are also known as iterative control statements.
o LOOP
o Sequence of statements;
o END LOOP;
PL/SQL Loop
The PL/SQL loops are used to repeat the execution of one or more statements for
specified number of times. These are also known as iterative control statements.
o LOOP
o Sequence of statements;
o END LOOP;
o WHILE <condition>
o LOOP statements;
o END LOOP;
o DECLARE
o i INTEGER := 1;
o BEGIN
o WHILE i <= 10 LOOP
o DBMS_OUTPUT.PUT_LINE(i);
o i := i+1;
o END LOOP;
o END;
After the execution of the above code, you will get the following result:
10
Note: You must follow these steps while using PL/SQL WHILE Loop.
59. VAR1:=200;
60. VAR2:=1;
o END LOOP;
63. BEGIN
64. FOR k IN 1..10 LOOP
After the execution of the above code, you will get the following result:
1
2
9
10
Note: You must follow these steps while using PL/SQL WHILE Loop.
67. You don't need to declare the counter variable explicitly because it is
declared implicitly in the declaration section.
68. The counter variable is incremented by 1 and does not need to be incremented
explicitly.
69. You can use EXIT WHEN statements and EXIT statements in FOR Loops but it
is not done often.
o BEGIN
o VAR1:=10;
o DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);
o END LOOP;
o END;
Output:
10
20
30
40
50
60
70
80
90
100
34. BEGIN
35. VAR1:=10;
40. END;
Output:
100
90
80
70
60
50
40
30
20
10
PL/SQL Procedure
The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one
or more specific tasks. It is just like procedures in other programming languages.
o Header: The header contains the name of the procedure and the parameters or
variables passed to the procedure.
o Body: The body contains a declaration section, execution section and exception
section similar to a general PL/SQL block.
How to pass parameters in procedure:
When you want to create a procedure or function, you have to define parameters .There
is three ways to pass parameters in procedure:
71. IS
72. [declaration_section]
73. BEGIN
74. executable_section
75. [EXCEPTION
76. exception_section]
Table creation:
Procedure Code:
o create or replace procedure
"INSERTUSER" o (id IN NUMBER,
o name IN VARCHAR2)
o is
o begin
o insert into user values(id,name);
o end;
o/
Output:
Procedure created.
41. BEGIN
42. insertuser(101,'Rahul');
45. /
Now, see the "USER" table, you will see one record is inserted.
ID Name
101 Rahul
PL/SQL Function
The PL/SQL Function is very similar to PL/SQL Procedure. The main difference between
procedure and a function is, a function must always return a value, and on the other
hand a procedure may or may not return a value. Except this, all the other things
of PL/SQL procedure are true for PL/SQL function too.
Here:
73. is
74. n3 number(8);
75. begin
76. n3 :=n1+n2;
79. /
Now write another program to call the function.
o DECLARE
o n3 number(2);
o BEGIN
o n3 := adder(11,22);
o /
Output:
Addition is: 33
Statement processed.
0.05 seconds
PL/SQL Cursor
When an SQL statement is processed, Oracle creates a memory area known as context
area. A cursor is a pointer to this context area. It contains all information needed for
processing the statement. In PL/SQL, the context area is controlled by Cursor. A
cursor contains information on a select statement and the rows of data accessed by it.
A cursor is used to referred to a program to fetch and process the rows returned by the
SQL statement, one at a time. There are two types of cursors:
o Implicit Cursors
o Explicit Cursors
These are created by default to process the statements when DML statements
like INSERT, UPDATE, DELETE etc. are executed.
Orcale provides some attributes known as Implicit cursor's attributes to check the
status of DML operations. Some of them are: %FOUND, %NOTFOUND, %ROWCOUNT
and %ISOPEN.
For example: When you execute the SQL statements like INSERT, UPDATE, DELETE
then the cursor attributes tell whether any rows are affected and how many have been
affected. If you run a SELECT INTO statement in PL/SQL block, the implicit cursor
attribute can be used to find out whether any row has been returned by the SELECT
statement. It will return an error if there no data is selected.
The following table soecifies the status of the cursor with each of its attribute.
Attribute Description
Let's execute the following program to update the table and increase salary of each
customer by 5000. Here, SQL%ROWCOUNT attribute is used to determine the number
of rows affected:
Create procedure:
o DECLARE
o total_rows number(2);
o BEGIN
o UPDATE customers
o dbms_output.put_line('no customers
updated'); o ELSIF sql%found THEN
o total_rows := sql%rowcount;
o dbms_output.put_line( total_rows || ' customers updated ');
o END IF;
o END;
o /
Output:
6 customers updated
PL/SQL procedure successfully completed.
Now, if you check the records in customer table, you will find that the rows are updated.
Steps:
You must follow these steps while working with an explicit cursor.
o Close cursor_name;
Let's take an example to demonstrate the use of explicit cursor. In this example, we
are using the already created CUSTOMERS table.
Execute the following program to retrieve the customer name and address.
18. DECLARE
19. c_id customers.id%type;
24. BEGIN
25. OPEN c_customers;
26. LOOP
27. FETCH c_customers into c_id, c_name, c_addr;
32. END;
33. /
Output:
1 Ramesh Allahabad
2 Suresh Kanpur
3 Mahesh Ghaziabad
4 Chandan Noida
5 Alex Paris
6 Sunita Delhi
PL/SQL procedure successfully completed.
PL/SQL Trigger
Trigger is invoked by Oracle engine automatically whenever a specified event
occurs.Trigger is stored into database and invoked repeatedly, when specific
condition match.
Triggers are stored programs, which are automatically executed or fired when
some event occurs.
Triggers could be defined on the table, view, schema, or database with which the event
is associated.
Advantages of Triggers
These are the following advantages of Triggers:
Creating a trigger:
Syntax for creating trigger:
86. ON table_name
87. [REFERENCING OLD AS o NEW AS n]
90. DECLARE
91. Declaration-statements
92. BEGIN
93. Executable-statements
94. EXCEPTION
95. Exception-handling-statements
96. END;
Here,
Create trigger:
Let's take a program to create a row level trigger for the CUSTOMERS table that would fire
for INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This
trigger will display the salary difference between the old values and new values:
o DECLARE
o sal_diff number;
o BEGIN
o sal_diff := :NEW.salary - :OLD.salary;
o /
After the execution of the above code at SQL Prompt, it produces the following result.
Trigger created.
Use the following code to get the old salary, new salary and salary difference after
the trigger created.
48. DECLARE
49. total_rows number(2);
50. BEGIN
51. UPDATE customers
60. /
Output:
6 customers updated