DBMS Lab Manual PDF
DBMS Lab Manual PDF
DBMS Lab Manual PDF
Padmasri Dr. B V Raju Institute of Technology, Vishnupur, Narsapur-502 313 Dist Medak(A.P.)
LABORATORY MANUAL
Prepared By
Vijaykumar Mantri,
M.Tech.(CSE) Asso. Prof. in IT Dept.
DBMS Lab - I Creation, altering and dropping of tables and inserting rows into a table (Use constraints while creating tables) examples using SELECT command.
Following tables (Relations) are considered for the lab purpose. SAILORS (SID:INTEGER, SNAME:STRING, RATING:INTEGER, AGE:REAL) BOATS (BID:INTEGER, BNAME:STRING, COLOR:STRING) RESERVES (SID:INTEGER, BID:INTEGER, DAY:DATE)
Creating Tables :The CREATE TABLE command is used to create the table (relation) in SQL. CREATE TABLE TABLENAME (ATT_NAME1 DATATYPE, ATT_NAME2
DATATYPE, ATT_NAME3 DATATYPE, ..); SQL> CREATE TABLE SAILORS (SID NUMBER (5), SNAME VARCHAR2(30), RATING NUMBER(5), AGE NUMBER(4,2));
FLOAT :- Floating point type of Data. Very similar to NUMBER it stores zero, positive, and negative floating-point numbers.
Along with these types of data types, Oracle supports other types of data types like TIMESTAMP, RAW, ROWID, CLOB, NCLOB, BLOB, XMLType, etc.
Primary Key & Foreign Key :- Consider the Sailors relation and the constraint that no
two sailors have the same SID. This type of constraint can be defined using Primary Key, which gives uniqueness for the value of attribute defined (Eg. SID). Similarly, a sailor cant reserve a boat unless he/she is a valid sailor i.e. the SID of Reserves relation must available in the Sailors relation. This type of constraint can be defined using Foreign Key, which gives the existence of the value of attribute in one relation is depends on value in another relation. We can use Primary Key or/and Foreign Key constraint while creating table. Creating tables with Primary Key CREATE TABLE TABLENAME (ATT_NAME1 DATATYPE, ATT_NAME2 DATATYPE, ATT_NAME3 DATATYPE .., PRIMARY KEY(ATT_NAMES) ); SQL> CREATE TABLE SAILORS ( SID NUMBER(5), SNAME VARCHAR2(30), RATING NUMBER(5), AGE NUMBER(4,2), , PRIMARY KEY(SID) ); Creating tables with Foreign Key CREATE TABLE TABLENAME (ATT_NAME1 DATATYPE, ATT_NAME2 DATATYPE, ATT_NAME3 DATATYPE .., FOREIGN KEY (ATT_NAME) REFERENCES
TABLENAME2)); SQL> CREATE TABLE RESERVES (SID NUMBER(5), BID NUMBER(5), DAY DATE, FOREIGN KEY (SID) REFERENCES (SAILORS) ); The following example gives the complete definition to create Reserves table (Defines Primary Key as well as Foreign Keys). SQL> CREATE TABLE RESERVES (SID NUMBER(5), BID NUMBER(5), DAY DATE, PRIMARY KEY (SID, BID, DAY), FOREIGN KEY (SID) REFERENCES (SAILORS) , FOREIGN KEY (BID) REFERENCES (BOATS) ); Similar way we can create Sailors as well as Boats table using Primary Key constraint.
Creating table with some Constraint :- Suppose we want to add rule for rating of the
sailors - Rating should be between 1 to 10 while creating table then we can use following command. SQL> CREATE TABLE SAILORS ( SID NUMBER(5), SNAME VARCHAR2(30), RATING NUMBER(5), AGE NUMBER(4,2), , PRIMARY KEY(SID), CHECK ( RATING >=1 AND RATING <=10) );
Deleting Table :- The table along with its definition & data can be deleted using following
command. DROP TABLE <TABLENAME>; SQL> DROP TABLE SAILORS;
Adding & Deleting the Attributes and Constraints to the Table :To add the attribute to a existing relation we can use ALTER TABLE Command. ALTER TABLE <TABLENAME> ADD COLUMN ATT_NAME DATATYPE; SQL> ALTER TABLE SAILORS ADD COLUMN SALARY NUMBER(7,2); To remove the attribute from an existing relation we can use following Command. ALTER TABLE <TABLENAME> DROP COLUMN ATT_NAME; SQL> ALTER TABLE SAILORS DROP COLUMN SALARY; To add the constraint to existing relation we can use ALTER TABLE Command. ALTER TABLE <TABLENAME> ADD CONSTRAINT <CON_NAME> <CON_DEFINITION>; SQL> ALTER TABLE SAILORS ADD CONSTRAINT RATE CHECK (RATING >= 1 AND RATING <=10); Similarly we can add primary key or foreign key constraint. To delete the constraint to existing relation we can use following Command. DROP CONSTRAINT <CON_NAME>; SQL> DROP CONSTRAINT RATE; Similarly we can drop primary key or foreign key constraint.
Adding data to the Table :- We can add data to table by using INSERT INTO command. While adding the data to the table we must remember the order of attributes as well
as their data types as defined while creating table. The syntax is as follows. INSERT INTO <TABLENAME> VALUES (VALUE1, VALUE2, VALUE3, ..); SQL> INSERT INTO SAILORS VALUES (1, Rajesh, 10, 30); But sometimes while adding data we may not remember the exact order or sometimes we want to insert few values then we can use following format to add data to a table. INSERT INTO <TABLENAME> (ATT_NAME1, ATT_NAME2, ATT_NAME3, ..) VALUES (VALUE1, VALUE2, VALUE3, ..); SQL> INSERT INTO SAILORS (SNAME, SID, AGE, RATING) VALUES (Rajesh, 1, 30, 10); By using one of these methods we can add records or data to Sailors, Boats as well as Reserves Table.
To delete the record(s) :- To delete all records from table or a single/multiple records which matches the given condition, we can use DELETE FROM command as follows.
DELETE FROM <TABLENAME> WHERE <CONDITION>; SQL> DELETE FROM SAILORS WHERE SNAME = Rajesh; To delete all records from the table DELETE FROM <TABLENAME>; SQL> DELETE FROM SAILORS;
To change particular value :- We can modify the column values in an existing row using
the UPDATE command. UPDATE <TABLENAME> SET ATT_NAME = NEW_VALUE WHERE CONDITION; SQL> UPDATE SAILORS SET RATING = 9 WHERE SID = 1;
Dept of IT, BVRIT, Narsapur
To update all records without any condition. SQL> UPDATE SAILORS SET RATING = RATING + 1;
Simple Queries on the Tables :- The basic form of an SQL query is:
SELECT <SELECT_LIST>FROM <TABLE_LIST> WHERE <CONDITION>; Q1) Display names & ages of all sailors. SQL> SELECT SNMAE, AGE FROM SAILORS; Write queries for 1) Find all sailors with a rating above 7. 2) Display all the names & colors of the boats. 3) Find all the boats with Red color. Queries on multiple tables Q2) Find the names of sailors who have reserved boat number 123. SQL> SELECT SNAME FROM SAILORS S, RESERVES R WHERE S.SID = R.SID AND R.BID = 123; Write queries for 1) Find SIDs of sailors who have reserved Pink Boat; 2) Find the color of the boats reserved by Rajesh. 3) Find names of the sailors who have reserved at least one boat.
DBMS Lab II
Queries (along with sub Queries) using ANY, ALL, IN, EXISTS, NOTEXISTS, UNION, INTERSET, Constraints.
DISTINCT Keyword :- The DISTINCT keyword eliminates the duplicate tuples from the
result records set. Ex:- Find the Names and Ages of all sailors. SQL> SELECT DISTINCT S.SNAME, S.AGE FROM SAILORS S; The answer is a set of rows, each of which is a pair (sname, age). If two or more sailors have the same name and age, the answer still contains just one pair with that name and age.
EXCEPT (MINUS) :- It is a set operator used as set-difference. Our next query illustrates
the set-difference operation. Ex:- Find the sids of all sailor's who have reserved red boats but not green boats. SQL> SELECT S.SID FROM SAILORS S, RESERVES R, BOATS B WHERE S.SID = R.SID AND R.BID = B.BID AND B.COLOR = 'RED' MINUS SELECT S2.SID FROM SAILORS S2, RESERVES R2, BOATS B2 WHERE S2.SID = R2.SID AND R2.BID = B2.BID AND B2.COLOR = 'GREEN; Same query can be written as follows. Since the Reserves relation contains sid information, there is no need to look at the Sailors relation, and we can use the following simpler query SQL> SELECT R.SID FROM BOATS B, RESERVES R WHERE R.BID = B.BID AND B.COLOR = 'RED' MINUS SELECT R2.SID FROM BOATS B2, RESERVES R2 WHERE R2.BID = B2.BID AND B2.COLOR = GREEN;
NESTED QUERIES:- For retrieving data from the tables we have seen the simple & basic
queries. These queries extract the data from one or more tables. Here we are going to see some complex & powerful queries that enables us to retrieve the data in desired manner. One of the most powerful features of SQL is nested queries. A nested query is a query that has another query embedded within it; the embedded query is called a subquery.
IN Operator :- The IN operator allows us to test whether a value is in a given set of elements;
an SQL query is used to generate the set to be tested. Ex:- Find the names of sailors who have reserved boat 103. SQL> SELECT S.SNAME FROM SAILORS S WHERE S.SID IN (SELECT R.SID FROM RESERVES R WHERE R.BID = 103 );
EXISTS Operator :- This is a Correlated Nested Queries operator. The EXISTS operator is
another set comparison operator, such as IN. It allows us to test whether a set is nonempty, an implicit comparison with the empty set. Ex:- Find the names of sailors who have reserved boat number 103. SQL> SELECT S.SNAME FROM SAILORS S WHERE EXISTS (SELECT * FROM RESERVES R WHERE R.BID = 103 AND R.SID = S.SID );
NOT EXISTS Operator :- The NOT EXISTS is used in a opposite manner to EXISTS.
Ex:- Find the names of sailors who have not reserved boat number 103. SQL> SELECT S.SNAME FROM SAILORS S WHERE NOT EXISTS ( SELECT * FROM RESERVES R WHERE R.BID = 103 AND R.SID = S.SID );
Note that IN and NOT IN are equivalent to = ANY and <> ALL, respectively.
op ALL Operator :- It is a comparison operator. It is used to compare a value with all the
elements in a given set. Ex:- Find the sailor's with the highest rating using ALL. SQL> SELECT S.SID FROM SAILORS S WHERE S.RATING >= ALL ( SELECT S2.RATING FROM SAILORS S2 )
4. MAX (A) :- The maximum value in the A column. Ex:- To find age of Oldest Sailor. SQL> SELECT MAX (AGE) FROM SAILORS; 5. MIN (A) :- The minimum value in the A column. Ex:- To find age of Youngest Sailor. SQL> SELECT MIN (AGE) FROM SAILORS; Note that it does not make sense to specify DISTINCT in conjunction with MIN or MAX (although SQL does not preclude this). Write the following queries using Aggregate Functions. 1) Find the average age of sailors with a rating of 10. 2) Count the number of different sailor names. 3) Find the name and age of the oldest sailor. 4) Count the number of Sailors. 5) Find the names of sailors who are older than the oldest sailor with a rating of 10.
ORDER BY Clause :- The ORDER BY keyword is used to sort the result-set by a specified
column. The ORDER BY keyword sorts the records in ascending order by default (we can even use ASC keyword). If we want to sort the records in a descending order, we can use the DESC keyword. The general syntax is SELECT ATT_LIST FROM TABLE_LIST ORDER BY ATT_NAMES [ASC | DESC]; Ex:- 1) Display all the sailors according to their ages. SQL> SELECT * FROM SAILORS ORDER BY AGE; 2) Display all the sailors according to their ratings (topper first). SQL> SELECT * FROM SAILORS ORDER BY RATING DESC; 3) Displays all the sailors according to rating, if rating is same then sort according to age. SQL> SELECT * FROM SAILORS ORDER BY RATING, AGE; Write the query 1) To display names of sailors according to alphabetical order.
2) Displays all the sailors according to rating (Topper First), if rating is same then sort according to age (Older First). 3) Displays all the sailors according to rating (Topper First), if rating is same then sort according to age (Younger First). 4) Displays all the sailors according to rating (Lower Rating First), if rating is same then sort according to age (Younger First).
GROUP BY and HAVING Clauses :- Thus far, we have applied aggregate operations to
all (qualifying) rows in a relation. Often we want to apply aggregate operations to each of a number of groups of rows in a relation, where the number of groups depends on the relation instance. For this purpose we can use Group by clause. GROUP BY:- Group by is used to make each a number of groups of rows in a relation, where the number of groups depends on the relation instances. The general syntax is SELECT [DISTINCT] ATT_LIST FROM TABLE_LIST WHERE CONDITION GROUP BY GROUPING_LIST; Ex:- Find the age of the youngest sailor for each rating level. SQL> SELECT S.RATING, MIN (S.AGE) FROM SAILORS S GROUP BY S.RATING; HAVING :- The extension of GROUP BY is HAVING clause which can be used to specify the qualification over group. The general syntax is SELECT [DISTINCT] ATT_LIST FROM TABLE_LIST WHERE CONDITION GROUP BY GROUPING_LIST HAVING GROUP_CONDITIION; Ex :- Find the age of youngest sailor with age >= 18 for each rating with at least 2 such sailors. SQL> SELECT S.RATING, MIN (S.AGE) AS MINAGE FROM SAILORS S WHERE S.AGE >= 18 GROUP BY S.RATING HAVING COUNT (*) > 1; Write following queries in SQL. 1) For each red boat; find the number of reservations for this boat. 2) Find the average age of sailors for each rating level that has at least two sailors. 3) Find those ratings for which the average age of sailors is the minimum over all ratings.
VIEWS :- A view is a table whose rows are not explicitly stored in the database but are
computed as needed from a view definition. The views are created using CREATE VIEW command. Ex :- Create a view for Expert Sailors ( A sailor is a Expert Sailor if his rating is more than 7). SQL> CREATE VIEW EXPERTSAILOR AS SELECT SID, SNAME, RATING FROM SAILORS WHERE RATING > 7; Now on this view we can use normal SQL statements as we are using on Base tables. Eg:- Find average age of Expert sailors. SQL> SELECT AVG (AGE) FROM EXPERTSAILOR; Write the following queries on Expert Sailor View. 1) Find the Sailors with age > 25 and rating equal to 10. 2) Find the total number of Sailors in Expert Sailor view. 3) Find the number of Sailors at each rating level ( 8, 9, 10). 4) Find the sum of rating of Sailors. 5) Find the age of Oldest as well as Youngest Expert Sailor. If we decide that we no longer need a view and want to destroy it (i.e. removing the definition of view) we can drop the view. A view can be dropped using the DROP VIEW command. To drop the ExpertSailor view. SQL> DROP VIEW EXPERTSAILOR;
DBMS Lab - IV Queries using Conversion functions :- to_char, to_number and to_date. String functions :- Concatenation, lpad, rpad, ltrim, rtrim, lower, upper, initcap, length, substr and instr. Date functions :- Sysdate, next_day, add_months, last_day, months_between, least, greatest, trunc, round, to_char, to_date.
Conversion Functions :- These functions are used to convert the value from one type to
another type. 1) TO_CHAR (N [,FMT]) :- Converts N of numeric data type to Varchar2 datatype using optional number format FMT. Example 1) Convert 12345 to string. SQL> SELECT TO_CHAR(12345) FROM DUAL; 2) Display system date after converting to varchar2 data type. SQL> SELECT TO_CHAR(SYSDATE) FROM DUAL; 3) Display system date in Mon-DD-YYYY format after converting to varchar2 data type. SQL> SELECT TO_CHAR(SYSDATE, Mon-DD-YYYY) FROM DUAL; 2) TO_NUMBER(CHAR) :- This conversion function is used to convert string to number data type. Ex :- Convert string 123.45 to number data type. SQL> SELECT TO_NUMBER(123.45) FROM DUAL; 3) TO_DATE :- Converts character data type data to date type data. Ex:- Display 09-02-2010 converted to DDD-MM-YY format using to_char & to_date functions. SQL> SELECT TO_CHAR(TO_DATE(09-02-2010, DD-MM-YYYY),(DDD-MM-YY) FROM DUAL;
Formats we can use for Date :- Following formats can be used with any function related to dates.
Y YY
Last digit in the year. Last two digits in the year. Year in four digits. Year in characters. Month in digits. Month in characters. Month in formatted with three characters.
YYYY YEAR MM
Day of Week. Day of the Month. Day of the Year. Day name. Hours in 12 Hrs or 24 Hrs format.
String Functions :1) Concatenation :- Concatenates two stings from a given list. CANCAT (CHAR1, CHAR2) EX 1) Concate the string Rajesh with Raghu SQL> SELECT CONCAT (Rajesh, Raghu) FROM DUAL; 2) Concat bid & bname of Boats & display along with color. SQL> SELECT CONCAT(BID, BNAME), COLOR FROM BOATS; 2) LPAD (CHAR1, N, CHAR2) :- Returns CHAR1 left padded to length N with sequence of characters in CHAR2. The default value of CHAR2 is a single blank space. Ex 1) Lpad the string Rajesh to length 30 with the set of characters in string -*- SQL> SELECT LPAD(Rajesh, 30, -*-) FROM DUAL; 2) Lpad the string bname to length 20 with -* set of characters and string color by /. 3) RPAD (CHAR1, N, CHAR2) :- Returns CHAR1 right padded to length N with sequence of characters in CHAR2. The default value of CHAR2 is a single blank space.
Ex 1) Rpad the string Rajesh to length 30 with the set of characters in string *# SQL> SELECT RPAD(Rajesh, 30, *#) FROM DUAL; 2) Rpad the string sname to length 20 with -* set of characters and remaining attributes in normal way. 4) LTRIM (CHAR, SET) :- Returns characters from the left of CHAR by deleting all leftmost characters that appear in set. Ex:- Display all sailors information by removing characters of sname if starts with R. SQL> SELECT SID, LTRIM(SNAME,R) FROM SAILORS; 5) RTRIM (CHAR, SET) :- Returns characters from the right of CHAR by deleting all rightmost characters that appear in set. Ex:- Display all sailors information by removing characters of sname if ends with i. SQL> SELECT SID, RTRIM(SNAME,i) FROM SAILORS; 6) LOWER(CHAR) :- Converts all characters to lowercase characters in a sting CHAR. Ex:- Display all Boats information by showing their names in lower case. SQL> SELECT BID, LOWER(BNAME), COLOR FROM BOATS; 7) UPPER(CHAR) :- Converts all characters to uppercase characters in a sting CHAR. Ex:- Display all Sailors information by showing their names in Upper case. SQL> SELECT SID, UPPER(SNAME), AGE, RATING FROM SAILORS; 8) INITCAP(CHAR) :- Converts first character of each word in a sting CHAR to uppercase. Ex:-1) Display all Sailors information by showing their names in Capitalizing first char. SQL> SELECT SID, INITCAP(SNAME), AGE, RATING FROM SAILORS; 2) Capatilize first letter of each word in rajesh raghu SQL> SELECT INITCAP(rajesh raghu) FROM DUAL;
9) LENGTH (CHAR) :- Returns the length of the string CHAR i.e. number of characters
present in the given string. Ex:-1) Find the number of characters in the string Information Technology
SQL> SELECT LENGTH (Information Technology) FROM DUAL; 2) Display length of string SID, SNAME from Sailors along with their values. SQL> SELECT SID, LENGTH(SID), SNAME, LENGTH(SNAME) FROM SAILORS; 10) SUBSTR(CHAR, M, N) :- It returns substring from CHAR string starting with index M & gives N characters. Ex : Display boats information by starting their names with 3rd character & show only 4 characters. SQL> SELECT BID, SUBSTR(BNAME, 3, 4), COLOR FROM BOATS; 11) INSTR(CHAR1, CHAR2, M, N) :- It searches CHAR1 beginning with Mth character for Nth occurrence of CHAR2 and returns the position after character in CHAR1. If N is negative value, then it searches backwards from the end of CHAR1. The default value of M & N is 1. Ex : Display the index of string ab after 2nd character & 3rd occurrence in the given string abcdabcdababab. SQL> SELECT INSTR (abcdabcdababab,ab, 2, 3) FROM DUAL; 12) TRANSLATE(CHAR, FROM, TO) :- It returns characters with all occurrences of each character in FROM replaced by its corresponding character in TO. Ex :1) Replace a with d in the given string abcdabcdababab. SQL> SELECT TRANSLATE (abcdabcdababab,a,b) FROM DUAL; 2) Display Sailors information by replacing a with i from SNAME, if any. SQL> SELECT SID, TRANSLATE(SNAME,a,i ) FROM SAILORS; 13) REPLACE(CHAR, S, R) :- It returns characters with every occurrences of S replaced with R. If R is not given or NULL, all occurrences of S are removed or deleted. Ex :1) Display BNAME by replacing da with ma. SQL> SELECT REPLACE (BNAME, da, ma) FROM BOATS;
Date Functions :1) SYSDATE :- Displays the system date for a system.
SQL> SELECT SYSDATE FROM DUAL; SQL> SELECT TO_CHAR (SYSDATE, 'DD-MON-YYYY HH:MI:SS') FROM dual; 2) NEXT_DAY (D, DAY) :- Displays next date on DAY after date D. Ex: Display date on Thu after 20th Feb, 2010. SQL> SELECT NEXT_DAY (20-FEB-2010, THU) FROM DUAL; 3) ADD_MONTHS (D, N) :- Returns a date after adding a specified day D with specified number of months N. Ex: Display SID, Day of Reservation by adding 20 months to given day. SQL> SELECT SID, DAY, ADD_MONTHS (DAY, 20) FROM RESERVES; 4) LAST_DAY(D) :- Returns the date corresponding to last day of the month. Ex: Display Sname, Day of Reservation and date corresponding to last date of the month. SQL> SELECT S.SNAME, DAY, LAST_DAY (DAY) FROM SAILORS S, RESERVES R WHERE S.SID = R.SID; 5) MONTHS_BETWEEN (D1, D2) :- Returns number of months between given two dates D1 & D2. Ex: Display SID, Day of Reservation and months between System Date & day of reservation. SQL> SELECT SID, DAY, MONTHS_BETWEEN (SYSDATE, DAY) FROM RESERVES;
PL/SQL PROGRAMMING
Procedural Language/Structured Query Language (PL/SQL) is an extension of SQL.
Steps to Write & Execute PL/SQL As we want output of PL/SQL Program on screen, before Starting writing anything type (Only Once per session)
SQL> SET SERVEROUTPUT ON
Decision making with IF statement :- The general syntax for the using IF--ELSE
statement is IF(TEST_CONDITION) THEN SET OF STATEMENTS ELSE SET OF STATEMENTS END IF;
For Nested IFELSE Statement we can use IF--ELSIFELSE as follows IF(TEST_CONDITION) THEN SET OF STATEMENTS ELSIF (CONDITION) SET OF STATEMENTS END IF;
Ex:- Largest of three numbers. This program can be written in number of ways, here are the two different ways to write the program. 1)
DECLARE A NUMBER := &A; B NUMBER := &B; C NUMBER := &C; BIG NUMBER; BEGIN IF (A > B) THEN
BIG := A; ELSE BIG := B; END IF; IF(BIG < C ) THEN DBMS_OUTPUT.PUT_LINE('BIGGEST OF A, B AND C IS ' || C); ELSE DBMS_OUTPUT.PUT_LINE('BIGGEST OF A, B AND C IS ' || BIG); END IF; END; /
2)
DECLARE A NUMBER := &A; B NUMBER := &B; C NUMBER := &C; BEGIN IF (A > B AND A > C) THEN DBMS_OUTPUT.PUT_LINE('BIGGEST IS ' || A); ELSIF (B > C) THEN DBMS_OUTPUT.PUT_LINE('BIGGEST IS ' || B); ELSE DBMS_OUTPUT.PUT_LINE('BIGGEST IS ' || C); END IF; END; /
LOOPING STATEMENTS:- For executing the set of statements repeatedly we can use
loops. The oracle supports number of looping statements like GOTO, FOR, WHILE & LOOP. Here is the syntax of these all the types of looping statements.
GOTO STATEMENTS
<<LABEL>> SET OF STATEMENTS GOTO LABEL;
FOR LOOP
FOR <VAR> IN [REVERSE] <INI_VALUE>..<END_VALUE> SET OF STATEMENTS END LOOP;
WHILE LOOP
WHILE (CONDITION) LOOP SET OF STATEMENTS END LOOP;
LOOP STATEMENT
LOOP SET OF STATEMENTS IF (CONDITION) THEN EXIT SET OF STATEMENTS END LOOP; While using LOOP statement, we have take care of EXIT condition, otherwise it may go into infinite loop.
Example :- Here are the example for all these types of looping statement where each program prints numbers 1 to 10.
GOTO EXAMPLE
DECLARE
I INTEGER := 1; BEGIN <<OUTPUT>> DBMS_OUTPUT.PUT_LINE(I); I := I + 1; IF I<=10 THEN GOTO OUTPUT; END IF; END; /
WHILE EXAMPLE
DECLARE I INTEGER := 1; BEGIN WHILE(I<=10) LOOP DBMS_OUTPUT.PUT_LINE(I); I := I + 1; END LOOP; END; /
LOOP EXAMPLE
DECLARE I INTEGER := 1; BEGIN LOOP DBMS_OUTPUT.PUT_LINE(I); I := I + 1; EXIT WHEN I=11; END LOOP; END; /
DATA TYPES
Already we know following data types. NUMBER, INTEGER, VARCHAR2, DATE, BOOLEAN, etc. Now lets see few more data types that are useful for writing PL/SQL programs in Oracle.
%TYPE :- %TYPE is used to give data type of predefined variable or database column.
Eg:- itemcode Number(10); icode itemcode%Type; The database column can be used as id Sailors.sid%type
Comments :- In Oracle we can have two types of comments i.e Single Line & Multiline
comments. Single line comment :- It starts with --. -- Comment here
Multiline comment is same as C/C++/JAVA comments where comments are present in the pair of /* & */. /* Comment here */
Inserting values to table :- Here is the example for inserting the values into a database
through PL/SQL Program. Remember that we have to follow all the rules of SQL like Primary Key Constraints, Foreign Key Constraints, Check Constraints, etc. Ex:- Insert the record into Sailors table by reading the values from the Keyboard. DECLARE SID NUMBER (5):=&SID; SNAME VARCHAR2(30):='&SNAME'; RATING NUMBER(5):=&RATING; AGE NUMBER(4,2):=&AGE; BEGIN INSERT INTO SAILORS VALUES(SID, SNAME, RATING, AGE); END; /
BEGIN SELECT SID INTO SID FROM SAILORS WHERE SNAME='&SNAME'; DBMS_OUTPUT.PUT_LINE(SID); EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE(No Sailors with given SID found); WHEN TOO_MANY_ROWS THEN DBMS_OUTPUT.PUT_LINE(More than one Sailors with same name found); END; /
Cursors
Oracle uses temporary work area cursor for storing output of an SQL statement. Cursors are defined as CURSOR C1 IS SELECT SID, SNAME, RATING, AGE FROM SAILORS; OR CURSOR C1 IS SELECT * FROM SAILORS; Generally while using cursors we have to Open the cursor then extract one row (record) from the cursor using Fetch operation, do the necessary operations on the Record. After completing the work Close the cursor. But if we want to do automatic opening & closing to cursor then we can use FOR loop in cursor.
Suppose we want to display all sailors information according to their rating with proper heading. (eg: Sailors with rating 1.. etc) then we can write program as follows. Ex:- Display records according to rating with proper heading.
DECLARE I INTEGER:=1; CURSOR C1 IS SELECT * FROM SAILORS ORDER BY RATING; Z C1%ROWTYPE; BEGIN WHILE(I<=10)LOOP DBMS_OUTPUT.PUT_LINE(SAILORS WITH RATING||I); FOR Z IN C1 LOOP IF(Z.RATING=I)THEN DBMS_OUTPUT.PUT_LINE(Z.SID|| ||Z.SNAME|| ||Z.AGE|| ||Z.RATING); END IF; END LOOP; I:=I+1; END LOOP; END; /
FOR Y IN C3 LOOP DBMS_OUTPUT.PUT_LINE(Y.SID|| ||Y.BID|| ||Y.DAY); END LOOP; ELSE DBMS_OUTPUT.PUT_LINE(NO SUCH TABLE EXISTS); END IF; END; /
Updating the Records :- Similar to inserting the values as well as selecting the values we
can use the PL/SQL programming for updating the records in the given table. Ex:- To update rating of sailors by 2 if rating is less than 5, by 1 if rating is >5 and doesnt change the rating if it is equal to 10. DECLARE CURSOR C1 IS SELECT * FROM SAILORS; Z C1%ROWTYPE; BEGIN FOR Z IN C1 LOOP IF (Z.RATING<5) THEN UPDATE SAILORS SET RATING=RATING+2 WHERE SID=Z.SID; ELSIF (Z.RATING>5 AND Z.RATING<10) THEN UPDATE SAILORS SET RATING=RATING+1 WHERE SID=Z.SID; END IF; END LOOP; FOR Z IN C1 LOOP DBMS_OUTPUT.PUT_LINE (Z.SID|| ||Z.RATING); END LOOP; END; /
Deleting the Records :- Similar to inserting and updating the values as well as selecting the
values we can use the PL/SQL programming for deleting the records from the given table. Ex:- Write a program to delete records from sailors table by reading SID from Keyboard. DECLARE BEGIN DELETE FROM SAILORS WHERE SID=&SID; END; /
Ex:- suppose we want to display all sailors information according to their rating with proper heading. (eg: Sailors with rating 1.. etc). Already we have seen same program with parameters to the cursor. Following program illustrates how we can pass parameters to the cursor.
Output
SQL> @Cur_Par SAILORS WITH RATING 1 ARE 4 Hemant 18 1 SAILORS WITH RATING 2 ARE 5 Rajendra 30 2 SAILORS WITH RATING 3 ARE 6 Satish 20 3 SAILORS WITH RATING 4 ARE 7 Shrikant 21 4 SAILORS WITH RATING 5 ARE 8 Shabaz 19 5 10 Kaushal 20 5 SAILORS WITH RATING 6 ARE 12 RAJ 19 6 SAILORS WITH RATING 7 ARE 1 aravind 19 7 SAILORS WITH RATING 8 ARE 9 Guru 36 8 SAILORS WITH RATING 9 ARE 3 Vijay 32 9 SAILORS WITH RATING 10 ARE 2 Amar 87 10 11 SUNNY 20 10
Output
SQL> @Raise_Application_Error ENTER VALUE FOR A: 12 OLD 2: A INTEGER:=&A; NEW 2: A INTEGER:=12; ENTER VALUE FOR B: 2 OLD 3: B INTEGER:=&B; NEW 3: B INTEGER:=2; RESULT IS :6 PL/SQL procedure successfully completed. SQL> @Raise_Application_Error ENTER VALUE FOR A: 15 OLD 2: A INTEGER:=&A; NEW 2: A INTEGER:=15; ENTER VALUE FOR B: 0 OLD 3: B INTEGER:=&B; NEW 3: B INTEGER:=0; DECLARE * ERROR at line 1: ORA-20001: DIVISION BY ZERO ORA-06512: at line 8
BEGIN INSERT INTO SAILORS VALUES('32','HEMANT',10, 30); UPDATE SAILORS SET SNAME='RAJENDRA' WHERE SID='10'; SAVEPOINT S1; DELETE FROM SAILORS WHERE SID='11';
ROLLBACK TO S1; COMMIT; END; / (You can even read these values from Keyboard)
Procedure in PL/SQL
Procedures are written for doing specific tasks. The general syntax of procedure is CREATE OR REPLACE PROCEDURE <Pro_Name> (Par_Name1 [IN/OUT/ IN OUT] Par_Type1, .) IS (Or we can write AS) Local declarations; BEGIN PL/SQL Executable statements; . EXCEPTION Exception Handlers; END <Pro_Name>; Mode of parameters 1) IN Mode :- IN mode is used to pass a value to Procedure/Function. Inside the procedure/function, IN acts as a constant and any attempt to change its value causes compilation error. 2) OUT Mode : The OUT parameter is used to return value to the calling routine. Any attempt to refer to the value of this parameter results in null value. 3) IN OUT Mode : IN OUT parameter is used to pass a value to a subprogram and for getting the updated value from the subprogram. For writing Procedures we can directly type at SQL prompt or create a file. SQL> ed File_Name Type & save procedure. To create Procedure (before calling from other program.) SQL> @File_Name To use/call procedure, write a PL/SQL code and include call in the code using Pro_Name(Par_List); Or you can execute from SQL Prompt as SQL>execute Pro_Name(Par_List)
For dropping Procedure/Function (Function described next) SQL>DROP PROCEDURE Pro_Name; SQL>DROP FUNCTION Fun_Name; Examples 1) Simple program to illustrate Procedure.
-- Assume file name P1 CREATE OR REPLACE PROCEDURE P1(A NUMBER) AS BEGIN DBMS_OUTPUT.PUT_LINE('A:'||A); END P1; / Now write PL/SQL code to use procedure in separate file. -- Assume file name testP1 DECLARE BEGIN P1(100); END; /
Output
SQL> @P1 Procedure created. SQL>@testP1 A:100 PL/SQL procedure successfully completed.
Output
SQL> @P2 Procedure created. SQL>@testP2 X:10 A:10
X:10 PL/SQL procedure successfully completed. 3) Program to illustrate Procedure with OUT mode parameter. -- Assume file name P3 CREATE OR REPLACE PROCEDURE P3(A OUT NUMBER) AS BEGIN A:=100; DBMS_OUTPUT.PUT_LINE('A:'|| A); END P3; / -- Assume file name testP3 DECLARE X NUMBER; BEGIN X:=50; DBMS_OUTPUT.PUT_LINE('X:'||X); P3(X); DBMS_OUTPUT.PUT_LINE('X:'||X); END; /
Output
SQL> @P3 Procedure created. SQL>@testP3 X:50 A:100 X:100 PL/SQL procedure successfully completed. 4) Program to illustrate Procedure with OUT mode parameter. -- Assume file name P4 CREATE OR REPLACE PROCEDURE P4(A OUT NUMBER) AS BEGIN DBMS_OUTPUT.PUT_LINE('A:'||A); END P4; / -- Assume file name testP4 DECLARE X NUMBER; BEGIN X:=10; DBMS_OUTPUT.PUT_LINE('X:'||X);
Output
SQL> @P4 Procedure created. SQL>@testP4 X:10 A: X: PL/SQL procedure successfully completed. 5) Program to illustrate Procedure with IN OUT mode parameter. --Assume file name P5 CREATE OR REPLACE PROCEDURE P5(A IN OUT NUMBER) AS BEGIN DBMS_OUTPUT.PUT_LINE('A:' || A); END P5; / -- Assume file name testP5 DECLARE X NUMBER; BEGIN X:=10; DBMS_OUTPUT.PUT_LINE('X:'|| X); P5(X); DBMS_OUTPUT.PUT_LINE('X:'|| X); END; /
Output
SQL> @P5 Procedure created. SQL>@testP5 X:10 A:10 X:10 PL/SQL procedure successfully completed.
Functions in PL/SQL
Similar to Procedure we can create Functions which can return one value to the calling program. The syntax of function is CREATE OR REPLACE FUNCTION <Fun_Name> (Par_Name1 [IN/OUT/ IN OUT] Par_Type1, .) RETURN return_datatype IS Local declarations; BEGIN PL/SQL Executable statements; . EXCEPTION Exception Handlers; END <Fun_Name>; For writing Function we can directly type at SQL prompt or create a file. SQL> ed File_Name Type & save Function. To create Function (before calling from other program.) SQL> @File_Name To use/call Function we have two ways. 1) Write a PL/SQL code and include call in the code using x=Fun_Name(Par_List); 2) You can execute from SQL Prompt as a select query SQL>Select Fun_Name(Par_List) from Dual; Ex :- Program to illustrate Function. (Finding Square of a number) -- Assume file name Fun CREATE OR REPLACE FUNCTION FUN(A NUMBER) RETURN NUMBER IS BEGIN RETURN (A*A); END FUN; / -- Assume file name testFun DECLARE X NUMBER:=&X; S NUMBER; BEGIN S:=FUN(X); DBMS_OUTPUT.PUT_LINE('SQUARE OF A NUMBER'|| S); END; /
Output
SQL> @Fun
Dept of IT, BVRIT, Narsapur
Function created. SQL> @testFun ENTER VALUE FOR X: 10 OLD 2: X NUMBER:=&X; NEW 2: X NUMBER:=10; SQUARE OF A NUMBER100 PL/SQL procedure successfully completed.