CS503 DBMS Labmanual
CS503 DBMS Labmanual
CS503 DBMS Labmanual
What is SQL?
● SQL stands for Structured Query Language
● SQL lets you access and manipulate databases
● SQL is an ANSI (American National Standards Institute) standard
●
What Can SQL do?
● SQL can execute queries against a database
● SQL can retrieve data from a database
● SQL can insert records in a database
● SQL can update records in a database
● SQL can delete records from a database
● SQL can create new databases
● SQL can create new tables in a database
● SQL can create stored procedures in a database
● SQL can create views in a database
● SQL can set permissions on tables, procedures, and views
●
5. Find the third highest paid and third lowest paid salary.
8. Show all employees who were hired the first half of the month.
9. Display the three record in the first row and two records in the second row and one record in the third
row in a single sql statements
10. Write a sql statements for rollback commit and save points.
11. Write a pl/sql for select, insert, update and delete statements.
12. Write a pl/sql block to delete a record. If delete operation is successful return 1 else return 0.
13. Display name, hire date of all employees using cursors.
15. Write a database trigger which fires if you try to insert, update, or delete after 7’o’ clock.
16. Write a data base trigger, which acts just like primary key and does not allow
Duplicate values.
17. Create a data base trigger, which performs the action of the on delete cascade.
18. Write a data base trigger, which should not delete from emp table if the day is Sunday.
19. In this subject the students are supposed to prepare a small database application in complete
semester like financial accounting system, Railway reservation system, institute timetable management
system. Student record system, library management system, hospital management system etc. in
RDBMS as follows:
Section A:
Solving the case studies using ER Data Model (design of the database)
Section B:
Implement a Mini Project for the problem taken in section A.
CONSTRAINTS
2. DEFAULT CONSTRAINT
CREATE TABLE EMP(ENO NUMBER(3) NOT NULL, ENAME VARCHAR2(10),DOJ DATE
DEFAULT SYSDATE);
3. PRIMARY CONSTRAINT(COLUMN LEVEL)
UNIQUE
PRIMARY KEY
CREATE TABLE EMP( ENO NUMBER(3) CONSTRAINT PKEMP PRIMARY KEY, ENAME
VARCHAR2(10));
4. CHECK CONSTRAINT
DELETE FROM emp A WHERE ROWID NOT IN(SELECT MIN(ROWID) FROM emp WHERE
A.DEPTNO=B.DEPTNO);
OR
DELETE FROM DEPT A WHERE ROWID NOT IN (SELECT MIN(ROWID) FROM DEPT B WHERE
A.DEPTNO=B.DEPTNO);
Ques2:-Delete all the rows having same name more then once?
Experiment 2
Program 2:
OR
SELECT * FROM GDEPT WHERE ROWID IN(SELECT DECODE(MOD(ROWNUM,2),0,ROWID)
FROM GDEPT);
Ques1:-Show the name of those employees who earn commission?
Ques2:-Show all employees who has no commission but have a10% hike in their salary?
Ques3:-Show the last name of all employees together with the number of years & the number of
complete months that they have been employed?
Experiment 3
Program 3:
Ques3:- Delete the row of employee whose salary is more then 25000?
Experiment 4
Program 4:
Select * from emp where dname = any(select dname from emp where dname = ‘sales’ or dname =
‘research’);
Select * from emp where dname = any(select dname from emp where
Dname like(‘sales’,’research’));
Ques1:-Find the name of those entire employee who work in Delhi and update there location to Bombay?
Ques3:- Write a query to raise the salary by 50% of those employees who do not have a commission?
Experiment 5
Program 5:
Find the third highest paid and third lowest paid salary.
Ques2:- Write a query to find those entire employees who earn maximum salary?
Ques3:- Write a query to find those employees who work in that dept in which the higher salary taker
works?
Experiment 6
DISPLAY from NTH ROW
SELECT * FROM DEPT WHERE ROWID NOT IN(SELECT ROWID FROM DEPT WHERE
ROWNUM<=(SELECT COUNT(*)-&N FROM DEPT));
Program 6:
SELECT * FROM DEPT WHERE ROWID NOT IN(SELECT ROWID FROM DEPT WHERE
ROWNUM<=(SELECT COUNT(*)-&3 FROM DEPT));
SELECT * FROM DEPT WHERE ROWID NOT IN(SELECT ROWID FROM DEPT WHERE
ROWNUM<=(SELECT COUNT(*)-&4 FROM DEPT));
SELECT * FROM DEPT WHERE ROWID NOT IN(SELECT ROWID FROM DEPT WHERE
ROWNUM<=(SELECT COUNT(*)-&9 FROM DEPT));
Ques2:-show the dept number and the lowest salary of the dept with the highest average salary?
Experiment 7
Program 7:
select ename
from employees
where name like 'J%'
or name like 'K%'
or name like 'L%' or name like 'M%' ;
or
select ename
from
employees
where name like '[JKLM]%'
Ques1:-Write a query to find that how many employees are there whose name ends with N?
Ques2:- Write a query to find that how many employees are there whose name ends with M without
using like operator?
Experiment 8
Program 8:
Show all employees who were hired the first half of the month.
Ques1:-Write a query to find the data of that entire employee whose name ends with t?
Ques2:- Find the DOB of that employee who was born on the same date on which the maximum salary
earner was born?
Experiment 9
Program 9:
Display the three record in the first row and two records in the second row and one record in the third row
in a single sql statements.
SQL> SAVEPOINT A
2 ;
Savepoint created.
1 row created.
SQL> SAVEPOINT B;
Savepoint created.
7 rows selected.
Rollback complete.
6 rows selected.
temp
~~~~
prodname comment date1
declare
qty NUMBER(5);
pname VARCHAR2(10);
begin
select quantity,prodname into qty,pname from inv where
prodname='&productname';
if qty>5 then
DBMS_OUTPUT.PUT_LINE('THANK U FOR THE PURCHASES MADE VISIT AGAIN');
update inv set quantity=quantity-1 where prodname=pname;
commit;
else
DBMS_OUTPUT.PUT_LINE('STOCK LEVEL IS BELOW ORDER LEVEL');
insert into temp values(pname,'out of stock',sysdate);
commit;
end if;
end;
Ques1:-Draw a sequence diagram for roll back and save point activity in ATM transaction?
PL/SQL
DECLARE
/* Declarative section: variables, types, and local subprograms.
*/
BEGIN
/* Executable section: procedural and SQL statements go
here. */
/* This is the only section of the block that is required. */
EXCEPTION
/* Exception handling section: error handling statements go
here. */
END;
Let us see an example of the above
DECLARE
TEMP_COST NUMBER(10, 2);
BEGIN
SELECT COST FROM JD11.BOOK INTO TEMP_COST
WHERE ISBN = 21;
IF TEMP_COST > 0 THEN
UPDATE JD11.BOOK SET COST =
(TEMP_COST*1.175) WHERE ISBN = 21;
ELSE
UPDATE JD11.BOOK SET COST = 21.32 WHERE
ISBN = 21;
END IF;
COMMIT;
EXCEPTION
WHEN NO_DATA_FOUND THEN
INSERT INTO JD11.ERRORS (CODE, MESSAGE)
VALUES(99, ‘ISBN 21 NOT FOUND’);
END;
Only the executable section is required. The other sections are optional.
The only SQL statements allowed in a PL/SQL program are SELECT, INSERT, UPDATE, DELETE and
several other data manipulation statements plus some transaction control.
Data definition statements like CREATE, DROP, or ALTER are not allowed.
The executable section also contains constructs such as assignments, branches, loops, procedure calls,
and triggers, which are all described below (except triggers). PL/SQL is not case sensitive. C style
comments (/* ... */) may be used.
To execute a PL/SQL program, we must follow the program
text itself by
· A line with a single dot (“.”), and then · A line with run;
As with Oracle SQL programs, we can invoke a PL/SQL
program either by typing it in sqlplus or by putting the code in a
file and invoking the file in the various ways we learned in
Types in PL/SQL
Types in PL/SQL can be tricky. In many cases, a PL/SQL variable will be used to manipulate data stored
in a existing relation. In this case, it is essential that the variable have the same type as the relation
column. If there is any type mismatch, variable assignments and comparisons may not work the way you
expect. To be safe, instead of hard coding the type of a variable, you should use the %TYPE operator. For
example:
DECLARE
gives PL/SQL variable myBeer whatever type was declared for
the name column in relation Beers.
Experiment 11
Program 11:
DECLARE
NAME VARCHAR2(10);
DESIG VARCHAR2(10);
SALARY NUMBER(7,2);
ENO NUMBER(4):=&EMPNO;
BEGIN
SELECT ENAME,JOB,SAL INTO NAME,DESIG,SALARY FROM EMP WHERE EMPNO=ENO;
DBMS_OUTPUT.PUT_LINE(ENO||' '||NAME||' '||SALARY||' '||DESIG);
IF DESIG='CLERK' THEN
DELETE FROM EMP WHERE EMPNO=ENO;
INSERT INTO TEMP VALUES(NAME,DESIG,SALARY);
DBMS_OUTPUT.PUT_LINE('DELETED FROM EMP AND INSERTED TO TEMP');
COMMIT;
ELSIF DESIG='MANAGER' THEN
UPDATE EMP SET SAL=SALARY+200 WHERE EMPNO=ENO;
DBMS_OUTPUT.PUT_LINE('INCREMENTED SALARY IS '||TO_CHAR(SALARY+200));
END IF;
END;
Ques2:-Write a query to create a view for DEPT table(Full view,View of fragmented table) ?
Experiment 12
Program 12:
Write a pl/sql block to delete a record. If delete operation is successful return 1 else return 0.
Ques2:-What is sequence?
Cursors
DECLARE
/* Output variables to hold the result of the query: */
a T1.e%TYPE;
b T1.f%TYPE;
/* Cursor declaration: */
CURSOR T1Cursor IS
SELECT e, f
FROM T1
WHERE e < f
FOR UPDATE;
BEGIN
OPEN T1Cursor;
LOOP
/* Retrieve each row of the result of the above query
into PL/SQL variables: */
FETCH T1Cursor INTO a, b;
/* If there are no more rows to fetch, exit the loop: */
EXIT WHEN T1Cursor%NOTFOUND;
/* Delete the current tuple: */
DELETE FROM T1 WHERE CURRENT OF T1Cursor;
/* Insert the reverse tuple: */
INSERT INTO T1 VALUES(b, a);
END LOOP;
/* Free cursor used by the query. */
CLOSE T1Cursor;
END;
Experiment 13
Program 13:
DECLARE
cursor c1 is select ename,hiredate from emp;
name varchar(20);
hdate date;
begin
open c1;
loop
fetch c1 into name,hdate;
exit when c1%NOTFOUND;
dbms_output.put_line(name||' '||hdate);
end loop;
close c1;
end;
Experiment 14
Program 14:
DECLARE
cursor c1 is select * from emp order by sal desc;
a c1%rowtype;
begin
open c1;
loop
fetch c1 into a;
exit when c1%rowcount>6;
dbms_output.put_line(a.ename||' '||a.sal||' '||a.job||'
'||C1%ROWCOUNT);
end loop;
close c1;
end;
Ques1:-Write a query to find the details of those employee who have same job using cursor?
Ques2:-Write a query to show dept where no sales representative works using cursor?
Triggers
A trigger (essentially, a stored SQL statement associated with a table) is a database object that defines
events that happen when some other event, called a triggering event, occurs. Create a trigger by using
the CREATE TRIGGER statement. Triggers execute when an INSERT, UPDATE, or DELETE modifies a
specified column or columns in the subject table. Typically, the stored SQL statements perform an
UPDATE, INSERT, or DELETE on a table different from the subject table.
Sometimes a statement fires a trigger, which in turn, fires another trigger. Thus the outcome of one
triggering event can itself become another trigger. The Teradata RDBMS processes and optimizes the
triggered and triggering statements in parallel to maximize system performance.
Trigger Functions
Use triggers to perform various functions:
• Define a trigger on the parent table to ensure that UPDATEs and DELETEs
performed to the parent table are propagated to the child table.
• Use triggers for auditing. For example, you can define a trigger which
causes INSERTs in a log record when an employee receives a raise higher
than 10%.
• Use a trigger to disallow massive UPDATEs, INSERTs, or DELETEs during
business hours.
For example, you can use triggers to set thresholds for inventory of each item
by store, to create a purchase order when the inventory drops below a
threshold, or to change a price if the daily volume does not meet expectations.
Restrictions on Using Triggers
Teradata triggers do not support FastLoad and MultiLoad utilities and, and
you must disable triggers before you run load utilities. In addition, a positioned
(updatable cursor) UPDATE or DELETE is not allowed to fire a trigger and
generates an error.
Note: You cannot define a join index on a table with a trigger.
Write a database trigger which fires if you try to insert, update, or delete after 7’o’ clock
Experiment 16
16. Write a data base trigger, which acts just like primary key and does not allow duplicate
CREATE OR REPLACE TRIGGER PRIKEY BEFORE INSERT ON EMP
FOR EACH ROW
DECLARE
A NUMBER;
BEGIN
SELECT COUNT(*) INTO A FROM EMP WHERE EMPNO=:NEW.EMPNO;
IF A >=1 THEN
RAISE_APPLICATION_eRROR(-20500,'THE PRI KEY RULE IS
VOILATED');
ELSIF A=0 THEN
PRINT('RECORD IS INSERTED');
END IF;
END;
1 row created.
Experiment 17
17. Create a data base trigger, which performs the action of the on delete cascade
Experiment 18
18. Write a data base trigger, which should not delete from emp table if the day is Sunday.
CREATE OR REPLACE TRIGGER EMPNO_CHECK
BEFORE DELETE ON emp
BEGIN
if to_char(sysdate,'dAy')='SUNDAY' then
raise_application_error(-20001,'TO DAY IS SUNDAY ');
end if;
END;
Ques 1:- What are triggers? How many triggers you can have on a table? How to
invoke a trigger on demand?
Ques2:- Write a data base trigger, for the employee whose day of joining is Sunday?
Viva Questions
1. What is database?
2. What is DBMS?
3. What is a Database system?
4. Explain the difference between a database administrator and a data administrator
5. Disadvantage in File Processing System?
6. Describe the three levels of data abstraction?
7. Define the "integrity rules"
8. What is extension and intension?
9. What is System R? What are its two major subsystems?
10. How is the data structure of System R different from the relational structure?
11. What is Data Independence?
12. What is a view? How it is related to data independence?
13. What is Data Model?
14. What is E-R model?
15. What is Object oriented model?
16. What is an Entity?
17. What is an Entity type?
18. What is an Entity set?
19. What is an Extension of entity type?
20. What is Weak Entity set?
21. What is an attribute?
22. What is a Relation Schema and a Relation?
23. What is degree of a Relation?
24. What is Relationship?
25. What is Relationship set?
26. What is Relationship type?
27. What is degree of Relationship type?
28. What is Data storage?
29. What is DML (Data Manipulation Language)?
30. What is VDL (View Definition Language)?
31. What is DML Compiler?
32. What is Query evaluation engine?
33. What is DDL Interpreter?
34. What is Record-at-a-time?
35. What is Set-at-a-time or Set-oriented?
36. What is relational Algebra?
37. What is Relational Calculus?
38. How does Tuple-oriented relational calculus differ from domain-oriented relational
calculus
39. What is normalization?
40. What is Functional Dependency?
41. When is a functional dependency F said to be minimal?
42. What is Multivalued dependency?
43. What is Lossless join property?
44. What is 1 NF (Normal Form)?
45. What is Fully Functional dependency?
46. What is 2NF?
47. What is 3NF?
48. What is BCNF (Boyce-Codd Normal Form)?
49. What is 4NF?
50. What is 5NF?
51. Explain the difference between an explicit and an implicit lock.
52. What is lock granularity?
53. In general, how should the boundaries of a transaction be defined?
54. Explain the meaning of the expression ACID transaction.
55. Explain the necessity of defining processing rights and responsibilities. How are such
responsibilities enforced?
56. Describe the advantages and disadvantages of DBMS-provided and application-provided
security.
57. Explain how a database could be recovered via reprocessing. Why is this generally not
feasible?
58. Define rollback and roll forward.
59. Why is it important to write to the log before changing the database values?