Dbms Complete Lab Manual
Dbms Complete Lab Manual
A Helpful Hand
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
DDL commands:
1. The Create Table Command: - it defines each column of the table uniquely. Each column has minimum of three attributes, a name , data type and size. Syntax: Create table <table name> (<col1> <datatype>(<size>),<col2> <datatype><size>)); Ex: create table emp(empno number(4) primary key, ename char(10)); 2. Modifying the structure of tables. a)add new columns Syntax: Alter table <tablename> add(<new col><datatype(size),<new col>datatype(size)); Ex: alter table emp add(sal number(7,2)); 3. Dropping a column from a table. Syntax: Alter table <tablename> drop column <col>; Ex: alter table emp drop column sal; 4. Modifying existing columns. Syntax: Alter table <tablename> modify(<col><newdatatype>(<newsize>));
4
WWW.CSEROCKZ.COM
5. Renaming the tables Syntax: Rename <oldtable> to <new table>; Ex: rename emp to emp1; 6. truncating the tables. Syntax: Truncate table <tablename>; Ex: trunc table emp1; 7. Destroying tables. Syntax: Drop table <tablename>; Ex: drop table emp;
DML commands:
8. Inserting Data into Tables: - once a table is created the most natural thing to do is load this table with data to be manipulated later. Syntax 1:
5
WWW.CSEROCKZ.COM
Syntax 3: insert into <tablename> values(<val 1>,<val 2>.,<val n>); Ex 1: Insert into skc (sname,rollno,class,dob,fee_paid) values(sri,104B,cse,27-feb-05,10000.00); Ex 2: insert into skc values(&sname,&roll no,&class); enter sname:sri enter roll no:104B enter class:cse 1 row created. Ex 3: insert into skc values(sri,104B,cse,27-feb-05,10000.00); 9. Delete operations. a) remove all rows Syntax: delete from <tablename>; b) removal of a specified row/s Syntax:
6
WWW.CSEROCKZ.COM
b) updating seleted records. Syntax: Update <tablename> set <col>=<exp>,<col>=<exp> where <condition>; 11. Types of data constrains. a) not null constraint at column level. Syntax: <col><datatype>(size)not null b) unique constraint Syntax: Unique constraint at column level. <col><datatype>(size)unique; c) unique constraint at table level: Syntax: Create table tablename(col=format,col=format,unique(<col1>,<col2>); d) primary key constraint at column level
7
WWW.CSEROCKZ.COM
f) foreign key constraint at column level. Syntax: <col><datatype>(size>) references <tablename>[<col>]; g) foreign key constraint at table level Syntax: foreign key(<col>[,<col>]) references <tablename>[(<col>,<col>) h) check constraint check constraint constraint at column level. Syntax: <col><datatype>(size) check(<logical expression>) i) check constraint constraint at table level. Syntax: check(<logical expression>)
DQL Commands:
12. 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.
8
WWW.CSEROCKZ.COM
b) selected rows and all columns: Syntax: select * from <tablename> where <condition>; c) selected columns and selected rows Syntax: select <col1>,<col2> from <tablename> where<condition>; 14. Sorting data in a table. Syntax: Select * from <tablename> order by <col1>,<col2> <[sortorder]>;
DCL commands:
Oracle provides extensive feature in order to safeguard information stored in its tables from unauthoraised viewing and damage.The rights that allow the user of some or all oracle resources on the server are called privileges. a) Grant privileges using the GRANT statement The grant statement provides various types of access to database objects such as tables,views and sequences and so on. Syntax: GRANT <object privileges> ON <objectname>
9
WWW.CSEROCKZ.COM
WEEK-1
CREATING,ALTERING AND DROPPING TABLES AND INSERTING ROWS INTO A TABLE (USE CONSTRAINTS WHILE CREATING TABLES) EXAMPLES USING SELECT COMMAND .
EXAMPLE 1:
CREATING A STUDENT RELATION TABLE WITH ALL DATATYPES:
SQL> create table student252( sid number(5), sname varchar(20), sbranch char(5), dob date, spercent number(3,2)); Table created.
RELATIONAL SCHEMA FOR STUDENT RELATION : SQL> desc student252; Name Null? Type ----------------------------------------- -------- ---------------------------SID NUMBER(5)
10
WWW.CSEROCKZ.COM
INSERT THE RECORDS INTO STUDENT RELATION: METHOD 1: SQL>Insert into Student252(sid,sname,sbranch,dob,spercent) values(104,sri,,cse,27feb-05,70); 1 row created. METHOD 2: SQL>Insert into Student252 values(104,sri,,cse,27-feb-05,70); 1 row created.
METHOD 3: SQL>Insert into Student252(sid,sname,sbranch,dob,spercent) values(&sid, &sname,&sbranch,&dob,&spercent); 1 row created. METHOD 4: SQL>Insert into Student252(sid,sname,sbranch,dob,spercent) values(&sid, &sname,&sbranch,&dob,&spercent); 1 row created. QUERY THE TABLE VALUES: ALL ROWS AND ALL COLUMNS:
SNAME SBRANCH DOB SPERCENT --------------- --------------------- --------------- -------------------ravi it 30-1-95 60 teja cse 21-07-87 55 kiran mech 12-05-92 60 sri cse 30-07-90 70
11
WWW.CSEROCKZ.COM
WEEK 2 (cont1) 1) Creation, altering and dropping tables and inserting rows into a table (use constraints while creating tables) examples using SELECT command.
MODIFYING THE STRUCTURE OF TABLE ADDING A NEW COLUMN SQL> ALTER TABLE Emp252 ADD (age number(3), phno number(10)); Table altered.
MODIFYING EXISTING COLUMN SQL> ALTER TABLE Emp252 MODIFY (phno varchar(20)); Table altered. DROPING A COLUMN SQL> ALTER TABLE Emp252 DROP COLUMN phno; Table altered. QUERY FOR THE TABLE VALUES SQL> SELECT * FROM Emp252; ENO ENAME ESAL DEPTNO AGE ----- -------------------- ---------- ---------- ---------30 ravi 51000 3 31 teja 31000 2
12
WWW.CSEROCKZ.COM
10 rows selected. UPDATING ENTIRE COLUMN SQL> UPDATE Emp252 SET age=18; 10 rows updated. QUERY THE TABLE VALUES SQL> SELECT * FROM Emp252;
ENO ENAME ESAL DEPTNO AGE ----- -------------------- ---------- ---------- ---------30 ravi 51000 3 18 31 teja 31000 2 18 29 kiran 31200 1 18 45 allen 41000 3 18 33 sajith 51000 4 18 46 geetha 11000 4 18 90 veena 16000 3 18 85 pragna 61000 1 18 84 harsha 91000 3 18 40 sanjeev 1500 13 18 10 rows selected. RENAMING THE TABLE: SQL> RENAME Emp252 TO Emp1252; Table renamed.
13
WWW.CSEROCKZ.COM
DESCRIBE A STUDENT TABLE SQL> desc Dept252; Name Null? Type ----------------------------------------- -------- ---------------------------DNAME VARCHAR2(10) DNO CHAR(5) DLOC VARCHAR2(25) DROPING THE TABLE SQL> DROP TABLE Dept252; Table dropped.
WEEK 3 (cont1) 1) Creation, altering and dropping tables and inserting rows into a table (use constraints while creating tables) examples using SELECT command.
14
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
Example 2 CREATING A TABLE WITH PRIMARY KEY CONSTRAINT: SQL> CREATE TABLE mdept252 (dno NUMBER(5), dname CHAR(10), dloc VARCHAR(10), PRIMARY KEY (dno)); Table created.
17
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
INSERING RECORDS INTO DETAIL EMPLOYEE TABLE: SQL> INSERT INTO detailemp252 VALUES (2, 'ravi', 50000); INSERT INTO detailemp252 VALUES (2, 'ravi', 50000) * ERROR at line 1:
19
WWW.CSEROCKZ.COM
20
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
CREATING AN ITEM TABLE USING CONSTRAINTS: SQL> CREATE TABLE itm252 (ino NUMBER(3), iname VARCHAR(10), iprice NUMBER(4,3), qtyonhand VARCHAR(5), CONSTRAINT itm252_ino_pkkey PRIMARY KEY (ino), CONSTRAINT itm230_qtyoh_chk CHECK (qtyonhand>1)); Table created.
22
WWW.CSEROCKZ.COM
SQL> / Enter value for ino: 2 Enter value for iname: 'powder' Enter value for iprice: 3.00 Enter value for qtyonhand: 0 old 1: INSERT INTO itm252 VALUES (&ino, &iname, &iprice, &qtyonhand) new 1: INSERT INTO itm252 VALUES (2, 'powder', 3.00, 0) INSERT INTO itm252 VALUES (2, 'powder', 3.00, 0)
23
WWW.CSEROCKZ.COM
1* CREATE TABLE invoice252(ivnno NUMBER(5), itemno NUMBER(5), qty NOT NULL, CONSTRAINT invoice252_ivnno_pkkey PRIMARY KEY(ivnno), CONSTRAINT FOREIGN KEY(itemno) REFERENCES cust252) SQL> desc cust252; Name Null? Type ----------------------------------------- -------- ---------------------------CNUM NOT NULL NUMBER(5) CNAME VARCHAR2(10) STATE VARCHAR2(10) PHNO NUMBER(5) CREATING A INVOICE TABLE USING CONSTRAINTS: SQL> CREATE TABLE invoice252 (ivnno NUMBER(5), itemno NUMBER(5), qty NUMBER(5) NOT NULL, CONSTRAINT invoice252_ivnno_pkkey PRIMARY KEY (ivnno), CONSTRAINT fk_inv252 FOREIGN KEY (itemno) REFERENCES cust252 (cnum)) Table created. SQL> CREATE TABLE invitm252 (invno NUMBER(5), itmno NUMBER(5), qty NUMBER(5) NOT NULL, CONSTRAINT invitm252_invno_itmno_pkkey PRIMARY KEY (invno, itmno));
24
WWW.CSEROCKZ.COM
WEEK 4 2) Queries (along with subqueries) using ANY, ALL, IN, EXISTS, NOT EXISTS, UNIQUE, INTERSECT, Constraints. Example: select the rollno and name of the student who secured 4th rank in the class
TABLE DEFINITIONS SQL> CREATE TABLE Customer ( cust_no NUMBER(4) PRIMARY KEY, last_name VARCHAR2(20), first_name VARCJHAR2(20) NOT NULL, address1 VARCHAR2(20), address2 VARCHAR2(20), city VARCHAR2(3), state VARCHAR2(20), pin VARCHAR2(6), birth_date DATE, status VARCHAR2(1), CHECH (status IN (V, I, A)) ); Table created. Insert the following data: 1 row created.
CUST NO 1001 1002 1003 LAST NAME UDUPI KUMAR BAHADUR FIRST NAME RAJ RAJ RAJ ADDRESS1 UPENDRABAU G SHANTHI VILLA ADDRESS2 NEAR KALPANA NEAR CITY UDP P UDP STATE KARNARAT A KARNATAK PIN 57610 1 57610 BIRTH DATE 12DEC-62 1-AUGSTATUS A A V
25
WWW.CSEROCKZ.COM
QUERIES 1) To list all the fields from the table Customer. SEELCT * FROM Customer; 2) To list the first name, last name. SELECT first_name, last_name FROM Customer; 3) To list the first name and last name of persons in Karnataka. SELECT first_name, last_name FROM Customer WHERE state = KARNATAKA;
4)
To list all the columns for invalid persons. SELECT * FROM Customer WHERE status = I; To list the names of active customers. SELECT first_name, last_name FROM Customer WHERE status = A; To list the name and address using concatenation. SELECT first_name || || last_name, address1 || , || address2 || , || city || , || state || - || pin FROM Customer; To select records where the pin code has not been entered. SELECT * FROM Customer
26
5)
6)
7)
WWW.CSEROCKZ.COM
To select the single occurrence of any value from the table. SELECT DISTINCT state FROM Customer; To select rows of valid customers from Karnataka. SELECT * FROM Customer WHERE state = KARNATAKA AND status = V; To select rows of customers from Karnataka or Kerala. SELECT * FROM Customer WHERE state = KARNATAKA OR state = KERALA; To sort the customer data in the alphabetic order of state. SELECT state, first_name, last_name, pin FROM Customer ORDER BY state; To sort in the descending order. SELECT state, first_name, last_name, pin FROM Customer ORDER BY state DESC; To sort the customer data, state wise and within state by the last name. SELECT state, first_name, last_name, pin FROM Customer ORDER BY state, last_name; To retrieve records of Karnataka customers who are valid. SELECT * FROM Customer WHERE UPPER(state) = KARNATAKA AND UPPER(status) = V; To retrieve records of Karnataka/Kerala customers. SELECT * FROM Customer WHERE UPPER(state) = KARNATAKA
27
9)
10)
11)
12)
13)
14)
15)
WWW.CSEROCKZ.COM
To retrieve records of Karnataka/Kerala customers who are active. SELECT * FROM Customer WHERE (UPPER(state) = KARNATAKA OR UPPER(state) = KERALA) AND UPPER(status) = A; To retrieve records of Karnataka customers with pin code 576101. SELECT * FROM Customer WHERE LOWER(state) = karnataka AND pin = 576101; To retrieve rows where the state name begins with K and followed by any other character. SELECT first_name, last_name, state FROM Customer WHERE state LIKE K%; To retrieve rows where the first name contains the word RAJ embedded in it. SELECT first_name, last_name, state FROM Customer WHERE first_name LIKE %RAJ%; To retrieve rows where the address2 contains the word UDUPI or UDIPI in which the 3rd character may be anything. SELECT first_name, last_name, state FROM Customer WHERE address2 LIKE UD_PI; To retrieve rows where the cust_no has data representing any value between 1003 and 1005, both numbers included. SELECT * FROM Customer WHERE cust_no BETWEEN 1003 AND 1005; To retrieve rows of persons born after 9-JAN-70 and before 1-AUG-96. SELECT * FROM Customer WHERE birth_date BETWEEN 10-JAN-70 AND 31-JUL-96;
17)
18)
19)
20)
21)
22)
28
WWW.CSEROCKZ.COM
To retrieve rows where the city has data which is equal to UDP or MNG or BNG or PJM or MAR. SELECT * FROM Customer WHERE city IN (UDP, MNG, BNG, PJM, MAR);
TABLE DEFINITIONS SQL> CREATE TABLE Emp ( emp_no NUMBER, emp_name VARCHAR(20), join_date DATE, join_basic NUMBER(7, 2), PRIMARY KEY (emp_no) ); Table created.
Insert the following data: EMP NO 1001 1002 1003 1004 1005 EMP NAME Subhas bose Nadeem shah Charles babbage Shreyas kumar George boole JOIN DATE 01-JUN-96 01-JUN-96 01-JUN-96 01-JUL-96 01-JUL-96 JOIN BASIC 3000 2500 3000 2500 2800
SQL> CREATE TABLE Salary ( emp_no NUMBER, basic NUMBER(7, 2), commission NUMBER(7, 2), deduction NUMBER(7, 2), salary_date DATE, FOREIGN KEY (emp_no) REFERENCES Emp ); Table created. Insert the following data: EMP NO 1001 1002 1003 BASIC 3000 2500 3000 COMMISSION 200 120 500 DEDUCTION 250 200 290 SALARY DATE 30-JUN-96 30-JUN-96 30-JUN-96 29
WWW.CSEROCKZ.COM
QUERIES 1) To sum the salary of each employee. SELECT emp_no, SUM(basic) FROM salary GROUP BY emp_no;
2)
To sum the salary of each employee and sort it on the sum of basic. SELECT emp_no, SUM(basic) FROM salary GROUP BY emp_no ORDER BY SUM(basic); To sum the salary of each employee and sort it in descending order on the sum of basic. SELECT emp_no, SUM(basic) FROM salary GROUP BY emp_no ORDER BY SUM(basic) DESC; To sum the salary of each employee and sort it in descending order on the sum of basic. Display name also SELECT s.emp_no, e.emp_name, SUM(s.basic) FROM salary s, emp e WHERE s.emp_no = e.emp_no GROUP BY s.emp_no, e.emp_no ORDER BY SUM(s.basic) DESC;
3)
4)
5) To group the data by average salary of each employee. SELECT s.emp_no, INITCAP(e.emp_name), AVG(s.basic) FROM salary s, emp e WHERE s.emp_no = e.emp_no GROUP BY s.emp_no, e.emp_no ORDER BY AVG(s.basic); 6) To group the basic by month.
30
WWW.CSEROCKZ.COM
WEEK 5
31
WWW.CSEROCKZ.COM
Queries (along with subqueries) using ANY, ALL, IN, EXISTS, NOT EXISTS, UNIQUE, INTERSECT, Constraints. Example: select the rollno and name of the student who secured 4th rank in the class.
3) Queries using Aggregate functions (COUNT, SUM, AVG, MAX and MIN), GROUP BY, HAVING and Creation and Dropping of Views. 4) Queries using Conversions, functions (to_char, to_num, and to_date), string function (Conactenation, lpad, rpad, ltrim, rtrim, lower, upper, initcap, length, substr, and instr), date functions (sysdate, next_day, add_months, last_day, months_between, least, greatest, trunk, round, to_char, to_date).
TABLE DEFINITIONS SQL> CREATE TABLE Emp ( emp_no NUMBER, emp_name VARCHAR(20), join_date DATE, join_basic NUMBER(7, 2), PRIMARY KEY (emp_no) ); Table created. Insert the following data:
EMP NO 1001 1002 1003 1004 1005 EMP NAME Subhas bose Nadeem shah Charles babbage Shreyas kumar George boole JOIN DATE 01-JUN-96 01-JUN-96 01-JUN-96 01-JUL-96 01-JUL-96 JOIN BASIC 3000 2500 3000 2500 2800
SQL> CREATE TABLE Salary ( emp_no NUMBER, basic NUMBER(7, 2), commission NUMBER(7, 2), deduction NUMBER(7, 2), salary_date DATE, FOREIGN KEY (emp_no) REFERENCES Emp );
32
WWW.CSEROCKZ.COM
QUERIES 11) To sum the salary of each employee. SELECT emp_no, SUM(basic) FROM salary GROUP BY emp_no;
12)
To sum the salary of each employee and sort it on the sum of basic. SELECT emp_no, SUM(basic) FROM salary GROUP BY emp_no ORDER BY SUM(basic); To sum the salary of each employee and sort it in descending order on the sum of basic. SELECT emp_no, SUM(basic) FROM salary GROUP BY emp_no ORDER BY SUM(basic) DESC; To sum the salary of each employee and sort it in descending order on the sum of basic. Display name also SELECT s.emp_no, e.emp_name, SUM(s.basic) FROM salary s, emp e WHERE s.emp_no = e.emp_no GROUP BY s.emp_no, e.emp_name ORDER BY SUM(s.basic) DESC;
13)
14)
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
Queries (along with subqueries) using ANY, ALL, IN, EXISTS, NOT EXISTS, UNIQUE, INTERSECT, Constraints. Example: select the rollno and name of the student who secured 4th rank in the class.
3) Queries using Aggregate functions (COUNT, SUM, AVG, MAX and MIN), GROUP BY, HAVING and Creation and Dropping of Views. 4) Queries using Conversions, functions (to_char, to_num, and to_date), string function (Conactenation, lpad, rpad, ltrim, rtrim, lower, upper, initcap, length, substr, and instr), date functions (sysdate, next_day, add_months, last_day, months_between, least, greatest, trunk, round, to_char, to_date).
TABLE DEFINITIONS Branch Schema <branch-name, branch-city, assets> Customer Schema <customer-name, customer-street, customer-city> Loan Schema <loan-number, branch-name, amount> Borrower Schema <customer-name, loan-number> Account Scheme <account-number, branch-name, balance> Depositor Scheme <customer-name, account-number>
BRANCH TABLE Branch Name Brighton Downtown Mianus North Town Perryridge Pownal Redwood Round Hill Branch City Brooklyn Brooklyn Horseneck Rye Horseneck Bennington Palo Alto Horseneck Assets 7100000 9000000 400000 3700000 1700000 300000 2100000 800000
35
WWW.CSEROCKZ.COM
BORROWER TABLE Customer Name Adams Curry Hayes Jackson Jones Smith Smith Loan Number l-16 L-93 L-15 L-14 L-17 L-11 L-23
36
WWW.CSEROCKZ.COM
L-17
Branch Name Downtown Perryridge Brighton Mianus Brighton Redwood Round Hill
WWW.CSEROCKZ.COM
and Rs100,000. SELECT loan_number FROM Loan WHERE amount BETWEEN 90000 AND 100000; Or SELECT loan_number FROM Loan WHERE amount <= 100000 AND amount >= 90000;
7) Find all loan numbers for loans with loan amounts not between
Rs90,000 and Rs100,000. SELECT loan_number FROM Loan WHERE amount NOT BETWEEN 90000 AND 100000;
8) For all customers who have a loan from the bank, find their names, loan
numbers and loan amounts. SELECT customer_name, Borrower.loan_number, amount FROM Borrower, Loan WHERE Borrower.loan_number = Loan.loan_number; Or SELECT customer_name, Borrower.loan_number AS loan_id, amount FROM Borrower, Loan
38
WWW.CSEROCKZ.COM
at the Perryridge branch. SELECT customer_name, Borrower.loan_number, amount FROM Borrower, Loan WHERE Borrower.loan_number = Loan.loan_number AND branch_name = Perryridge; Or SELECT customer_name, T.loan_number, S.amount FROM Borrower AS T, Loan AS S WHERE T.loan_number = S.loan_number AND branch_name = Perryridge;
10) Find the names of all branches that have assets greater than atleast
one branch located in Brooklyn. SELECT DISTINCT T.branch_name FROM Branch as T, Branch as S WHERE T.assets > S.assets AND S.branch_city = Brooklyn;
11) Find the names of all customers whose street address includes the
substring Main. SELECT customer_name FROM Customer WHERE customer_street LIKE %Main%;
12) To list in alphabetic order all customers who have a loan at the
Perryridge branch. SELECT DISTINCT customer_name FROM Borrower B, Loan L WHERE B.loan_number = L.loan_number AND branch_name = Perryridge ORDER BY customer_name;
WWW.CSEROCKZ.COM
without duplicates. (SELECT customer_name FROM Depositor) UNION (SELECT customer_name FROM Borrower);
15) To find all customers having a loan, an account or both at the bank,
with duplicates. (SELECT customer_name FROM Depositor) UNION ALL (SELECT customer_name FROM Borrower);
16) To find all customers having both a loan and an account at the bank,
without duplicates. (SELECT customer_name FROM Depositor) INTERSECT (SELECT customer_name FROM Borrower);
17) To find all customers having a loan, an account or both at the bank,
with duplicates. (SELECT customer_name FROM Depositor) INTERSECT ALL (SELECT customer_name FROM Borrower);
40
WWW.CSEROCKZ.COM
without duplicates. (SELECT DISTINCT customer_name FROM Depositor) EXCEPT (SELECT customer_name FROM Borrower);
19) To find all customers who have an account but no loan at the bank,
with duplicates. (SELECT DISTINCT customer_name FROM Depositor) EXCEPT ALL (SELECT customer_name FROM Borrower);
SELECT branch_name, COUNT(DISTINCT customer_name) FROM Depositor D, Account A WHERE D.account_number = A.account_number GROUP BY branch_name;
23) Find the number of depositors for each branch where average account
balance is more than Rs 1200. SELECT branch_name, COUNT(DISTINCT customer_name) FROM Depositor D, Account A
41
WWW.CSEROCKZ.COM
SELECT customer_name FROM Borrower WHERE customer_street IN (SELECT customer_name FROM Depositor);
29) Find all customers who have both an account and a loan at the
WWW.CSEROCKZ.COM
have an account the bank. SELECT DISTINCT customer_name FROM Borrower WHERE customer_name NOT IN (SELECT customer_name FROM Depositor);
31) Find the names of customers who do have a loan at the bank, and
whose names are neither Smith nor Jones. SELECT DISTINCT customer_name FROM Borrower WHERE customer_name NOT IN (Smith, Jones);
32) Find the names of all branches that have assets greater than those of
at least one branch located in Brooklyn. SELECT DISTINCT T.branch_name FROM Branch AS T, Branch AS S WHERE T.assets > S.assets AND S.branch_city = Brooklyn;
33) Find the names of all branches that have assets greater than that of
WWW.CSEROCKZ.COM
34) Find all customers who have an account at all the branches located in
Brooklyn. SELECT DISTINCT S.customer_name FROM Depositor AS D WHERE NOT EXISTS ((SELECT branch_name FROM Branch WHERE branch_city = Brroklyn) EXCEPT (SELECT R.branch_name FROM Depositor AS T, Account AS R WHERE T.account_number = R.account_number AND D.customer_name = t.customer_name));
35) Find all customers who have at most one account at the Perryridge
branch. SELECT T.customer_name FROM Depositor AS T WHERE UNIQUE (SELECT R.customer_name FROM Depositor AS R, Account AS A WHERE T.customer_name = R.customer_name AND R.account_number = A.account_number AND A.branch_name = Perryridge);
36) Find all customers who have at least two accounts at the Perryridge
branch. SELECT DISTINCT T.customer_name FROM Depositor AS T WHERE NOT UNIQUE (SELECT R.customer_name FROM Depositor AS R, Account AS A WHERE T.customer_name = R.customer_name AND R.account_number = A.account_number
44
WWW.CSEROCKZ.COM
average account balance is greater than 1200. SELECT branch_name, avg_balance FROM (SELECT branch_name, AVG(balance) FROM Account GROUP BY branch_name) AS Branch_avg(branch_name, avg_balance) WHERE avg_balance > 1200;
38) Find the maximum across all branches of the total balance at each
branch. SELECT MAX(tot_balance) FROM (SELECT branch_name, SUM(balance) FROM Account GROUP BY branch_name) AS Branch_total(branch_name, tot_balance);
39) Find the all customers who have an account but no loan at the bank.
SELECT d-CN FROM (Depositor LEFT OUTER JOIN Borrower ON Depositor.customer_name = Borrower.customer_name) AS db1(d-CN, account_number, b-CN, loan_number) WHERE b-CN is null;
40) Find the all customers who have either an account or a loan (but not
both) at the bank. SELECT customer_name FROM (Depositor NATURAL FULL OUTER JOIN Borrower) WHERE account_number IS NULL OR loan_number IS NULL;
WEEK 7
45
WWW.CSEROCKZ.COM
Queries (along with subqueries) using ANY, ALL, IN, EXISTS, NOT EXISTS, UNIQUE, INTERSECT, Constraints. Example: select the rollno and name of the student who secured 4th rank in the class.
6) Queries using Aggregate functions (COUNT, SUM, AVG, MAX and MIN), GROUP BY, HAVING and Creation and Dropping of Views. 7) Queries using Conversions, functions (to_char, to_num, and to_date), string function (Conactenation, lpad, rpad, ltrim, rtrim, lower, upper, initcap, length, substr, and instr), date functions (sysdate, next_day, add_months, last_day, months_between, least, greatest, trunk, round, to_char, to_date).
WWW.CSEROCKZ.COM
STRING FUNCTIONS:
17) To display a field value after left padding. SELECT LPAD('PAGE-1', 10, '*') FROM DUAL; 18) To display a field value after left padding. SELECT RPAD('PAGE-1', 10, '*') FROM DUAL;
19)
To display a field value after converting to lower case. SELECT LOWER(A) FROM DUAL; To display a field value after converting to upper case. SELECT LOWER(a) FROM DUAL; To display a field value after converting to initial capital case.
47
20)
21)
WWW.CSEROCKZ.COM
To display a substring of a field value. SELECT SUBSTR(CSE2A, 4, 2) FROM DUAL; To display the length of a field value. SELECT LENGTH(HOW LONG AM I?) FROM DUAL; To display a field value after trimming the right side. SELECT RTRIM(CSE2A, 2A) FROM DUAL;
23)
24)
25) To display a field value after trimming the left side. SELECT LTRIM(CSE2A, CSE) FROM DUAL;
WEEK 8 (PL/SQL) (i) Creation of simple PL/SQL program which includes declaration section, executable section and exception handling section ( ex: Student marks can be selected from the table and printed for those who secured first class and an exception can be raised if no records were found). (ii) Insert data into student table and use COMMIT, ROLLBACK and SAVEPOINT in SQL block. Develop a program that includes the features NESTED IF, CASE and CASE expression. The program can be extended using the NULLIF and COALESCE functions.
6)
7)
48
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
OUTPUT:This ia a demo of FOR loop loop number 1 loop number 2 loop number 3 loop number 4 loop number 5
PS:
For syntax: For <var> in <start_num> .. <endnum> loop <statement(s);>
50
WWW.CSEROCKZ.COM
Example: 2 Create a file DBREVFOR.SQL, to execute the REVERSE FOR loop and display the variable. Program
begin dbms_ouput.put_line(This is a demo of REVERSE FOR loop); for cnt in reverse 1..10 loop if mod(cnt, 2) = 0 then dbms_output.put_line(loop counter || cnt); end if; end loop; end; /
OUTPUT:This is a demo of REVERSE FOR loop loop loop loop loop loop counter counter counter counter counter 10 8 6 4 2
PS:
Reverse For syntax: For <var> in reverse <start_num> .. <endnum> loop <statement(s);> End loop; Other forms of if syntax are: If <condition> then <action(s);> End if; If <condition> then <action(s);> Else
51
WWW.CSEROCKZ.COM
Example: 3 Create a file DBLOOP.SQL, to execute the LOOP loop and display the variable. Program
set serveroutput on declare cnt number(2) := 0; begin dbms_ouput.put_line(This is a demo of LOOP loop); loop cnt := cnt + 1; exit when cnt > 10; dbms_output.put_line(loop counter || cnt); end loop; end; / set serveroutput off
WWW.CSEROCKZ.COM
PS:
Loop syntax: loop <statement(s);> Exit when <condition>; End loop;
Example: 4 Create a file DBWHILE.SQL, to execute the WHILE loop and display the variable. Program
set serveroutput on declare cnt number(2) := 1; begin dbms_ouput.put_line(This is a demo of WHILE loop); while cnt <= 10 loop dbms_output.put_line(loop counter: || to_char(cnt, 999)); cnt := cnt + 1; end loop; end; / set serveroutput off
WWW.CSEROCKZ.COM
PS:
while syntax: while <condition> loop <statement(s);> End loop;
Example: 4 Write a program EMPDATA.SQL, to retrieve the employee details of an employee whose number is input by the user . Program
-- PROGRAM TO RETRIEVE EMP DETAILS set serveroutput on prompt Enter Employee Number: accept n declare dname emp.emp_name%type; dbasic emp.emp_basic%type; ddesig emp.desig%type; begin select emp_name, basic, design into dname, dbasic, ddesig from emp where emp_no = &n; dbms_ouput.put_line(Employee Details:); dbms_output.put_line(Name: || dname); dbms_output.put_line(Basic: || dbasic); dbms_output.put_line(Designation: || ddesig); end; /
OUTPUT:54
WWW.CSEROCKZ.COM
PS:
Similarly you can use other SQL statements in the PL/SQL block
Exercises: 1) Write a PL/SQL code, EX_INVNO.SQL, block for inverting a number using all forms of loops. ANSWER:declare n number(20):=123; s number(13):=0; d number(3):=1; r number(3):=10; begin
55
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
3) Write a PL/SQL code, EX_AREA.SQL, of block to calculate the area of the circle for the values of radius varying from 3 to 7. Store the radius and the corresponding values of calculated area in the table AREA_VALUES. ANSWER:set serveroutput on declare area number(5);
57
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
(i) Creation of simple PL/SQL program which includes declaration section, executable section and exception handling section ( ex: Student marks can be selected from the table and printed for those who secured first class and an exception can be raised if no records were found). (ii) Insert data into student table and use COMMIT, ROLLBACK and SAVEPOINT in SQL block. Develop a program that includes the features NESTED IF, CASE and CASE expression. The program can be extended using the NULLIF and COALESCE functions.
14)
15) Program development using WHILE LOOPS, numeric FOR LOOPS, nested loops using ERROR handling, BUILT IN exceptions, USER defined exceptions, RAISE APPLICATION ERROR. 16) Program development using creation of procedure, passing parameters IN and OUT procedures. 17) Program development using creation of stored function, invoke functions in SQL statements and write complex functions. 18) Program development using creation of package specification, package bodies, private objects, package variables and cursors and calling stored packages. 19) Develop programs using features of parameters in a CURSOR, FOR UPDATE CURSOR, WHERE CURRENT of clause and CURSOR variables.
59
WWW.CSEROCKZ.COM
Example: 1 Create a file (NEWINS.SQL), to insert into a new table, NEWEMP, the record of any employee whose number is input by the user.
1. Create the table NEWEMP <emp_no, emp_name, join_date, basic). 2. Open an editor and type the following program.
Program
prompt Enter Employee Number: accept userno number declare dno number(4); dname varchar2(30); ddate date; dbasic number(10); begin select emp_no, emp_name, join_date, basic into dno, dname, ddate, dbasic from emp where emp_no = &userno; if sql%rowcount > 0 then insert into newemp values (dno, dname, ddate, dbaisc); end if; end; / 3. Save the file as NEWINS 4. Execute the program as SQL> start newins
Example: 2 Create a file (NEWINS2.SQL), to insert into a new table, NEWEMP, the record of any employee whose number is input by the user. Also display on the screen the employee details and to handle errors like user entering a number which does not exist in the table.
60
WWW.CSEROCKZ.COM
if sql%rowcount > 0 then insert into newemp values (dno, dname, ddate, dbasic); dbms_output.put_line(Record inserted into NEWEMP); dbms_output.put_line(DNO || || DNAME || || DDATE || || DBASIC); end if; exception when no_data_found then dbms_output.put_line (Record || &userno || does not exist); end; /
Example: 3 Create a file (CALCTAX.SQL), to calculate tax for a specific employee and display name and tax. Program
prompt Enter Employee Number: accept userno number declare tot_basic tax name number(10, 2); number(10, 2); varchar2(30);
61
WWW.CSEROCKZ.COM
if tot_basic = 0 or tot_basic is null then dbms_output.put_line(NO BASIC); elsif tot_basic <= 2000 then tax := tot_basic * .02; dbms_output.put_line(NAME || TOTAL BASIC: || TOT_BASIC); dbms_output.put_line(NAME || TOTAL TAX: || TAX); else tax := tot_basic * .04; dbms_output.put_line(NAME || TOTAL BASIC: || TOT_BASIC); dbms_output.put_line(NAME || TOTAL TAX: || TAX); end if; exception when no_data_found then dbms_output.put_line (Record || &userno || does not exist); end; /
PS: EXECPTIONS When a program is executed certain errors are automatically recognized and certain error situations must be recognized by the program itself. Errors in general are referred to as Exceptions. Exceptions can be either System defined or User defined. Certain system exceptions raise the following flags: CURSOR_ALREADY_OPEN Displayed when the user tries to open a cursor that is already open DUP_VAL_ON_INDEX when user tries to insert a duplicate value into a unique column INVALID_CURSOR when user references an invalid cursor or attempts an illegal cursor operation INVALID_NUMBER when user tries to use something other than a number where one is called for LOGIN_DENIED when connect request for user has been denied
62
WWW.CSEROCKZ.COM
Write a PL/SQL code block that will accept an account number from the user and debit an amount of RS2000 from the account. If the
63
WWW.CSEROCKZ.COM
2)
20)
21)
22) Program development using WHILE LOOPS, numeric FOR LOOPS, nested loops using ERROR handling, BUILT IN exceptions, USER defined exceptions, RAISE APPLICATION ERROR. 23) Program development using creation of procedure, passing parameters IN and OUT procedures. 24) Program development using creation of stored function, invoke functions in SQL statements and write complex functions. 25) Program development using creation of package specification, package bodies, private objects, package variables and cursors and calling stored packages.
64
WWW.CSEROCKZ.COM
Example: 1 Create a PL/SQL program using cursors, to retrieve first tuple from the department relation. (use table dept(dno, dname, loc)) Program declare vdno dept.deptno%type; vdname dept.dname%type; vloc dept.loc%type; cursor c1 is select * from dept; or // cursor c1 is select * from dept where rowno = 1; begin open c1; fetch c1 into vdno,vdname,vloc; dbms_output.put_line('vdno = ' ||vdno|| ' vdname = '||vdname||' vloc = '||vloc); close c1; end; / PS: Cursors are used when the SQL select statement is expected to return more than 1 row.
65
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
Example: 3 Create a PL/SQL program using cursors, to display the number, name, salary of the three highest paid employees. (use table emp(empno, ename,sal)) Program declare no emp.empno%type; name emp.ename%type; salary emp.sal%type; cursor c1 is select empno, ename, sal from emp order by sal desc; begin open c1; loop fetch c1 into no,name,salary; exit when c1 %notfound; exit when c1 %rowcount >3; dbms_output.put_line(no||name||salary); end loop; close c1;
67
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
70
WWW.CSEROCKZ.COM
71
WWW.CSEROCKZ.COM
(i) Creation of simple PL/SQL program which includes declaration section, executable section and exception handling section ( ex: Student marks can be selected from the table and printed for those who secured first class and an exception can be raised if no records were found). (ii) Insert data into student table and use COMMIT, ROLLBACK and SAVEPOINT in SQL block. Develop a program that includes the features NESTED IF, CASE and CASE expression. The program can be extended using the NULLIF and COALESCE functions.
28)
29) Program development using WHILE LOOPS, numeric FOR LOOPS, nested loops using ERROR handling, BUILT IN exceptions, USER defined exceptions, RAISE APPLICATION ERROR. 30) Program development using creation of procedure, passing parameters IN and OUT procedures. 31) Program development using creation of stored function, invoke functions in SQL statements and write complex functions. 32) Program development using creation of package specification, package bodies, private objects, package variables and cursors and calling stored packages. 33) Develop programs using features of parameters in a CURSOR, FOR UPDATE CURSOR, WHERE CURRENT of clause and CURSOR variables. Example: 1 Code a procedure to calculate the sales made to a particular customer. { create table trn (itmid number(10), cstid number(10), trnqty number(10)); create table itmmast (itmid itmprice number(10), number(10,2));
72
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
Example: 3
76
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
(i) Creation of simple PL/SQL program which includes declaration section, executable section and exception handling section ( ex: Student marks can be selected from the table and printed for those who secured first class and an exception can be raised if no records were found). (ii) Insert data into student table and use COMMIT, ROLLBACK and SAVEPOINT in SQL block.
80
WWW.CSEROCKZ.COM
Develop a program that includes the features NESTED IF, CASE and CASE expression. The program can be extended using the NULLIF and COALESCE functions.
36) Program development using WHILE LOOPS, numeric FOR LOOPS, nested loops using ERROR handling, BUILT IN exceptions, USER defined exceptions, RAISE APPLICATION ERROR. 37) Program development using creation of procedure, passing parameters IN and OUT procedures. 38) Program development using creation of stored function, invoke functions in SQL statements and write complex functions. 39) Program development using creation of package specification, package bodies, private objects, package variables and cursors and calling stored packages. 40) Develop programs using features of parameters in a CURSOR, FOR UPDATE CURSOR, WHERE CURRENT of clause and CURSOR variables. Example: 1 Write a row trigger to insert the existing values of the salary table into a new table when the salary table is updated. (Salary < emp_no, basic, commission, deduction, salary_date, department> Salaryaud < emp_no, basic, commission, deduction, salary_date, department>) Step 1: Open the editor Step 2: Type the code below in a file named, TRSAL. Program CREATE TRIGGER UPDSAL BEFORE UPDATE ON SALARY FOR EACH ROW BEGIN insert intosalaryaud
81
WWW.CSEROCKZ.COM
number(9);
82
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
84
WWW.CSEROCKZ.COM
Overview of SQL DDL, DML and DCL Commands. DDL is Data Definition Language statements. Some examples: CREATE - to create objects in the database ALTER - alters the structure of the database DROP - delete objects from the database TRUNCATE - remove all records from a table, including all spaces allocated for the records ar removed COMMENT - add comments to the data dictionary GRANT - gives user's access privileges to database REVOKE - withdraw access privileges given with the GRANT command DML is Data Manipulation Language statements. Some examples: SELECT - retrieve data from the a database
85
WWW.CSEROCKZ.COM
86
WWW.CSEROCKZ.COM
Mgr short CONSTRAINT FKey1 REFERENCES EMP (EmpNo), Hiredate Date, DeptNo short CONSTRAINT FKey2 REFERENCES DEPT(DeptNo)); RESULT: Table created. SQL>Create table prog20 (pname varchar2(20) not null), doj date not null,dob date not null, sex varchar(1) not null, prof1 varchar(20),prof2 varchar(20),salary number(7,2) not null); RESULT: Table created. SQL>desc prog20; Name Null? Type ---------------------------VARCHAR2(20) DATE
87
WWW.CSEROCKZ.COM
Basic SQL DML Commands. To practice basic SQL DML Commands such as INSERT, DELETE, etc. 1. SQL - INSERT INTO Syntax:
Single-row insert
88
WWW.CSEROCKZ.COM
Other Examples: INPUT: SQL>Insert into prog values (kkk,05-may-56); RESULT: 1 row created. INPUT: SQL>Insert into prog20 values(Hema,25-sept-0128-jan-85,f,c,c+ +,25000); RESULT: 1 row created. INPUT: SQL>Insert into prog values(&pname,&doj); SQL> Insert into prog values('&pname','&doj'); Enter value for pname: ravi Enter value for doj: 15-june-81
89
WWW.CSEROCKZ.COM
3. SQL - DELETE FROM Syntax: DELETE FROM tablename WHERE condition Examples: DELETE FROM SP WHERE PNO= P1 DELETE FROM SP INPUT: SQL>Delete from emp where empno=7369; RESULT: 1 row deleted. Basic SQL DCL Commands. To practice basic SQL DCL Commands such as COMMIT, ROLLBACK etc.
90
WWW.CSEROCKZ.COM
91
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
93
WWW.CSEROCKZ.COM
2. Get the description DEPT table. SQL>desc dept; RESULT: Name --------------------------------DEPTNO DNAME LOC 3.List all employee details. SQL>select * from emp; RESULT:
94
WWW.CSEROCKZ.COM
95
WWW.CSEROCKZ.COM
96
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
15. Find how much amount the company is spending towards salaries. INPUT SQL>select sum (sal) from emp; RESULT SUM(SAL) --------32928 16. Display name of the dept. with deptno 20. INPUT SQL>select ename from emp where deptno = 20; RESULT
99
WWW.CSEROCKZ.COM
6 rows selected.
100
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
103
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
105
WWW.CSEROCKZ.COM
106
WWW.CSEROCKZ.COM
NESTED QUERY:- A nested query makes use of another sub-query to compute or retrieve the information. 1. Find the name of the institute in which the person studied and developed the costliest package. INPUT SQL>select splace, pname from study where pname = (select pname from software where scost = (select max (scost) from software); RESULT SPLACE PNAME -----------------------SAHBHARI MARY 2. Find the salary and institute of a person who developed the highest selling package. INPUT SQL> select study.pname, sal, splace from study, programmer where study.pname = programmer.pname and study.pname = (select pname from software where scost = (select max (scost) from software)); RESULT
107
WWW.CSEROCKZ.COM
108
WWW.CSEROCKZ.COM
4. Calculate the amount to be recovered for those packages whose development cost has not yet recovered. INPUT SQL>select title , (dcost-scost) from software where dcost > scost; 5. Display the title, scost, dcost, difference of scost and dcost in the descending order of difference. INPUT SQL> select title, scost, dcost, (scost - dcost) from software descending order by (scost-dcost); 6. Display the details of those who draw the same salary. INPUT SQL> select p.pname, p.sal from programmer p, programmer t where p.pname <> t.pname and p.sal = t.sal;(or) INPUT SQL>select pname,sal from programmer t where pname<>t.pname and sal= t.sal; Writing Queries using functions. AIM: To write queries using single row functions and group functions. 1. Display the names and dob of all programmers who were born in january. INPUT SQL>select pname , dob from programmer where to_char (dob,MON)=JAN;
109
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
111
WWW.CSEROCKZ.COM
Note: update command does not works for all queries on views. INPUT SQL>delete from view1 where pname like raju; RESULT 1 row deleted.
112
WWW.CSEROCKZ.COM
INPUT SQL>drop view xyz; Writing PL/SQL block for insertion into a table. To write a PL/SQL block for inserting rows into EMPDET table with the following Calculations: HRA=50% OF BASIC DA=20% OF BASIC PF=7% OF BASIC NETPAY=BASIC+DA+HRA-PF INPUT DECLARE ENO1 empdet.eno%type; ENAME1 empdet.name%type; DEPTNO1 empdet.deptno%type; BASIC1 empdet.basic%type; HRA1 empdet.HRA%type; DA1 empdet.DA%type; PF1 empdet.pf%type; NETPAY1 empdet.netpay%type; BEGIN ENO1:=&ENO1; ENAME1:='&ENAME1'; DEPTNO1:=&DEPTNO1; BASIC1:=&BASIC1; HRA1:=(BASIC1*50)/100; DA1:=(BASIC1*20)/100;
113
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
PF
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
119
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
Writing PL/SQL block for checking palendrome. To write a PL/SQL block to Check the Given String is Palindrome or Not. INPUT DECLARE name1 varchar2(20); name2 varchar2(20); l number(5); BEGIN name1:='&name1'; l:=length(name1); while l>0 loop name2:=name2||substr(name1,l,1); l:=l-1; end loop; dbms_RESULT.put_line('REVERSE OF STRING IS:'||NAME2); if(name1=name2) then dbms_RESULT.put_line(name1||' IS PALINDROME '); else dbms_RESULT.put_line(name1||' IS NOT PALINDROME '); end if; END; / RESULT Enter value for name1: LIRIL old 6: name1:='&name1'; new 6: name1:='LIRIL'; REVERSE OF STRING IS:LIRIL
121
WWW.CSEROCKZ.COM
Writing PL/SQL block to demonstrate Cursors. To write a Cursor to display the list of Employees and Total Salary Department wise. INPUT DECLARE cursor c1 is select * from dept; cursor c2 is select * from emp; s emp.sal%type; BEGIN for i in c1 loop s:=0; dbms_RESULT.put_line('----------------------------------------------'); dbms_RESULT.put_line('Department is :' || i.deptno ||' Department name is:' || i.dname); dbms_RESULT.put_line('-------------------------------------------'); for j in c2 loop if ( i.deptno=j.deptno) then s:=s+j.sal;
122
WWW.CSEROCKZ.COM
RESULT: SQL> @abc -----------------------------------------------------------------------------Department is :10 Department name is : ACCOUNTING -----------------------------------------------------------------------------7782 CLARK 2450 7839 KING 5000 7934 MILLER 1300 ----------------------------------------------------------------------------Total salary is: 8750 --------------------------------------------------------------------------------------------------------------------------------------------------------Department is :20 Department name is:RESEARCH -----------------------------------------------------------------------------7369 SMITH 800 7566 JONES 2975 7788 SCOTT 3000 7876 ADAMS 1100 7902 FORD 3000 ----------------------------------------------------------------------------Total salary is: 10875 ----------------------------------------------------------------------------------------------------------------------------------------------------------Department is :30 Department name is:SALES -----------------------------------------------------------------------------123
WWW.CSEROCKZ.COM
Writing PL/SQL CURSOR To write a Cursor to display the list of employees who are Working as a Managers or Analyst. INPUT DECLARE cursor c(jb varchar2) is select ename from emp where job=jb; em emp.job%type;
124
WWW.CSEROCKZ.COM
125
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
Writing PL/SQL CURSOR To write a Cursor to find employee with given job and deptno. INPUT DECLARE cursor c1(j varchar2, dn number) is select empno, ename from emp where job=j and deptno=dn; row1 emp%rowtype; jb emp.job%type; d emp.deptno%type; BEGIN jb:='&jb'; d:=&d; open c1(jb,d); fetch c1 into row1.empno,row1.ename; if c1%notfound then dbms_RESULT.put_line('Employee does not exist'); else dbms_RESULT.put_line('empno is:'||row1.empno||' ' ||'employee name is:'||row1.ename); end if; END; RESULT: SQL> @CUR Enter value for jb: MANAGER old 7: jb:='&jb'; new 7: jb:='MANAGER'; Enter value for d: 20
127
WWW.CSEROCKZ.COM
Writing PL/SQL BLOCK using string functions. To write a PL/SQL block to apply String Functions on a given input String. INPUT DECLARE a varchar2(20); l number(5); BEGIN a:='&a'; l:=length(a); dbms_RESULT.put_line('Using Lower Function:' || lower(a)); dbms_RESULT.put_line('Using UPPER Function:' || upper(a)); dbms_RESULT.put_line('Using Initcap Function:' || initcap(a)); dbms_RESULT.put_line('Using Substring Function:' || substr(a,l,1)); dbms_RESULT.put_line('Using Substring Function:' || substr(a,1,3)); dbms_RESULT.put_line('Using Ltrim function for xxxabcxxxx:' || ltrim('xxxabcxxxx','x'));
128
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
Writing PL/SQL triggers To write a TRIGGER to ensure that DEPT TABLE does not contain duplicate of null values in DEPTNO column. INPUT CREATE OR RELPLACE TRIGGER trig1 before insert on dept for each row DECLARE
130
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
132
WWW.CSEROCKZ.COM
Locking Table. AIM: To learn commands related to Table Locking LOCK TABLE Statement Manually lock one or more tables.
Syntax: LOCK TABLE [schema.] table [options] IN lockmode MODE [NOWAIT] LOCK TABLE [schema.] view [options] IN lockmode MODE [NOWAIT] Options: PARTITION (partition) SUBPARTITION (subpartition) @dblink lockmodes: EXCLUSIVE SHARE ROW EXCLUSIVE SHARE ROW EXCLUSIVE ROW SHARE* | SHARE UPDATE* If NOWAIT is omitted Oracle will wait until the table is available. Several tables can be locked with a single command - separate with commas e.g. LOCK TABLE table1,table2,table3 IN ROW EXCLUSIVE MODE; Default Locking Behaviour : A pure SELECT will not lock any rows.
133
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
135
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
Layout Wizard End of the Data Block Wizard and beginning of the Layout Wizard In the Congratulations screen, use the default checkmark radio button (Create the data block, then call the Layout Wizard), and click "Finish." You can also use the Data Block Wizard to modify your existing data block. Simply select the data block in the Object Navigator and click the Data Block Wizard toolbar button, or choose Data Block wizard from the Tools menu. Welcome screen In the Welcome to the Layout Wizard window, click Next. Selecting canvas In the Layout Wizard window, select the "new canvas" option. Canvas is a place that you will have your objects such as columns, titles, pictures, etc. If you have already had your canvas, select the canvas and then click on the next. The following are different types of canvases: Content, Stacked, Vertical Toolbar, Horizontal Toolbar, and Tab. Think of the Content canvas as one flat place to have all your objects. In the stacked canvas, you can have multiple layers of objects and it is the same as the tab canvas. You use the vertical or horizontal toolbar canvases for your push buttons. Check the different types of canvases by clicking on the down arrow box next to the Type field. Select "content," then click Next. Selecting Columns for the Layout Wizard In the Layout Wizard window, select all the columns. These are the columns that you want to be displayed on the canvas. Then click Next.
137
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
139
WWW.CSEROCKZ.COM
140
WWW.CSEROCKZ.COM
141
WWW.CSEROCKZ.COM
Object wizard
142
WWW.CSEROCKZ.COM
143
WWW.CSEROCKZ.COM
144
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
148
WWW.CSEROCKZ.COM
Creating reports
149
WWW.CSEROCKZ.COM
150
WWW.CSEROCKZ.COM
151
WWW.CSEROCKZ.COM
152
WWW.CSEROCKZ.COM
153
WWW.CSEROCKZ.COM
154
WWW.CSEROCKZ.COM
155
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
(ii) REVOKE Statement Revoke privileges from users or roles. Syntax: Roles: REVOKE role FROM {user, | role, |PUBLIC} System Privs: REVOKE system_priv(s) FROM {user, | role, |PUBLIC}
158
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
REFERENCES:
1.
Oracle 9i Release 2 (9.2) SQL Reference, www.cs.ncl.ac.uk/teaching/facilities/swdoc/oracle9i/server.920/a96540/t oc.htm. Oracle 9i Release 1 (9.0.1) SQL Reference, http://downloadeast.oracle.com/docs/cd/A91202_01/901_doc/server.901/a90125/toc.htm. An A-Z Index of Oracle SQL Commands (version 9.2) http://www.ss64.com/ora/. Database Systems Instructor: Prof. Samuel Madden Source: MIT Open Courseware (http://ocw.mit.edu).
160
2.
3.
4.
WWW.CSEROCKZ.COM
RDBMS Lab Guide, www.campusconnect.infosys.com userid:demo@infosys and passwork:infosys. Orelly PL/SQL Pocket Reference, http://www.unix.org.ua/orelly/oracle/langpkt/index.htm PL/SQL User's Guide and Reference, Release 2 (9.2) http://www.lc.leidenuniv.nl/awcourse/oracle/appdev.920/a96624/to c.htm.
6.
7.
161
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
85. What is database Trigger? A database trigger is a PL/SQL block that can defined to automatically execute for insert, update, and delete statements against a table. The trigger can e defined to execute once for the entire statement or once for every row that is inserted, updated, or deleted. For any one table, there are twelve events for which you can define database triggers. A database trigger can call database procedures that are also written in PL/SQL. 86. Name two utilities that Oracle provides, which are use for backup and recovery. Along with the RDBMS software, Oracle provides two utilities that you can use to back up and restore the database. These utilities are Export and Import. The Export utility dumps the definitions and data for the specified part of the database to an operating system binary file. The Import utility reads the file produced by an export, recreates the definitions of objects, and inserts the data If Export and Import are used as a means of backing up and recovering the database, all the changes made to the database cannot be recovered since the export was performed. The best you can do is recover the database to the time when the export was last performed. 87. What are stored-procedures? And what are the advantages of using them. Stored procedures are database objects that perform a user defined operation. A stored procedure can have a set of compound SQL statements. A stored procedure executes the SQL commands and returns the result to the client. Stored procedures are used to reduce network traffic. 88. How are exceptions handled in PL/SQL? Give some of the internal exceptions' name PL/SQL exception handling is a mechanism for dealing with run-time errors
176
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
178
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
WWW.CSEROCKZ.COM
183
WWW.CSEROCKZ.COM
EMAIL:
184
WWW.CSEROCKZ.COM