SQL Often Referred to As Structured Query Language, Is A
1
INTRODUCTION TO STRUCTURED QUERY LANGUAGE(SQL)
SQL often referred to as Structured Query Language, is a database computer language designed for managing data in relational database management systems (RDBMS), and originally based upon relational algebra and calculus. Its scope includes data insert, query, update and delete, schema creation and modification, and data access control. SQL was one of the first commercial languages for Edgar F. Codd's relational model, as described in his influential 1970 paper, "A Relational Model of Data for Large Shared Data Banks". Despite not adhering to the relational model as described by Codd, it became the most widely used database language.
LANGUAGE ELEMENTS
The SQL language is sub-divided into several language elements, including:
Clauses, which are constituent components of statements and queries. (In some cases, these are optional.) Expressions, which can produce either scalar values or tables consisting of columns and rows of data. Predicates, which specify conditions that can be evaluated to SQL three-valued logic (3VL) or Boolean (true/false/unknown) truth values and which are used to limit the effects of statements and queries, or to change program flow. Queries, which retrieve the data based on specific criteria. This is the most important element of SQL. Statements, which may have a persistent effect on schemata and data, or which may control transactions, program flow, connections, sessions, or diagnostics. o SQL statements also include the semicolon (";") statement terminator. Though not required on every platform, it is defined as a standard part of the SQL grammar. Insignificant whitespace is generally ignored in SQL statements and queries, making it easier to format SQL code for readability.
Data types
Each column in an SQL table declares the type(s) that column may contain. ANSI SQL includes the following datatypes.
Character strings
CHARACTER(n) or CHAR(n) — fixed-width n-character string, padded with spaces as needed CHARACTER VARYING(n) or VARCHAR(n) — variable-width string with a maximum size of n characters NATIONAL CHARACTER(n) or NCHAR(n) — fixed width string supporting an international character set NATIONAL CHARACTER VARYING(n) or NVARCHAR(n) — variable-width NCHAR string
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 2
Bit strings
BIT(n) — an array of n bits BIT VARYING(n) — an array of up to n bits
Numbers
INTEGER and SMALLINT FLOAT, REAL and DOUBLE PRECISION NUMERIC(precision, scale) or DECIMAL(precision, scale)
SQL provides a function to round numerics or dates, called TRUNC (in Informix, DB2, PostgreSQL, Oracle and MySQL) or ROUND (in Informix, Sybase, Oracle, PostgreSQL and Microsoft SQL Server)[19]
Date and time
DATE — for date values (e.g., 2010-05-30) TIME — for time values (e.g., 14:55:37). The granularity of the time value is usually a tick (100 nanoseconds). TIME WITH TIME ZONE or TIMESTAMP — the same as TIME, but including details about the time zone in question. TIMESTAMP — This is a DATE and a TIME put together in one variable (e.g., 2010- 05-30 14:55:37). TIMESTAMP WITH TIME ZONE or TIMESTAMPTZ — the same as TIMESTAMP, but including details about the time zone in question.
Different types of commands in SQL: A).DDL commands: - To create a database objects B).DML commands: - To manipulate data of a database objects C).DQL command: - To retrieve the data from a database. D).DCL/DTL commands: - To control the data of a database…
THE ORACLE TABLE – DUAL DUAL is the table owned by SYS.SYS owns the data dictionary and DUAL is a part of the data dictionary.DUAL is a small oracle worktable, which consists of only one row and one column, and contains the value x in that column .Besides arithmetic calculations it also supports date retrieval and it’s formatting
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 3
ORACLE FUNCTIONS Oracle functions serve the purpose of manipulating data items and returning a result Functions are also capable of accepting user supplied variables or constants and operating on them Such variables or constants are called arguments. Any number of arguments (or no arguments at all) can be passed to a function in the following format: Function_name(argument1,argument2,………..) Oracle Functions can be clubbed together depending upon whether they operate on a single row or a group of rows retrieved from a table.Accordingly, functions an be classified as follows: Group Functions(Aggregate Functions) Functions that act on a set of values are called Group functions.For example, SUM is a function which calculates the total set of numbers.A group function returns a single result row for a group of queried rows. Scalar Functions(Single Row Functions) Functions that act on only one value at a time are called Scalar functions.For example ,Length relates to the String Data type .Functions can be classified corresponding to different data types as: String Functions : For String data type Numeric Functions : For Number data type Conversion Functions : For Conversion data type to another Date Functions : For Date data type
Additional Exercise-I Queries to facilitate acquaintance of Built-In Functions : Aggregate functions
AGGREGATE FUNCTIONS
1. AVG:Returns an average value of ‘n’, ignoring null values in a column.
Syntax: AVG ([| ] )
Example: SELECT AVG(CURBAL) “Average balance” FROM ACCT_MSTR;
2.MIN:Returns a minimum value of expr
Syntax: MIN([| ] )
Example : SELECT MIN(CURBAL) “Minimum balance” FROM ACCT_MSTR;
3.MAX:Returns a maximum value of expr.
Syntax: MAX([| ] )
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 4
Example: SELECT MAX(CURBAL) “Maximum balance” FROM ACCT_MSTR;
4.COUNT: Returns the number of rows where expr is not null.
Syntax: COUNT ([| ] )
Example : SELECT COUNT(ACCT_NO) “No of accounts” FROM ACCT_MSTR;
5.COUNT(*):Returns the number of rows in the table , including duplicates and those with nulls.
Syntax: COUNT(*)
Example: SELECT COUNT(*) “No of records” FROM ACCT_MSTR;
6. SUM:Returns the sum of the values of ‘n’.
Syntax: SUM([| ] )
Example: SELECT SUM(CURBAL) “Total Balance” FROM ACCT_MSTR;
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 5
Exercise-I Queries to facilitate acquaintance of Built-In Functions, String Functions, Numeric Functions, Date Functions and Conversion Functions.
A.NUMERIC FUNCTIONS 1.ABS:Returns the absolute value of ‘n’.
Syntax: ABS(n)
Example : SELECT ABS(-15) “Absolute” FROM DUAL;
2.POWER:Returns m raised to the n th power .n must be an integer, else an error is returned.
Syntax: POWER(m,n)
Example: SELECT POWER(3,2) “Raised” FROM DUAL;
3.ROUND:Returns n, rounded to m places to the right of a decimal point. If m is omitted, n is rounded to 0 places.m can be negative to round off digits to the left of the decimal point.m must be an integer.
Syntax:ROUND(n[,m])
Example: SELECT ROUND(15.19,1) “ROUND” FROM DUAL;
4.SQRT:Returns square root of n.If n<0, NULL.SQL reurns a real result.
Syntax: SQRT(n)
Example : SELECT SQRT(25) “Square Root” FROM DUAL;
5.EXP:Returns e raised to the n th power, where e=2.71828183.
Syntax: EXP(n) Example SELECT EXP(5) “Exponent” FROM DUAL;
6.GREATEST : Returns the greatest value in a list of expressions.
Syntax:
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 6
GREATEST(expr1,expr2,………….,expr_n) Where the expr1,expr2,………….,expr_n are expressions that are evaluated by the greatest function.
Example SELECT GREATEST (5,6,17) “num” FROM DUAL;
7.LEAST : Returns the LEAST value in a list of expressions.
Syntax: LEAST(expr1,expr2,………….,expr_n) Where the expr1,expr2,………….,expr_n are expressions that are evaluated by the LEAST function.
Example: SELECT LEAST (5,6,17) “num” FROM DUAL;
8.MOD:Returns the remainder of the first number divided by the second number passed a parameter . If the second number is zero , the result is the same as the first number.
Syntax: MOD(m,n)
Example : SELECT MOD(15,7) “RESULT” FROM DUAL;
9.FLOOR:Returns the largest integer value that is equal to or less than a number.
Syntax: FLOOR(n)
Example: SELECT FLOOR(24.8) “FLOOR” FROM DUAL;
10. CEIL: Returns the SMALLEST integer value that is equal to or greater than a number.
Syntax: CEIL(n)
Example: SELECT CEIL(24.8) “CEIL” FROM DUAL; STRING FUNCTIONS 1.LOWER:Returns char, with all letters in lowercase.
Syntax: LOWER(char)
Example:SELECT LOWER (‘DHANEKULA’) “Lower” FROM DUAL;
2.UPPER:Returns char, with all letters in uppercase.
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 7
Syntax:UPPER(char)
Example:SELECT UPPER (‘dhanekula’) “Upper” FROM DUAL;
3.SUBSTR:Returns a portion of characters, beginning at character m, and going upto character n. If n is omitted, the result returned is upto the last character in the string.The first position of the char is 1.
Syntax: SUBSTR(,,[]) Where < string> is the source string. is the position for extraction. The first position in the string is always 1. is the number of characters to extract.
Example SELECT SUBSTR(‘SECURE’,3,4) “Substring” FROM DUAL;
4. INSTR:Returns the location of a substring in a string. Syntax: INSTR(,(, [],[]) Where , is the string to search. is the substring to search for in string1. is the position in string1 where the search will start. If omitted , it defaults to 1. The first position in the string is 1. nth_appearance is the nth appearance of string2 .If omitted, it defaults to 1.
Example: SELECT INSTR(‘SCT on the net’,’t’) “instr” FROM DUAL;
5. LENGTH:Returns the length of a word.
Syntax: LENGTH(word)
Example: SELECT LENGTH(‘DHANEKULA’) “Length” FROM DUAL;
6. LTRIM:Removes characters from the left of char with initial characters removed upto the first character not in set.
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 8
Syntax: LTRIM(char,[set])
Example: SELECT LTRIM(‘NISHA’,’N’) “LTRIM” FROM DUAL;
7. RTRIM:Returns char, with final characters removed after the last character not in the set. ‘set’ is optional it defaults to spaces
Syntax: RTRIM(char,[set])
Example: SELECT RTRIM(‘SUNILA’,’A’) “RTRIM” FROM DUAL;
8. TRIM:Removes all specified characters either from the beginning or the ending of a string .
Syntax: Trim([leading|Trailing|both[ from ]] ) Where Leading – remove trim_string from the front of string1 Trailing – remove trim_string from the end of string1 Both – remove trim_string from the front and end string1 If none of the above option is chosen , it takes ‘Both’ Option.
Example: SELECT TRIM (‘ Hansel’) “Trim both sides” FROM DUAL
9. LPAD: Returns char1, left-padded to length n with the sequence of characters specified in CHAR2. if CHAR2 is not specified Oracle uses blanks by default.
Syntax: LPAD(char1, n,[,char2])
Example : SELECT LPAD(‘page 1’,10,’*’)”LPAD” from dual
10. RPAD: Returns char1, right-padded to length n with the characters specified in CHAR2. if CHAR2 is not specified Oracle uses blanks by default.
Syntax: RPAD(char1, n,[,char2])
Example: SELECT RPAD(‘page 1’,10,’*’) “RPAD” from dual DATE FUNCTIONS 1.ADD_MONTHS:Returns date after adding the number of months specified in the function
Syntax: ADD_MONTHS(d,n)
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 9
Example : SELECT ADD_MONTHS(SYSDATE,4) “Add months” FROM DUAL;
2.LAST_DAY: Returns the last date of the month specified with the function.
Syntax: LAST_DAY(d)
Example : SELECT SYSDATE,LAST_DAY(SYSDATE) “LAST DAY” FROM DUAL;
3.MONTHS_BETWEEN:Returns number of months between d1 and d2.
Syntax: MONTHS_BETWEEN (d1,d2)
Example: SELECT MONTHS_BETWEEN (’02-FEB-92’,’02-JAN-92’) “MONTHS” FROM DUAL;
4.NEXT_DAY:Returns the date of the first weekday named by char that is after the date named by date. char must be a day of the week. Syntax: NEXT_DAY (date,char) Example: SELECT NEXT_DAY(’06-JULY-02’,’Saturday’) “NEXT DAY” FROM DUAL; Conversion Functions 1.TO_NUMBER: Converts char, a CHARACTER value expressing a number, to a NUMBER data type.
Syntax: TO_NUMBER(char) Example: update acct_mstr set curbal=curbal + to_number(substr(‘$100’,2,3));
2. TO_CHAR(number conversion) : Converts a value of a NUMBER datatype to a character datatyp, using the optional format string. TO_CHAR() accepts a number (n) and a numeric format(fmt) in which the number has to appear. If fmt is omitted, n is converted to a char value exactly long enough to hold all significant igits.
Syntax: TO_CHAR(n[,fmt]) Example: select to_char(dt,’month dd,yyyy’) “new date format” from trans_mstr where trans_no=’t1’;
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 10
3.TO_DATE: Converts a character field to a date field Syntax : TO_DATE(char,[,fmt]) Example: insert into cust_mstr(cust_no,fname,mname,lname,dob_inc) Values(“c1’,’ivan’,’nelson’,’bayross’,to_date(’25-jun-1952 10:55 a.m.’,’dd- mon-hh:mi a.m’));
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 11
Exercise-II Queries using operators in SQL A. Arithmetic Operators Arithmetic operators manipulate numeric operands. The '-' operator is also used in date arithmetic. Supported arithmetic operators are listed in Table Operator Description Example + (unary) Makes operand positive SELECT +3 FROM DUAL; - (unary) Negates operand SELECT -4 FROM DUAL; / Division (numbers and dates) SELECT SAL / 10 FROM EMP; * Multiplication SELECT SAL * 5 FROM EMP; + Addition (numbers and dates) SELECT SAL + 200 FROM EMP; - Subtraction (numbers and SELECT SAL - 100 FROM dates) EMP;
B. Character Operators Character operators used in expressions to manipulate character strings are listed in Table Operator Description Example || Concatenates character SELECT 'The Name of the employee is: ' || ENAME strings FROM EMP;
C.Comparision operators Comparison operators used in conditions that compare one expression with another are listed in Table 2-4. The result of a comparison can be TRUE, FALSE, or UNKNOWN. Operator Description Example = Equality test. SELECT ENAME "Employee" FROM EMP WHERE SAL = 1500; !=, ^=, <> Inequality test. SELECT ENAME FROM EMP WHERE SAL ^= 5000; > Greater than test. SELECT ENAME "Employee", JOB "Title" FROM EMP WHERE SAL > 3000; < Less than test. SELECT * FROM PRICE WHERE MINPRICE < 30; >= Greater than or equal to test. SELECT * FROM PRICE WHERE MINPRICE >= 20; <= Less than or equal to test. SELECT ENAME FROM EMP WHERE SAL <= 1500; IN "Equivalent to any member of" test. Equivalent SELECT * FROM EMP to "=ANY". WHERE ENAME IN ('SMITH', 'WARD');
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 12
ANY/ Compares a value to each value in a list or SELECT * FROM DEPT SOME returned by a query. Must be preceded by =, !=, WHERE LOC = SOME >, <, <= or >=. Evaluates to FASLE if the query ('NEW YORK','DALLAS'); returns no rows. NOT IN Equivalent to "!=ANY". Evaluates to FALSE if SELECT * FROM DEPT any member of the set is NULL. WHERE LOC NOT IN ('NEW YORK', 'DALLAS'); ALL Compares a value with every value in a list or SELECT * FROM emp returned by a query. Must be preceded by =, !=, WHERE sal >= ALL (1400, >, <, <= or >=. Evaluates to TRUE if the query 3000); returns no rows. EXISTS TRUE if a sub-query returns at least one row. SELECT * FROM EMP WHERE EXISTS (SELECT ENAME FROM EMP WHERE MGR IS NULL);
D. Set Oriented Operations
Set operators which combine the results of two queries into a single result are listed in Table Operator Description Example UNION Returns all distinct rows selected SELECT * FROM by either query. (SELECT ENAME FROM EMP WHERE JOB = 'CLERK' UNION SELECT ENAME FROM EMP WHERE JOB = 'ANALYST'); UNION ALL Returns all rows selected by SELECT * FROM either query, including all (SELECT SAL FROM EMP WHERE JOB = duplicates. 'CLERK' UNION SELECT SAL FROM EMP WHERE JOB = 'ANALYST'); INTERSECT Returns all distinct rows selected SELECT * FROM orders_list1 and INTERS by both queries. INTERSECT ECT ALL SELECT * FROM orders_list2 MINUS Returns all distinct rows selected SELECT * FROM (SELECT SAL FROM by the first query but not the EMP WHERE JOB = 'PRESIDENT' second. MINUS SELECT SAL FROM EMP WHERE JOB = 'MANAGER');
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 13
E.Logical operators(AND,OR and NOT)
Operator Description Example NOT Returns TRUE if the following SELECT * FROM EMP WHERE NOT condition is FALSE. (job IS NULL) Returns FALSE if it is TRUE. If it SELECT * FROM EMP WHERE NOT is UNKNOWN, it (sal BETWEEN 1000 AND 2000) remains UNKNOWN. AND Returns TRUE if both component SELECT * FROM EMP WHERE conditions are TRUE. job='CLERK' AND deptno=10 Returns FALSE if either is FALSE; otherwise returns UNKNOWN. OR Returns TRUE if either component SELECT * FROM emp WHERE condition is TRUE. Returns FALSE if job='CLERK' OR deptno=10 both are FALSE. Otherwise, returns UNKNOWN.
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 14
Exercise-III Queries to Retrieve and Change Data: Select, Insert, Delete, and Update A. . Viewing data in the tables Once data has been inserted into a table, the next most logical operation would be to view what has been inserted. a) all rows and all columns Syntax: Select
to
from tablename; or Select * from tablename; Example: select * from branch_mstr;
b) Filtering table data While viewing data from a table, it is rare that all the data from table will be required each time. Hence, sql must give us a method of filtering out data that is not required data. i) Selected columns and all rows: The retrieval of specific columns from the table can be done as shown below Syntax: select , from ; Example: select branch_no from branch_mstr;
ii ) selected rows and all columns: Oracle provides the option of using WHERE Clause in an SQL query to apply a filter on the rows retrieved Syntax: select * from where ; Example: select * from branch_mstr where branch_no='501';
iii) selected columns and selected rows The retrieval of specific columns and specific rows from the table can be done as shown below Syntax: select , from where; Example: select name from branch_mstr where branch_no='501';
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 15
B. Inserting data into tables Once the table is created , the most natural thing to do is load this table with data to be manipulated later. When inserting a single row of data into the table, the insert operation : Creates a new row in the database table Loads the values passed into the columns specified Syntax: INSERT INTO (,) VALUES(,);
Example: Insert into cust_mstr(cno,name) values(10,”raj”); C. DELETE OPERATIONS The DELETE command deletes rows from the table that satisfies the condition provided by its where clause, and returns the number of records deleted. The verb delete in SQL is used to remove either: 1. All the rows from a table. Or 2. A set of rows from a table a.Removal of All Rows Syntax: DELETE FROM ; Example: delete from branch_mstr ; b.Removal Of Specific Rows Syntax: DELETE FROM Where ; Example:
delete from branch_mstr where branch_no='501'; D. Updating the contents of the table The UPDATE command is used to change or modify data values in a table.The verb update in SQL is used to either update: 1. All the rows from a table. Or 2.A select set of rows from a table 1. Updating all Rows The UPDATE statement updates columns in the existing table’s rows with new values. The SET clause indicates which column data should be modified and
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 16
the new values that they should hold. The WHERE clause, if given , specifies which rows should be updated .Otherwise, all table rows are updated.
Syntax: UPDATE SET =,=; Example: update branch_mstr set name = 'ashoknagar'; 2.Updating Records Conditionally Syntax: UPDATE SET =,= WHERE ; Example: update branch_mstr set name = 'ashoknagar' where name='patamata';
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 17
Exercise-IV
Queries using Group By, Order By, and Having Clauses GROUP BY AND HAVING CLAUSES GROUP BY Clause: The GROUP BY clause is another section of the select statement .This optional clause tells Oracle to group rows based on distinct values that exist for specified columns The GROUP BY clause creates a data set, containing several sets of records grouped together based on a condition. Syntax: Select , aggregate _function() from where group by ,,; Having Clause: The HAVING clause can be used in conjunction with the GROUP BY clause . HAVING imposes a condition on the GROUP BY clause, which further filters the groups created by the GROUP BY clause. Each column specification specified in the HAVING clause must occur within a statistical function or must occur in the list of columns named in the GROUP BY clause Syntax: Select , aggregate _function() from where group by ,, having ; Example: SELECT COUNT(Id), Country FROM Customer GROUP BY Country HAVING COUNT(Id) > 10
Sorting Data In A Table. Oracle allows data from a table to be viewed in a sorted order. The rows retrieved from the table will be sorted in either ascending or descending order depending on the condition specified in the select sentence. Syntax: SELECT * FROM ORDER BY , <[SORTORDER]>; Example: select * from branch_mstr order by branch_no;
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 18
Exercise-V
Queries on Controlling Data: Commit, Rollback, and Save point
Transaction Processing Using Commit ,Rollback and Savepoint Commit Save changes (transactional). Syntax: COMMIT [WORK] [COMMENT 'comment_text'] COMMIT [WORK] [FORCE 'force_text' [,int] ] FORCE - will manually commit an in-doubt distributed transaction force_text - transaction identifier (see the DBA_2PC_PENDING view) int - sets a specific SCN. If a network or machine failure prevents a distributed transaction from committing properly, Oracle will store any commit comment in the data dictionary along with the transaction ID. INPUT: SQL>commit; RESULT: Commit complete. Rollback Undo work done (transactional). Syntax: ROLLBACK [WORK] [TO [SAVEPOINT]'savepoint_text_identifier']; ROLLBACK [WORK] [FORCE 'force_text']; FORCE - will manually rollback an in-doubt distributed transaction INPUT: SQL>rollback; RESULT:Rollback complete. Savepoint Save changes to a point (transactional). Syntax: SAVEPOINT text_identifier Example: UPDATE employees SET salary = 95000 WHERE last_name = 'Smith'; SAVEPOINT justsmith; UPDATE employees SET salary = 1000000; SAVEPOINT everyone; SELECT SUM(salary) FROM employees;
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 19
ROLLBACK TO SAVEPOINT justsmith; COMMIT; SQL> select * from emp1;
OUTPUT:- EID ENAME ESAL EBRANCH ------1 scotty 6000 a 2 wayne 10000 b 3 david 7000 c 4 max 8000 b 5 mark 7000 a 6 jeff 12000 a 7 matt 10000 b 8 steve 7000 c
8 rows selected
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 20
Exercise-VI Queries to Build Report in SQL *PLUS
The Steps in Report Writing 1. Formulate your query 2. Format the columns – 3.Add page headers/footers 4. Format the page 5. Print it 6. If more advanced: • Add page and line breaks • Add totals and subtotals Example: SELECT E.EMPLOYEE_NAME, P.PROJECT_NAME, SUM(PH.HOURS_LOGGED) , SUM(PH.DOLLARS_CHARGED) FROM EMPLOYEE E, PROJECT P, PROJECT_HOURS PH WHERE E.EMPLOYEE_ID = PH.EMPLOYEE_ID AND P.PROJECT_ID = PH.PROJECT_ID GROUP BY E.EMPLOYEE_ID, E.EMPLOYEE_NAME, P.PROJECT_ID, P.PROJECT_NAME;
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 21
Exercise-VII Queries for Creating, Dropping, and Altering Tables, Views, and Constraints
A. Create Table Command: - it defines each column of the table uniquely. Each column has minimum of three attributes, a name , data type and size.
Rules For Creating Tables: 1. A name can have maximum upto 30 characters 2. Alphabets from A-Z,a-z and numbers from 0-9 are allowed 3. A name should begin with an alphabet 4. The use of the special character like _ is allowed and also recommended 5. SQL reserved words not allowed. For example : create,select, and so on.
f) foreign key constraint at column level. Syntax:
(size>) references [
];
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 22
g) foreign key constraint at table level Syntax: foreign key(
[,
]) references [(
,
)
h) check constraint at column level. Syntax:
(size) check()
i) check constraint constraint at table level. Syntax: check(
Example: . Write a query to create branch_mstr described as below: Column name Data type Size Default Attributes
Branch_no Varchar2 10 Primary key
Name Varchar2 30
create table branch_mstr(branch_no varchar2(10) primary key,name varchar2(30)); B.Destroying tables: Some times tables within a particular database become obsolete and need to be discarded in such situation using the DROP TABLE statement with the table name can destroy a specific table
Syntax: Drop table ;
Example: drop table branch_mstr;
C. Modifying the structure of tables. The structure of a table can be modified by using the ALTER TABLE command . This command allows changing the structure of an existing table.With this command it is possible to add or delete columns, create or destroy indexes,change the data type of existing columns, or renme columns or table itself
a) Add new columns
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 23
Syntax: Alter table add(datatype(size));
Example: Alter table emp add(sal number(7,2));
b) Dropping a column from a table. Syntax: Alter table drop column
;
Example: Alter table emp drop column sal;
c) Modifying existing columns. Syntax: Alter table modify(
());
Example: Alter table emp modify(ename varchar2(15)); d) Renaming The Attributes We can rename the attributes in oracle
Syntax ALTER TABLE RENAME COLUMN OLD_COLUMN_NAME TO NEW_COLUMN_NAME;
Example ALTER TABLE CUST_TABLE RENAME COLUMN CUST_SEX TO CUST_GENDER;
D.Views I. Creating Views After a table is created and populated with data , it becomes necessary to prevent all users from accessing all columns of a table ,for data security reasons.. This would mean creating several tables having the appropriate number of columns and assigning specific users to each table, as required.This will Answer data security requirements very well but give rise to a great deal of redundant data being resident in tables, in the database.
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 24
To reduce redundant data to the minimum possible, Oracle allows the creation of an object called a View Syntax: CREATE VIEW AS SELECT , FROM
;
Example: Create view cust_vw as select name, gender from cust_mstr;
II. Drop a view The DROP VIEW command is used to remove a view from the database Syntax: DROP VIEW < VIEWNAME> Example: DROP VIEW CUST_VW;
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 25
Exercise-VIII Queries on Joins and Correlated Sub-Queries Simple joins( no INNER JOIN):
Combining tables to derive a new table is called a join.Joins help us to derive a single table that contains all of the desired data.Using the WHERE clause we can join two tables
Inner-joins :
INNER JOIN takes two tables and a join specification describing how the two tables should be joined.The join specification may be specified as a condition.The condition follows the keyword ON. .In short, the INNER JOIN returns all rows from both the tables where there is a match.
Syntax:
SELECT ,, FROM INNER JOIN ON
,=, WHERE ORDER BY ,, Where
o ColumnName1 in TableName1 is usually that table’s Primary key o ColumnName2 in TableName2 is a foreign key in that table o ColumnName1 and ColumnName2 must have the same data type and for certain data types, the same size. NOTE:
It is common to join tables over attributes with the same name .Thus SQL provides a shorthand for this type of join.The USING clause lists those attributes common to both tables that must have the same value to be in the resultHere USING is identical to the equijoin..Note that INNER may be omitted. Because it is the default type of join. Example: SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID; Inner-recursive joins(joining to itself)
In some situations, we need to connect a table to itself..SQL handles this situation by allowing two copies of the same table to appear in the FROM clause.The only
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 26 requirement is that each copy of the table must be given a different alias to distinguish between the copies of the table.
Syntax:
SELECT column_name(s) FROM table1 T1, table1 T2 WHERE condition; Example: SELECT A.CustomerName AS CustomerName1, B.CustomerName AS CustomerName2, A.City FROM Customers A, Customers B WHERE A.CustomerID <> B.CustomerID AND A.City = B.City ORDER BY A.City; Outer joins:
Outer joins are similar to inner joins, but give a bit more flexibility when selecting data from related tables.This type of join can be used in situation where it is desired, to select all rows from the table on the left(or right, or both) regardless of whether the other table has values in common and usually enter NULL where data is missing.
Syntax:
SELECT column_name(s) FROM table1 FULL OUTER JOIN table2 ON table1.column_name = table2.column_name; Example: SELECT Customers.CustomerName, Orders.OrderID FROM Customers FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID ORDER BY Customers.CustomerName; \
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 27
Exercise-IX
Queries on Working with Index, Sequence, Synonym, Controlling Access, and Locking Rows for Update, Creating Password and Security features A.Creating index The CREATE INDEX statement is used to create indexes in tables.Indexes are used to retrieve data from the database very fast. The users cannot see the indexes, they are just used to speed up searches/queries. Syntax Creates an index on a table. Duplicate values are allowed: CREATE INDEX index_name ON table_name (column1, column2, ...);
DROP INDEX The DROP INDEX statement is used to delete an index in a table. Syntax
DROP INDEX index_name;
B.Creating sequence Oracle provides an object called a sequence that can generate numeric values. The value generated can have a maximum of 38 digits .A sequence can be defined to:
o Generate numbers in ascending or descending order o Provide intervals between numbers o Caching of sequence numbers in memory to speed up their availability The minimum information required fro generating numbers using a sequence is :
o The starting number o The maximum number that can be generated by a sequence o The increment value for generating the next number This information is provided to Oracle at the time of the sequence creation
Syntax:
CREATE SEQUENCE [INCREMENT BY START WITH MAXVALUE / NOMAXVALUE MINVALUE / NOMINVALUE CYCLE / NOCYCLE CACHE / NOCACHE ORDER / NO ORDER]
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 28
Eg: create a sequence by the name ADDR_SEQ which will generate numbers from 1 upto 999 in ascending order with an interval of 1.The sequence must restart from the number 1 after generating the number 999
SQL>CREATE SEQUENCE ADDR_SEQ INCREMENT BY 1 START WITH 1 MINIMUM VALUE 1 MAXVALUE 999 CYCLE; C.Working with synonyms Aliasing Tables-Full/Partial Name Qualification
It becomes tiresome and error prone to prefix attributes with the full table name every time .Fortunately, SQL allows aliases for the table names.Using the AS clause we can give an alias name to an already existing table
For eg: ingredients AS i
Now ingredients and i refer to the same table.
D.Controlling access
Privilege Management Through The Grant And Revoke Commands
Granting privileges using the GRANT Statement:
Objects that are created by a user are owned and controlled by that user,If a user wishes to access any of the objects belonging to another user,the owner of the object will have to give permissions for such access.This is called Granting of privileges.
Syntax:
GRANT
TO [WITH GRANT OPTION];
The list of object privileges is as follows:
1. ALTER 2. DELETE 3. INDEX 4. INSERT 5. SELECT 6. UPDATE The WITH GRANT OPTION allows the grantee to in turn grant privileges to other users.
Revoking Privileges Given:
Privileges once given can be denied to a user using the REVOKE command. The object owner can revoke privileges granted to another user.
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 29
A user of an object who is not the owner, but has been granted the GRANT privilege, has the power to REVOKE the privileges from a grantee
Syntax:
REVOKE ON
FROM
E. Locking Rows for Update In Oracle, adding a FOR UPDATE clause to a SELECT statement lets you lock the selected rows. Other users cannot lock or update those rows until you end your transaction. Things to know about row locking in Oracle: 1. SELECT…FOR UPDATE will not be able to lock rows if they are already locked by another transaction. By default, the session will wait for the locks to be released by the other transaction. 2. You can instruct Oracle to not wait for the locks to be released, by adding a NOWAIT to SELECT…FOR UPDATE. 3. To release the locked rows, a COMMIT or ROLLBACK must be issued in the session holding the lock. 4. SELECT…FOR UPDATE is restricted from use in SQLs with the DISTINCT operator, set operators, CURSOR expression, GROUP BY or aggregate functions. 5. Nested table rows are not locked when the parent table rows are locked. You must lock nested table rows explicitly if needed. 6. In a SQL with joins of multiple tables, if you want to lock rows from only a particular table, specify the OF … column clause to indicate which table to lock. Without this clause, Oracle locks the selected rows from all the tables in the join. 7. When selecting multiple rows for update, you can add the SKIP LOCKED clause to lock rows if not already locked by another transaction, else skip rows if they are already locked. [Note: Oracle recommends that you use the Oracle Streams Advanced Queuing APIsinstead of the SKIP LOCKED functionality.]
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 30
F. Creating Password and Security features
SQL>CONNECT SYSTEM/MANAGER; SQL>CREATE USER "USERNAME" IDENTIFIED BY "PASSWORD" SQL>GRANT DBA TO "USERNAME" SQL>CONNECT "USERNAME"/"PASSWORD"; EXAMPLE CREATING A USER SQL>CONNECT SYSTEM/MANAGER; SQL>CREATE USER CSE2 IDENTIFIED BY CSECSE; SQL>GRANT DBA TO CSE2; SQL>CONNECT CSE2/CSECSE; SQL>REVOKE DBA FROM CSE2;
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 31
Exercise-X Write a PL/SQL Code using Basic Variable, Anchored Declarations, and Usage of Assignment Operation
INTRODUCTION TO PL/SQL As the name suggests, PL/SQL is a superset of SQL.PL/SQL is a block-structured language that enables developers to combine the power of SQL with procedural statements.PL/SQL bridges the gap between database technology and procedural programming languages.
ADVANTAGES OF PL/SQL 1. PL/SQL is development tool that not only supports SQL data manipulation but also provides facilities of conditional checking,branching and looping. 2. PL/SQL sends an entire block of SQL statements to the oracle engine all in one go. 3. PL/SQL also permits dealing with errors as required , and facilitates displaying user-friendly messages,when errors are encountered. 4.PL/SQL allows declaration and use of variables in blocks of code. 5.Applications written in PL/SQL are portable to any computer hardware and operating system, where oracle is operational.
THE GENERIC PL/SQL BLOCK Every programming environment allows the creation of structured,logical blocks of code that describe processes, which have to be applied to data. Once these blocks are passed to the environment ,the processes described are applied to data ,suitable data manipulation takes place, and useful output is obtained. A PL/SQL block has a definite structure , which can be divided into sections.The sections of a PL/S1QL block are: o The Declare section o The Master Begin and End section that also (optionally) contains an Exception section
PL/SQL BLOCK DECLARE --Declarations of memory variables,constants,cursors etc.,in PL/SQL BEGIN --SQL executable statements --PL/SQL executable statements EXCEPTION /*SQL or PL/SQL code to handle errors that may arise during the execution of the code block between BEGIN and EXCEPTION section END; The Declare Section
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 32
Code blocks start with a declaration section, in which, memory variables and other Oracle objects can be declared, and if required initialized. Once declared , they can be used in SQL statements for data manipulation. The Begin Section It consists of a set of SQL and PL/SQL statements, which describe processes that have to be applied to table of data.Actual data manipulation, retrieval,looping and branching constructs are specified in this section. The Exception Section This section deals with handling of errors that arise during execution of the data manipilation statements, which make up the PL/SQL code block.Errors can arise due to syntax, logic and/or validation rule violation. The End Section This marks the end of a PL/SQL block.
Creation of simple PL/SQL program which includes declaration section, executable section and exception –Handling section declare sno marks.sid%type; m1 marks.s1%type; m2 marks.s2%type; m3 marks.s3%type; p number(10,4); begin sno:='&sno'; select sid,cd,dc,dbms into sno,m1,m2,m3 from marks where sid=sno; p:=(m1+m2+m3)/3; if(p>70) then dbms_output.put_line('first class'); elsif( p>50 and p<60) then dbms_output.put_line('second class'); elsif(p>40 and p<50) then dbms_output.put_line('third class'); else dbms_output.put_line('fail'); end if; exception when no_data_found then dbms_output.put_line('student does not exists'); end; /
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 33
Output:
SQL> @ marks Enter value for sno: 66 old 8: sno:='&sno'; new 8: sno:='66'; first class PL/SQL procedure successfully completed.
SQL> @ marks Enter value for sno: 22 old 8: sno:='&sno'; new 8: sno:='22'; student does not exists
PL/SQL procedure successfully completed.
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 34
Exercise-XI Write a PL/SQL Code Bind and Substitution Variables. Printing in PL/SQL
Referencing Bind Variables
You reference bind variables in PL/SQL by typing a colon (:) followed immediately by the name of the variable. For example
:ret_val := 1;
To change this bind variable in SQL*Plus, you must enter a PL/SQL block. For example
SQL> begin 2 :ret_val:=4; 3 end; 4 /
PL/SQL procedure successfully completed.
This command assigns a value to the bind variable named ret_val.
Displaying Bind Variables
To display the value of a bind variable in SQL*Plus, you use the SQL*Plus PRINT command. For example
SQL> print ret_val
RET_VAL ------4 Substitution Variables
Inserting rows into a table is a very tedious task. In real-life tables, we are talking about thousands of rows per table!
There are screen designers, form creators, and so on. An SQL statement does not have those fancy controls or buttons. The SQL language does have substitution variables, which enable you to create interactive
SQL> INSERT INTO dept (DeptId, DeptName, Location, EmployeeId) VALUES (&dept,_id,'&dept,_namef,'&location', &emp__.,id); Enter value for dept~_id: 70 Enter value for dept~_name: Testing Enter value for location: Miami
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 35
Enter value for emp__.,id: NULL
1 row created.
SQL script. When you execute the script, Oracle prompts you to enter a value for the substitution variable. 'Ihe ampersand (&) character is used before the substitution variable in the query. The substitution variables for character and date type columns are enclosed within a pair of single quotation marks. Figure 5-1 shows the use of substitution variables and the interactive prompts displayed by Oracle.
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 36
Exercise-XII Write a PL/SQL block using SQL and Control Structures in PL/SQL a.FOR LOOP In Oracle, the FOR LOOP allows you to execute code repeatedly for a fixed number of times.
Syntax The syntax for the FOR Loop in Oracle/PLSQL is: FOR loop_counter IN [REVERSE] lowest_number..highest_number LOOP {...statements...} END LOOP; Where the parameters are loop_counter The loop counter variable. REVERSE Optional. If specified, the loop counter will count in reverse. lowest_number The starting value for loop_counter. highest_number The ending value for loop_counter. statements The statements of code to execute each pass through the loop.
c.In Oracle, we use a WHILE LOOP when we are not sure how many times we will execute the loop body and the loop body may not execute even once.
Syntax The syntax for the WHILE Loop in Oracle/PLSQL is:
WHILE condition LOOP {...statements...}
END LOOP;
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 37
Where the Parameters or Arguments condition
The condition is test each pass through the loop. If condition evaluates to TRUE, the loop body is executed. If condition evaluates to FALSE, the loop is terminated. statements
The statements of code to execute each pass through the loop.
The syntax for a nested FOR LOOP statement in PL/SQL is as follows:
FOR counter1 IN initial_value1 .. final_value1 LOOP sequence_of_statements1 FOR counter2 IN initial_value2 .. final_value2 LOOP sequence_of_statements2 END LOOP; END LOOP; The syntax for a nested WHILE LOOP statement in Pascal is as follows:
WHILE condition1 LOOP sequence_of_statements1 WHILE condition2 LOOP sequence_of_statements2 END LOOP; END LOOP;
Program illustrating for loop declare i number(5); n number(2); s number(3); a number(5); begin n:=&n; s:=0;
for i in 1..n loop a:=&a; s:=s+a; end loop; dbms_output.put_line('sum is'||s); end;
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 38
/ output: SQL> @ sun Enter value for n: 3 old 7: n:=&n; new 7: n:=3; Enter value for a: 2 old 11: a:=&a; new 11: a:=2; sum is6
PL/SQL procedure successfully completed.
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 39
Exercise-XIII Write a PL/SQL Code using Cursors, Exceptions and Composite Data Types Cursors :. A cursor is a temporary work area created in the system memory when a SQL statement is executed. A cursor contains information on a select statement and the rows of data accessed by it. This temporary work area is used to store the data retrieved from the database, and manipulate this data. A cursor can hold more than one row, but can process only one row at a time. The set of rows the cursor holds is called the active set. There are two types of cursors in PL/SQL: Implicit cursors These are created by default when DML statements like, INSERT, UPDATE, and DELETE statements are executed. They are also created when a SELECT statement that returns just one row is executed. Explicit cursors They must be created when you are executing a SELECT statement that returns more than one row. Even though the cursor stores multiple records, only one record can be processed at a time, which is called as current row. When you fetch a row the current row position moves to next row. Both implicit and explicit cursors have the same functionality, but they differ in the way they are accessed.
A cursor must be opened before processing and closed after processing. (Similar to how files are opened and closed in a C program).
Syntax to define a cursor: CURSOR IS
Syntax to open the cursor: OPEN
Syntax to store data in the cursor: FETCH INTO , , …. OR FETCH INTO
Syntax to close the cursor: CLOSE
CURSOR LOOPS: The cursor for loop can be used to process multiple records. The advantage of cursor for loop is that the loop itself will open the cursor, read the records into the cursor from the table until end of file and close the cursor.
Syntax for cursor for loop: FOR IN LOOP
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 40
END LOOP;
Implicit Cursors: Application When you execute DML statements like DELETE, INSERT, UPDATE and SELECT statements, implicit statements are created to process these statements. Oracle provides few attributes called as implicit cursor attributes to check the status of DML operations. The cursor attributes available are %FOUND, %NOTFOUND, %ROWCOUNT, and %ISOPEN. For example, When you execute INSERT, UPDATE, or DELETE statements the cursor attributes tell us whether any rows are affected and how many have been affected. When a SELECT... INTO statement is executed in a PL/SQL Block, implicit cursor attributes can be used to find out whether any row has been returned by the SELECT statement. PL/SQL returns an error when no data is selected. The status of the cursor for each of these attributes are defined in the below table.
Attributes Return Value Example %FOUND The return value is TRUE, if the DML statements like SQL%FOUND INSERT, DELETE and UPDATE affect at least one row and if SELECT ….INTO statement return at least one row. The return value is FALSE, if DML statements like INSERT, DELETE and UPDATE do not affect row and if SELECT….INTO statement do not return a row. %NOTFOUND The return value is FALSE, if DML statements like SQL%NOTFOUND INSERT, DELETE and UPDATE at least one row and if SELECT ….INTO statement return at least one row. The return value is TRUE, if a DML statement like INSERT, DELETE and UPDATE do not affect even one row and if SELECT ….INTO statement does not return a row. %ROWCOUNT Return the number of rows affected by the DML SQL%ROWCOUNT operations INSERT, DELETE, UPDATE, SELECT
Explicit Cursors
An explicit cursor is defined in the declaration section of the PL/SQL Block. It is created on a SELECT Statement which returns more than one row. We can provide a suitable name for the cursor. General Syntax for creating a cursor is as given below: CURSOR cursor_name IS select_statement; Where cursor_name – A suitable name for the cursor. select_statement – A select query which returns multiple rows.
How to use Explicit Cursor? There are four steps in using an Explicit Cursor. DECLARE the cursor in the declaration section. OPEN the cursor in the Execution Section.
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 41
FETCH the data from cursor into PL/SQL variables or records in the Execution Section. CLOSE the cursor in the Execution Section before you end the PL/SQL Block. 1) Declaring a Cursor in the Declaration Section: DECLARE CURSOR emp_cur IS SELECT * FROM emp_tbl WHERE salary > 5000; In the above example we are creating a cursor ‘emp_cur’ on a query which returns the records of all the employees with salary greater than 5000. Here ‘emp_tbl’ in the table which contains records of all the employees. 2) Accessing the records in the cursor: Once the cursor is created in the declaration section we can access the cursor in the execution section of the PL/SQL program. How to access an Explicit Cursor? These are the three steps in accessing the cursor. 1) Open the cursor. 2) Fetch the records in the cursor one at a time. 3) Close the cursor. General Syntax to open a cursor is: OPEN cursor_name; General Syntax to fetch records from a cursor is: FETCH cursor_name INTO record_name; OR FETCH cursor_name INTO variable_list; General Syntax to close a cursor is: CLOSE cursor_name; When a cursor is opened, the first row becomes the current row. When the data is fetched it is copied to the record or variables and the logical pointer moves to the next row and it becomes the current row. On every fetch statement, the pointer moves to the next row. If you want to fetch after the last row, the program will throw an error. When there is more than one row in a cursor we can use loops along with explicit cursor attributes to fetch all the records. Points to remember while fetching a row: · We can fetch the rows in a cursor to a PL/SQL Record or a list of variables created in the PL/SQL Block. · If you are fetching a cursor to a PL/SQL Record, the record should have the same structure as the cursor. · If you are fetching a cursor to a list of variables, the variables should be listed in the same order in the fetch statement as the columns are present in the cursor. General Form of using an explicit cursor is: DECLARE variables; records; create a cursor; BEGIN OPEN cursor;
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 42
FETCH cursor; process the records; CLOSE cursor; END; What are Explicit Cursor Attributes? Oracle provides some attributes known as Explicit Cursor Attributes to control the data processing while using cursors. We use these attributes to avoid errors while accessing cursors through OPEN, FETCH and CLOSE Statements. When does an error occur while accessing an explicit cursor? a) When we try to open a cursor which is not closed in the previous operation. b) When we try to fetch a cursor after the last operation.
These are the attributes available to check the status of an explicit cursor.
Attributes Return values Example %FOUND TRUE, if fetch statement returns at least Cursor_name%FOUND one row.
FALSE, if fetch statement doesn’t return a row. %NOTFOUND TRUE, , if fetch statement doesn’t return Cursor_name%NOTFOUND a row.
FALSE, if fetch statement returns at least one row. %ROWCOUNT The number of rows fetched by the fetch Cursor_name%ROWCOUNT statement
If no row is returned, the PL/SQL statement returns an error. %ISOPEN TRUE, if the cursor is already open in the Cursor_name%ISNAME program
FALSE, if the cursor is not opened in the program.
SELECT FOR UPDATE STATEMENT The SELECT FOR UPDATE statement allows you to lock the records in the cursor result set. You are not required to make changes to the records in order to use this statement. The record locks are released when the next commit or rollback statement is issued. Syntax The syntax for the SELECT FOR UPDATE statement in Oracle/PLSQL is:
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 43
CURSOR cursor_name IS select_statement FOR UPDATE [OF column_list] [NOWAIT]; Where cursor_name - The name of the cursor. Select_statement- A SELECT statement that will populate your cursor result set. column_list - The columns in the cursor result set that you wish to update. NOWAIT- Optional. The cursor does not wait for resources. EXAMPLE For example, you could use the SELECT FOR UPDATE statement as follows: CURSOR c1 IS SELECT course_number, instructor FROM courses_tbl FOR UPDATE OF instructor; WHERE CURRENT OF STATEMENT If you plan on updating or deleting records that have been referenced by a SELECT FOR UPDATE statement, you can use the WHERE CURRENT OF statement. SYNTAX The syntax for the WHERE CURRENT OF statement in Oracle/PLSQL is either: UPDATE table_name SET set_clause WHERE CURRENT OF cursor_name; OR DELETE FROM table_name WHERE CURRENT OF cursor_name;
Note: The WHERE CURRENT OF statement allows you to update or delete the record that was last fetched by the cursor.
Program to demonstrate cursors declare
cursor emp_cur is
select * from emp
for update;
cur_rec emp_cur%rowtype;
begin
for i in emp_cur loop
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 44
update emp set lname='chp'
where current of emp_cur;
end loop;
if not emp_cur%isopen then
Open emp_cur;
End if;
LOOP
Fetch emp_cur into cur_rec;
Exit when emp_cur%notfound;
dbms_output.put_line(cur_rec.eid || ' age is ' ||cur_rec.lname);
END LOOP;
Close emp_cur;
end;
/
Output:
SQL> set serveroutput on
SQL> @ cur; age is chp
1 age is chp
PL/SQL procedure successfully completed.
EXECPTIONS PL/SQL provides a feature to handle the Exceptions which occur in a PL/SQL Block known as exception Handling. Using Exception Handling we can test the code and avoid it from exiting abruptly. When an exception occurs a messages which explains its cause is recieved. PL/SQL Exception message consists of three parts. 1) Type of Exception 2) An Error Code 3) A message
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 45
By Handling the exceptions we can ensure a PL/SQL block does not exit abruptly. Structure of Exception Handling. General Syntax for coding the exception section DECLARE Declaration section BEGIN Exception section EXCEPTION WHEN ex_name1 THEN -Error handling statements WHEN ex_name2 THEN -Error handling statements WHEN Others THEN -Error handling statements END; General PL/SQL statments can be used in the Exception Block. When an exception is raised, Oracle searches for an appropriate exception handler in the exception section. For example in the above example, if the error raised is 'ex_name1 ', then the error is handled according to the statements under it. Since, it is not possible to determine all the possible runtime errors during testing fo the code, the 'WHEN Others' exception is used to manage the exceptions that are not explicitly handled. Only one exception can be raised in a Block and the control does not return to the Execution Section after the error is handled. If there are nested PL/SQL blocks like this. DELCARE Declaration section BEGIN DECLARE Declaration section BEGIN Execution section EXCEPTION Exception section END; EXCEPTION Exception section END; In the above case, if the exception is raised in the inner block it should be handled in the exception block of the inner PL/SQL block else the control moves to the Exception block of the next upper PL/SQL Block. If none of the blocks handle the exception the program ends abruptly with an error. 3) Types of Exception. There are 3 types of Exceptions. a) Named System Exceptions b) Unnamed System Exceptions c) User-defined Exceptions a) Named System Exceptions
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 46
System exceptions are automatically raised by Oracle, when a program violates a RDBMS rule. There are some system exceptions which are raised frequently, so they are pre-defined and given a name in Oracle which are known as Named System Exceptions. For example: NO_DATA_FOUND and ZERO_DIVIDE are called Named System exceptions. Named system exceptions are: 1) Not Declared explicitly, 2) Raised implicitly when a predefined Oracle error occurs, 3) caught by referencing the standard name within an exception-handling routine.
Exception Name Reason Error Number CURSOR_ALREADY_OPEN When you open a cursor that is already open. ORA- 06511 INVALID_CURSOR When you perform an invalid operation on a cursor ORA- like closing a cursor, fetch data from a cursor that is 01001 not opened. NO_DATA_FOUND When a SELECT...INTO clause does not return any ORA- row from a table. 01403 TOO_MANY_ROWS When you SELECT or fetch more than one row into a ORA- record or variable. 01422 ZERO_DIVIDE When you attempt to divide a number by zero. ORA- 01476
For Example: Suppose a NO_DATA_FOUND exception is raised in a proc, we can write a code to handle the exception as given below. BEGIN Execution section EXCEPTION WHEN NO_DATA_FOUND THEN dbms_output.put_line ('A SELECT...INTO did not return any row.'); END; b) Unnamed System Exceptions Those system exception for which oracle does not provide a name is known as unamed system exception. These exception do not occur frequently. These Exceptions have a code and an associated message. There are two ways to handle unnamed sysyem exceptions: 1. By using the WHEN OTHERS exception handler, or 2. By associating the exception code to a name and using it as a named exception. We can assign a name to unnamed system exceptions using a Pragma called EXCEPTION_INIT. EXCEPTION_INIT will associate a predefined Oracle error number to a programmer_defined exception name. Steps to be followed to use unnamed system exceptions are • They are raised implicitly. • If they are not handled in WHEN Others they must be handled explicity. • To handle the exception explicity, they must be declared using Pragma EXCEPTION_INIT as given above and handled referecing the user-defined exception name in the exception section.
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 47
The general syntax to declare unnamed system exception using EXCEPTION_INIT is: DECLARE exception_name EXCEPTION; PRAGMA EXCEPTION_INIT (exception_name, Err_code); BEGIN Execution section EXCEPTION WHEN exception_name THEN handle the exception END; c) User-defined Exceptions PL/SQL allows us to define our own exceptions according to the need of our program.Apart from sytem exceptions we can explicity define exceptions based on business rules. These are known as user-defined exceptions. Steps to be followed to use user-defined exceptions: • They should be explicitly declared in the declaration section. • They should be explicitly raised in the Execution Section. • They should be handled by referencing the user-defined exception name in the exception section. Syntax The syntax for declaring an exception is: DECLARE my-exception EXCEPTION;
RAISE_APPLICATION_ERROR ( ) RAISE_APPLICATION_ERROR is a built-in procedure in oracle which is used to display the user- defined error messages along with the error number whose range is in between -20000 and - 20999. Whenever a message is displayed using RAISE_APPLICATION_ERROR, all previous transactions which are not committed within the PL/SQL Block are rolled back automatically (i.e. change due to INSERT, UPDATE, or DELETE statements). RAISE_APPLICATION_ERROR raises an exception but does not handle it. RAISE_APPLICATION_ERROR is used for the following reasons, a) to create a unique id for an user-defined exception. b) to make the user-defined exception look like an Oracle error. The General Syntax to use this procedure is: RAISE_APPLICATION_ERROR (error_number, error_message);
• The Error number must be between -20000 and -20999 • The Error_message is the message you want to display when the error occurs. Steps to be folowed to use RAISE_APPLICATION_ERROR procedure: 1. Declare a user-defined exception in the declaration section. 2. Raise the user-defined exception based on a specific business rule in the execution section. 3. Finally, catch the exception and link the exception to a user-defined error number in RAISE_APPLICATION_ERROR.
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 48
for zero divide exception declare x number(5); d number(5); q number(5); begin x:=÷nt; d:=&divisor; if((d!=0)) then q:=x/d; dbms_output.put_line('the quotient is '|| q); else raise zero_divide; end if; exception when zero_divide then dbms_output.put_line('division with 0 is not possible'); end; /
SQL> @zd_excep.sql; Enter value for divident: 22 old 6: x:=÷nt; new 6: x:=22; Enter value for divisor: 4 old 7: d:=&divisor; new 7: d:=4; the quotient is 6
PL/SQL procedure successfully completed.
SQL> @zd_excep.sql; Enter value for divident: 77 old 6: x:=÷nt; new 6: x:=77; Enter value for divisor: 0 old 7: d:=&divisor; new 7: d:=0; division with 0 is not possible
PL/SQL procedure successfully completed.
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 49
User defined exceptions declare name student.sname%type; sage student.age%type; my_excep exception; id number(3); begin id:=&sid; select sname into name from student where sid=id; if(name='chp') then select age into sage from student where sid=id; dbms_output.put_line('student age is' || age); else raise my_excep; end if; exception when my_excep then dbms_output.put_line('the id you entered is not correct '); when no_data_found then dbms_output.put_line('the id is not table'); end; /
SQL> @ud_excep.sql; Enter value for sudhakar_id: 22 old 7: id:=&sudhakar_id; new 7: id:=22; sudhakar age is32
PL/SQL procedure successfully completed.
SQL> @ud_excep.sql; Enter value for sudhakar_id: 77 old 7: id:=&sudhakar_id; new 7: id:=77; the id you entered is not sudhakar id PL/SQL procedure successfully completed.
SQL> @ud_excep.sql; Enter value for sudhakar_id: 66 old 7: id:=&sudhakar_id; new 7: id:=66; the id is not table PL/SQL procedure successfully completed. SQL> commit; Commit complete.
SQL> exit;
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 50
Exercise-XIV Write a PL/SQL Code using Procedures, Functions, and Packages FORMS Procedural Objects Grroups of SQL and PL/SQL statements can be stored in the database. The code stored once in the database can be used by multiple applications Various types of procedural objects are: procedures, functions , packages
Procedures: Procedures are subprograms which will perform an action and functions are subprogramsthat are generally coded to compute some value.The clients execute the procedure or function and the processing is done in the server. Procedures can receive an return values from and to the caller . Communication is passed to a procedure through a parameter and communication is passed out of a procedure through a parameter
There are three types of parameters that can be declared:
1. IN - The parameter can be referenced by the procedure . The value of the parameter can not be overwritten by the procedure . 2. OUT - The parameter can not be referenced by the procedure , but the value of the parameter can be overwritten by the procedure or . 3. IN OUT - The parameter can be referenced by the procedure and the value of the parameter can be overwritten by the procedure .
Syntax: CREATE [OR REPLACE] PROCEDURE procedure_name [(parameter_name [IN | OUT | IN OUT] type [, ...])] {IS | AS} BEGIN < procedure_body > END procedure_name; DROP PROCEDURE Once we have created the procedure in Oracle, we might find that we need to remove it from the database. Syntax The syntax to a drop a procedure in Oracle is: DROP PROCEDURE procedure_name;
Program to demonstrate Procedures create procedure fact1(n in number, f out number) is i integer; begin
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 51
f:=1; for i in 1 .. n loop
f:=f*i; end loop; end;
/
Proc_cal.sql declare x number(10); y number(10); begin x:=&x; if(x>0) then fact1(x,y); dbms_output.put_line('the factorial is' ||y); end if; end;
/
Output:
SQL> set serveroutput on
SQL> @ proc
Procedure created.
SQL> @ proc_cal
Enter value for x: 3 old 5: x:=&x;
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 52 new 5: x:=3; the factorial is6
PL/SQL procedure successfully completed
Functions: Functions are also a collection of SQL and PL/SQL code which can return a value to the caller. Unlike procedures, functions can return a value to the caller. This value is returned through the use of the RETURN keyword within the function. A function can return a single value to the caller. Functions do not allow the OUT and IN OUT arguments.
Syntax: Create [OR Replace] FUNCTION (Parameter) RETURN IS/AS Begin ; RETURN(variable); End;
DROP FUNCTION
Once we have created the function in Oracle, we might find that we need to remove it from the database.
Syntax
The syntax to a drop a function in Oracle is: DROP FUNCTION function_name;
Program to demonstrate functions
Creating function: create or replace function sail(sno in varchar2) return varchar2 as name varchar2(15); begin
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 53 select sname into name from sailor where sid=sno; return name; exception when no_data_found then dbms_output.put_line('no sailor found'); end;
/
Calling function: declare sno varchar2(15); name varchar2(15); begin sno:=&sid; name:=sail(sno); dbms_output.put_line('the sailor is:'||name); end;
/
Output:
SQL> @ func_cal
Enter value for sid: 22 old 5: sno:=&sid; new 5: sno:=22; the sailor is:Dustin
PL/SQL procedure successfully completed.
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 54
Packages: Packages are groups of procedures, functions, variables and SQL statements in a single unit. It consists of the package definition/specification and package body. A package specification consists of the list of functions, procedures, variables, constants, cursors and exceptions that will be available to users of the package. A package body consists of the PL/SQL blocks and specifications for all of the public objects listed in the package specification. It may also include code that is run every time the package is invoked, regardless of the part of the package that is executed. The name of the package body should be the same as the name of the package specification.
Syntax for specification: Create Package IS/AS ; END; Syntax for Body: Create Package Body IS/AS ; END;
Program to demonstrate packages create or replace package maths as procedure square(n in number); function cub(n in number)return number; end maths;
/
Package body: create or replace package body maths as y number; procedure square(n number) is
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 55 begin y:=n*n; dbms_output.put_line('the square of '||n||'is'||y); end square; function cub(n in number)return number as
--z number; begin y:=n*n*n; return y; end cub; end maths;
/
SQL> ed pack.sql; SQL> @ pack.sql; Package created.
SQL> ed pack_body.sql;
SQL> @ pack_body.sql;
Package body created.
Calling: declare n number; y number; begin n:=&n; maths.square(n); y:=maths.cub(n); dbms_output.put_line('the cube of '||n||'is'||y);
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 56 end;
/
Output:
SQL> set serveroutput on
SQL> @ pack_cal
Enter value for n: 2 old 5: n:=&n; new 5: n:=2; the square of 2is4 the cube of 2is8
PL/SQL procedure successfully completed.
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 57
Exercise-XV Write a PL/SQL Code Creation of forms for any Information System such as Student Information System, Employee Information System etc.
Creating a Tabular Form
A tabular form enables users to update multiple rows in a table. The Tabular Form Wizard creates a form to perform update, insert, and delete operations on multiple rows in a database table.
To create a tabular form:
1. On the Workspace home page, click the Application Builder icon. 2. Select an application. 3. Click Create Page. 4. Select Form and click Next. 5. Select Tabular Form and click Next.
The Tabular Form Wizard appears.
6. For Table/View Owner: a. Specify the table or view owner on which you want to base your tabular form. b. Select the operations to be performed on the table (for example, Update, Insert and Delete). c. Click Next. 7. For Table/View Name, select a table and click Next. 8. For Displayed Columns: a. Select the columns (updatable and nonupdatable) to include in the form.
Note that you can modify the column order or your SQL query after you create the page.
b. Click Next. 9. For Primary Key, select the Primary Key column and a secondary Primary Key column (if applicable) and click Next. 10. For Primary Key Source, select a source type for the primary key column and click Next. Valid options include: o Existing trigger - Select this option if a trigger is defined for the table. You can also select this option if you plan on specifying the primary key column source later after completing the form. o Custom PL/SQL function - Select this option if you want to provide a PL/SQL function to generate returning key value. o Existing sequence - Select this option if you want to pick the sequence from a list of sequences available in the selected schema. On Updatable Columns, select which columns should be updatable and click Next.
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 58
On Page and Region Attributes: . Specify page and region information. a. Select a region template. b. Select a report template. c. Click Next. On Tab, specify a tab implementation for this page and click Next. On Button Labels, enter the display text to appear for each button and click Next. On Branching, specify the pages to branch to after the user clicks the Submit and Cancel buttons and click Next. Click Finish.
Note: Any modification of the select list of a SQL statement of a tabular form after it has been generated is not recommended. If you do modify the query, make sure the values of the updateable columns are not altered after being queried from the database by the Application Express engine.
Using a PL/SQL API to Process Form Values
For certain types of applications, it is appropriate to centralize all access to tables in a single or a few PL/SQL packages. If you created a package to handle DML operations, you can call procedures and functions within this package from an After Submit PL/SQL process to process insert, updates, and delete requests.
Populating Forms
Oracle Application Express populates a form either on load or when the Application Express engine renders the page. You can populate a form in the following ways:
Create a process and define the type as Automated Row Fetch. Populate the form manually by referencing a hidden session state item.
To create an Automated Row Fetch process:
1. Navigate to the appropriate Page Definition. See "Accessing a Page Definition". 2. Under Processes, click Create. 3. Select the process type Data Manipulation. 4. Select the process category Automatic Row Fetch. 5. Specify the following process attributes: a. In the Name field, enter a name to identify the process. b. In the Sequence field, specify a sequence number. c. From the Point list, select the appropriate processing point. d. From the Type list, select Automated Row Fetch. 6. Follow the on-screen instructions.
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 59
You can also populate a form manually by referencing a hidden session state item. For example, the following code in an Oracle Application Express process of type PL/SQL would set the values of ename and sal. The example also demonstrates how to manually populate a form by referencing a hidden session state item named P2_ID.
FOR C1 in (SELECT ename, sal
FROM emp WHERE ID=:P2_ID)
LOOP
:P2_ENAME := C1.ename;
:P2_SAL := C1.sal;
END LOOP;
In this example:
C1 is an implicit cursor. The value of P2_ID has been set. The process point for this process would be set to execute (or fire) on or before Onload - Before Regions.
Validating User Input in Forms
You can use validations to check data a user enters before processing. Once you create a validation and the associated error message, you can associate it with a specific item. You can choose to have validation error messages display inline (that is, on the page where the validation is performed) or on a separate error page.
Creating an inline error message involves these steps:
Create a validation and specify error message text. Associate the validation with a specific item.
Creating a Validation
To create a validation:
1. Navigate to the appropriate Page Definition. See "Accessing a Page Definition". 2. Under Validations, click the Create icon. 3. When the Create Validations Wizard appears, follow the on-screen instructions.
Validation Types are divided into two categories:
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 60
o Item. These validations start with the term Item and provide common checks you may want to perform on the item with which the validation is associated. o Code. These validations require that you provide either a piece of PL/SQL code or SQL query that defines the validation logic. Use this type of validation to perform custom validations that require verifying values of more than one item or accessing additional database tables. 4. Follow the on-screen instructions.
Note: Validations cannot contain more than 3,950 characters.
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 61
Exercise-XVI
Demonstration of database connectivity
The JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational Database.
JDBC helps you to write Java applications that manage these three programming activities:
1. Connect to a data source, like a database 2. Send queries and update statements to the database 3. Retrieve and process the results received from the database in answer to your query
The following simple code fragment gives a simple example of these three steps: public void connectToAndQueryDatabase(String username, String password) {
Connection con = DriverManager.getConnection( "jdbc:myDriver:myDatabase", username, password);
Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next()) { int x = rs.getInt("a"); String s = rs.getString("b"); float f = rs.getFloat("c"); } }
This short code fragment instantiates a DriverManager object to connect to a database driver and log into the database, instantiates a Statement object that carries your SQL language query to the database; instantiates a ResultSet object that retrieves the results of your query, and executes a simple while loop, which retrieves and displays those results. It's that simple.
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 62
Additional Exercise 2 Develop Programs using BEFORE and AFTER Triggers, Row and Statement Triggers and INSTEAD OF Triggers
TRIGGERS
Triggers are stored programs, which are automatically executed or fired when some events occur. Triggers are, in fact, written to be executed in response to any of the following events:
A database manipulation (DML) statement (DELETE, INSERT, or UPDATE). A database definition (DDL) statement (CREATE, ALTER, or DROP). A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).
Triggers could be defined on the table, view, schema, or database with which the event is associated. Benefits of Triggers Triggers can be written for the following purposes:
Generating some derived column values automatically Enforcing referential integrity Event logging and storing information on table access Auditing Synchronous replication of tables Imposing security authorizations Preventing invalid transactions Creating Triggers The syntax for creating a trigger is:
CREATE [OR REPLACE ] TRIGGER trigger_name {BEFORE | AFTER | INSTEAD OF } {INSERT [OR] | UPDATE [OR] | DELETE} [OF col_name] ON table_name [REFERENCING OLD AS o NEW AS n] [FOR EACH ROW] WHEN (condition) DECLARE Declaration-statements
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 63
BEGIN Executable-statements EXCEPTION Exception-handling-statements END;
Where, CREATE [OR REPLACE] TRIGGER trigger_name: Creates or replaces an existing trigger with the trigger_name. {BEFORE | AFTER | INSTEAD OF} : This specifies when the trigger would be executed. The INSTEAD OF clause is used for creating trigger on a view.
{INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML operation.
[OF col_name]: This specifies the column name that would be updated.
[ON table_name]: This specifies the name of the table associated with the trigger.
[REFERENCING OLD AS o NEW AS n]: This allows you to refer new and old values for various DML statements, like INSERT, UPDATE, and DELETE.
[FOR EACH ROW]: This specifies a row level trigger, i.e., the trigger would be executed for each row being affected. Otherwise the trigger will execute just once when the SQL statement is executed, which is called a table level trigger.
WHEN (condition): This provides a condition for rows for which the trigger would fire. This clause is valid only for row level triggers.
Type of Triggers
1. BEFORE Trigger : BEFORE trigger execute before the triggering DML statement (INSERT, UPDATE, DELETE) execute. Triggering SQL statement is may or may not execute, depending on the BEFORE trigger conditions block. 2. AFTER Trigger : AFTER trigger execute after the triggering DML statement (INSERT, UPDATE, DELETE) executed. Triggering SQL statement is execute as soon as followed by the code of trigger before performing Database operation. 3. ROW Trigger : ROW trigger fire for each and every record which are performing INSERT, UPDATE, DELETE from the database table. If row deleting is define as trigger event, when trigger file, deletes the five rows each times from the table.
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 64
4. Statement Trigger : Statement trigger fire only once for each statement. If row deleting is define as trigger event, when trigger file, deletes the five rows at once from the table. 5. Combination Trigger : Combination trigger are combination of two trigger type,
PL/SQL Trigger Execution Hierarchy
The following hierarchy is followed when a trigger is fired. 1) BEFORE statement trigger fires first. 2) Next BEFORE row level trigger fires, once for each row affected. 3) Then AFTER row level trigger fires once for each affected row. This events will alternates between BEFORE and AFTER row level triggers. 4) Finally the AFTER statement level trigger fires.
How To know Information about Triggers.
We can use the data dictionary view 'USER_TRIGGERS' to obtain information about any trigger.
The below statement shows the structure of the view 'USER_TRIGGERS'
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY 65
This view stores information about header and body of the trigger.
Example:
SELECT * FROM user_triggers WHERE trigger_name = 'Before_Update_Stat_product';
The above sql query provides the header and body of the trigger 'Before_Update_Stat_product'.
Drop trigger
You can drop a trigger using the following command.
DROP TRIGGER trigger_name;
CYCLIC CASCADING in a TRIGGER
This is an undesirable situation where more than one trigger enter into an infinite loop. while creating a trigger we should ensure the such a situtation does not exist.
The below example shows how Trigger's can enter into cyclic cascading. Let's consider we have two tables 'abc' and 'xyz'. Two triggers are created. 1) The INSERT Trigger, triggerA on table 'abc' issues an UPDATE on table 'xyz'. 2) The UPDATE Trigger, triggerB on table 'xyz' issues an INSERT on table 'abc'.
In such a situation, when there is a row inserted in table 'abc', triggerA fires and will update table 'xyz'. When the table 'xyz' is updated, triggerB fires and will insert a row in table 'abc'. This cyclic situation continues and will enter into a infinite loop, which will crash the database.
i. Write a trigger to update a price_history _table whenever the price of a product is changed
DBMS MANUAL DHANEKULA INSTITUTE OF ENGINEERING &TECHNOLOGY