DBMS LAB
DBMS LAB
LAB MANUAL
YEAR\SEM : II\IV
REGULATION : 2021
1
Vision:
Mission:
ethical responsibilities.
2
INDEX
3
EX.NO : 1 CREATE A DATABASE TABLE, ADD CONSTRAINTS (PRIMARY
KEY, UNIQUE, CHECK, NOT NULL), INSERT ROWS,UPDATE
AND DELETE ROWS USING SQL DDL AND DML COMMANDS.
AIM:
To create a database and write SQL queries to retrieve information from the database.
ALOGRITHM:
STEP 1: Start
STEP 3: Execute different Commands and extract information from the table.
STEP 4: Stop
QUERY: 01
Q1. Query to create a table employee with empno, ename, designation, and salary.
QUERY:
Table created.
QUERY: 02
Q2. Query to display the column name and data type of the table employee.
4
Syntax for describe the table:
QUERY: 03
Q3. Query for create a from an existing table with all the fields
SQL> CREATE TABLE <TRAGET TABLE NAME> SELECT * FROM <SOURCE TABLE
NAME>;
QUERY:
Table created.
QUERY: 04
Q4. Query for create a from an existing table with selected fields
5
SQL> CREATE TABLE <TRAGET TABLE NAME> SELECT EMPNO, ENAME FROM
<SOURCE TABLE NAME>;
QUERY:
Table created.
QUERY: 01
Q1. Query to Alter the column EMPNO NUMBER (4) TO EMPNO NUMBER (6).
SQL > ALTER <TABLE NAME> MODIFY <COLUMN NAME> <DATATYPE> (SIZE);
QUERY:
Table altered.
6
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)
QUERY: 02
Q2. Query to Alter the table employee with multiple columns (EMPNO, ENAME.)
SQL > ALTER <TABLE NAME> MODIFY <COLUMN NAME1> <DATATYPE> (SIZE),
MODIFY <COLUMN NAME2> <DATATYPE> (SIZE)………………………………………….;
QUERY:
Table altered.
QUERY: 03
SQL> ALTER TABLE <TABLE NAME> ADD (<COLUMN NAME> <DATA TYPE> <SIZE>);
QUERY:
Table altered.
7
SQL> DESC EMP;
QUERY: 4
SQL> ALTER TABLE <TABLE NAME> ADD (<COLUMN NAME1> <DATA TYPE> <SIZE>,
(<COLUMN NAME2> <DATA TYPE> <SIZE>,………………………………);
QUERY:
Table altered.
REMOVE / DROP
8
QUERY: 5
QUERY:
Table altered.
QUERY:
Table altered.
REMOVE
QUERY: 7
QUERY:
TYPES OF CONSTRAINTS:
Primary key
Foreign key/references
Check
Unique
Not null
Null
Default
OPERATION ON CONSTRAINT:
ENABLE
DISABLE
DROP
PRIMARY KEY
QUERY:1
Q2. Query to create primary constraints with column level with naming convention
QUERY:2
11
SQL>CREATE TABLE EMPLOYEE(EMPNO NUMBER(4) CONSTRAINT EMP_EMPNO_PK
PRIMARY KEY,ENAME VARCHAR2(10), JOB VARCHAR2(6),SAL NUMBER(5), DEPTNO
NUMBER(7));
Q3. Query to create primary constraints with table level with naming convention
QUERY: 3
SQL> ALTER TABLE <TABLE NAME> ADD CONSTRAINTS <NAME OF THE CONSTRAINTS>
<TYPE OF THE CONSTRAINTS> <COLUMN NAME>);
QUERY: 4
12
SQL>ALTER TABLE EMP3 ADD CONSTRAINT EMP3_EMPNO_PK PRIMARY KEY
(EMPNO);
CHECK CONSTRAINT
QUERY:10
QUERY:11
13
Q.12. Query to create Check constraints with table level using alter command.
QUERY:12
UNIQUE CONSTRAINT
QUERY:13
14
Syntax for Table level constraints with Unique:
QUERY:14
QUERY:15
NOT NULL
15
SQL :> CREATE <OBJ.TYPE> <OBJ.NAME> (<COLUMN NAME.1> <DATATYPE> (SIZE)
CONSTRAINT <NAME OF CONSTRAINTS> <CONSTRAINT TYPE>, (COLUMN NAME2
<DATATYPE> (SIZE)) ;
QUERY: 16
NULL
QUERY:17
16
EX.NO : 2
CREATE A SET OF TABLES, ADD FOREIGN KEY CONSTRAINTS
AND INCORPORATE REFERENTIAL INTEGRITY.
AIM:
To create a database and write SQL queries to retrieve information from the database.
ALOGRITHM:
STEP 1: Start
STEP 3: Execute different Commands and extract information from the table.
STEP 4: Stop
Parent Table:
Child Table:
17
SQL>CREATE <OBJ.TYPE> <OBJ.NAME> (COLUMN NAME.1 <DATATYPE> (SIZE),
COLUMN NAME2 <DATATYPE> (SIZE) REFERENCES <TABLE NAME> (COLUMN NAME>
……………………………);
QUERY: 5
Parent Table:
Child Table:
QUERY:6
18
Table Level Foreign Key Constraints
Parent Table:
SQL>CREATE <OBJ.TYPE> <OBJ.NAME> (COLUMN NAME.1 <DATATYPE> (SIZE)<TYPE OF
CONSTRAINTS> , COLUMN NAME.1 <DATATYPE> (SIZE) ……………………………);
Child Table:
QUERY: 7
Q.8. Query to create foreign key constraints with Table level with alter command.
Parent Table:
Child Table:
19
SQL>CREATE <OBJ.TYPE> <OBJ.NAME> (COLUMN NAME.1 <DATATYPE> (SIZE) ,
COLUMN NAME2 <DATATYPE> (SIZE));
SQL> ALTER TABLE <TABLE NAME> ADD CONSTRAINT <CONST. NAME> REFERENCES
<TABLE NAME> (COLUMN NAME>);
QUERY:9
20
EX.NO : 3 .QUERY THE DATABASE TABLES USING DIFFERENT ‘WHERE’
CLAUSE CONDITIONS AND ALSO IMPLEMENT AGGREGATE
FUNCTIONS
AIM:
To create a database tables using different ‘where’ clause conditions and also implement
aggregate functions.
ALOGRITHM:
STEP 1: Start
STEP 3: Execute different Commands and extract information from the table.
STEP 4: Stop
SQL> select title from book where unitprice between 300 and 400;
Aggregate functions
Average : avg
Minimum: min
Maximum: max
Total:sum
Count:count
359.8
Minimum
250
Maximum
450
SQL>select sum(unitprice) “total”from book;
Total
450
no of books
22
EX.NO : 4
. QUERY THE DATABASE TABLES AND EXPLORE SUB QUERIES
AIM:
ALOGRITHM:
STEP 1: Start
STEP 3: Execute different Commands and extract information from the table.
STEP 4: Stop
23
EX.NO : 5
. QUERY THE DATABASE TABLES AND EXPLORE NATURAL
EQUI AND OUTER JOIN
AIM:
ALOGRITHM:
STEP 1: Start
STEP 3: Execute different Commands and extract information from the table.
STEP 4: Stop
JOIN
INNER JOIN
OUTER JOIN
NATURAL JOIN
INNER JOIN
i)Employee (Empname,city)
24
SQL> SELECT * FROM EMPLOYEE INNER JOIN EMPLOYEESALARY ON
EMPLOYEE.EMPNAME = EMPLOYEEASALARY. EMPNAME;
OUTER JOIN
25
EX.NO : 6
. WRITE USER DEFINED FUNCTIONS AND STORED PROCEDURES IN SQL.
AIM:
PL/SQL:
Oracle uses a PL/SQL engine to processes the PL/SQL statements. A PL/SQL code can be
stored in the client system (client-side) or in the database (server-side).
ADVANTAGES OF PL/SQL:
Block Structures: PL SQL consists of blocks of code, which can be nested within each
other. Each block forms a unit of a task or a logical module. PL/SQL Blocks can be stored in
the database and reused.
26
PL/SQL PLACEHOLDERS:
Placeholders are temporary storage area. Placeholders can be any of Variables, Constants
and Records. Oracle defines placeholders to store data temporarily, which are used to manipulate
data during the execution of a PL SQL block.
Depending on the kind of data you want to store, you can define placeholders with a name and a
datatype. Few of the datatypes used to define placeholders are as given below.
Number (n,m) , Char (n) , Varchar2 (n) , Date , Long , Long raw, Raw, Blob, Clob, Nclob, Bfile.
PL/SQL VARIABLES:
These are placeholders that store the values that can change through the PL/SQL Block.
As the name implies, PL/SQL supports programming language features like conditional
statements, iterative statements.
The programming constructs are similar to how you use in programming languages like Java
and C++.
Iterative control Statements are used when we want to repeat the execution of one or more
statements for specified number of times.
A cursor is a temporary work area created in the system memory when a SQL statement is
executed. A cursor contains information on a select statement and the rows of data accessed by it.
27
This temporary work area is used to store the data retrieved from the database, and
manipulate this data. A cursor can hold more than one row, but can process only one row at a time.
The set of rows the cursor holds is called the active set.
STORED PROCEDURES
A stored procedure or in simple a proc is a named PL/SQL block which performs one or
more specific task. This is similar to a procedure in other programming languages.
A procedure has a header and a body. The header consists of the name of the procedure and
the parameters or variables passed to the procedure. The body consists or declaration section,
execution section and exception section similar to a general PL/SQL Block.
A procedure is similar to an anonymous PL/SQL Block but it is named for repeated usage.
1) IN-parameters
2) OUT-parameters
3) IN OUT-parameters
28
PL/SQL FUNCTIONS
A function is a named PL/SQL Block which is similar to a procedure. The major difference
between a procedure and a function is, a function must always return a value, but a procedure may
or may not return a value.
RETURN return_datatype;
IS
Declaration_section
BEGIN
Execution_section
Return return_variable;
EXCEPTION
exception section
Return return_variable;
END;
1) Return Type: The header section defines the return type of the function. The return datatype can
be any of the oracle datatype like varchar, number etc.
2) The execution and exception section both should return a value which is of the datatype defined
in the header section.
EXCEPTION HANDLING
PL/SQL provides a feature to handle the Exceptions which occur in a PL/SQL Block known as
exception Handling. Using Exception Handling we can test the code and avoid it from exiting
abruptly.
1) Type of Exception
2) An Error Code
3) A message
What is a Trigger?
A trigger is a pl/sql block structure which is fired when a DML statements like Insert, Delete,
Update is executed on a database table. A trigger is triggered automatically when an associated DML
statement is executed.
Syntax of Triggers
30
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
WHEN (condition)
BEGIN
END;
SQL> DECLARE
<VARIABLE DECLARATION>;
BEGIN
IF(CONDITION)THEN
END;
DECLARE
b number;
c number;
BEGIN
B:=10;
C:=20;
if(C>B) THEN
dbms_output.put_line('C is maximum');
31
end if;
end;
OUTPUT:
C is maximum
SQL> DECLARE
<VARIABLE DECLARATION>;
BEGIN
<STATEMENTS>;
ELSE
<STATEMENTS>;
ENDIF;
END;
SQL> declare
n number;
begin
n:=&number;
if n<5 then
else
end if;
32
end;
Input
old 5: n:=&number;
new 5: n:=2;
Output:
SQL> DECLARE
<VARIABLE DECLARATION>;
BEGIN
<STATEMENTS>;
<STATEMENTS>;
ELSE
<STATEMENTS>;
ENDIF;
END;
SQL> declare
a number;
b number;
33
c number;
d number;
begin
a:=&a;
b:=&b;
c:=&b;
if(a>b)and(a>c) then
dbms_output.put_line('A is maximum');
elsif(b>a)and(b>c)then
dbms_output.put_line('B is maximum');
else
dbms_output.put_line('C is maximum');
end if;
end;
INPUT:
old 7: a:=&a;
new 7: a:=21;
old 8: b:=&b;
new 8: b:=12;
old 9: c:=&b;
new 9: c:=45;
OUTPUT:
34
C is maximum
I) PROGRAM:
2 BEGIN
4 END;
5 /
OUTPUT:
ALOGRITHM created.
II) PROGRAM:
3 BEGIN
4 TOT := N1 + N2;
35
5 END;
6 /
OUTPUT:
PROCEDURE created.
SQL> PRINT T
----------
99
I) PROGRAM:
return number is
b number;
begin
b:=1;
for i in 1..n
loop
b:=b*i;
end loop;
return b;
end;
36
/SQL>Declare
n number:=&n;
y number;
begin
y:=fnfact(n);
dbms_output.put_line(y);
end;
Function created.
old 2: n number:=&n;
new 2: n number:=5;
120
II) PROGRAM
SQL> create table phonebook (phone_no number (6) primary key,username varchar2(30),doorno
varchar2(10), street varchar2(30),place varchar2(30),pincode char(6));
Table created.
1 row created.
1 row created.
37
PHONE_NO USERNAME DOORNO STREET PLACE PINCODE
------------------------------- ------------- ---------------- --------------------
20312 vijay 120/5D bharathi street NGO colony 629002
29467 vasanth 39D4 RK bhavan sarakkal vilai 629002
[
begin
return address;
exception
end;
Function created.
SQL>declare
2 address varchar2(100);
3 begin
4 address:=findaddress(20312);
5 dbms_output.put_line(address);
6 end;
7 /
OUTPUT 1:
38
SQL> declare
2 address varchar2(100);
3 begin
4 address:=findaddress(23556);
5 dbms_output.put_line(address);
6 end;
7 /
OUTPUT2:
39
AND TCL COMMANDS.
AIM:
ALOGRITHM
STEP 1: Start
STEP 5: Stop
40
1.COMMIT command
The commit command saves all transaction to all database since the last COMMIT or ROLLBACK
command
SQL>commit work;
2.ROLLBACK
The transaction control command used to undo transactions that have not already been saved to the
database.
SQL>rollback work;
41
EX.NO : 8 WRITE SQL TRIGGERS FOR INSERT, DELETE, AND UPDATE
OPERATIONS IN A DATABASE TABLE
AIM:
To develop and execute a Trigger for Before and After update, Delete, Insert operations on a table.
ALOGRITHM:
STEP 1: Start
STEP 3:Specify the operations (update, delete, insert) for which the trigger has to be executed.
STEP 4: Execute the Trigger ALOGRITHM for both Before and After sequences
STEP 5: Carryout the operation on the table to check for Trigger execution.
STEP 6: Stop
EXECUTION
43
SQL> select * from emp;
EMPID EMPNAME INCOME EXPENSE SAVINGS
--------- --------------- ------------ ------------- -------------
2 vivek 830 150 100
3 kumar 5000 550 50
9 vasanth 987 6554 644
44
1. Create a Trigger to check the age valid or not Using Message Alert
SQL> CREATE TABLE TRIG(NAME CHAR(10),AGE NUMBER(3));
SQL> DESC TRIG;
Table created.
Name Null? Type
-------------------------------------------- -------- -------------------------
NAME CHAR(10)
AGE NUMBER(3)
PROGRAM:
SQL> SET SERVEROUTPUT ON;
SQL> CREATE TRIGGER TRIGNEW
AFTER INSERT OR UPDATE OF AGE ON TRIG
FOR EACH ROW
BEGIN
IF(:NEW.AGE<0) THEN
DBMS_OUTPUT.PUT_LINE('INVALID AGE');
ELSE
DBMS_OUTPUT.PUT_LINE('VALID AGE');
END IF;
END;
/
Trigger created.
SQL> insert into trig values('abc',15);
Valid age
1 row created.
SQL> insert into trig values('xyz',-12);
Invalid age
1 row created.
NAME AGE
---------- ----------
abc 15
xyz -12
45
2. Trigger to check the age valid and Raise appropriate error code and error message.
SQL> create table data(name char(10),age number(3));
Table created.
NAME AGE
---------- ----------
abc 10
46
3. Trigger for EMP table it will update another table SALARY while inserting values.
SQL> CREATE TABLE SRM_EMP2(INAME VARCHAR2(10),
IID NUMBER(5),
SALARY NUMBER(10));
Table created.
47
SQL> INSERT INTO SRM_EMP2 VALUES('SRM',200,3000);
1 row created.
RESULT:
48
EX.NO :9
CREATE VIEW AND INDEX FOR DATABASE TABLES WITH A LARGE
NUMBER OF RECORDS.
AIM:
OBJECTIVE:
Provides user security on each view - it depends on your data policy security.
Using view to convert units - if you have a financial data in US currency, you can create
view to convert them into Euro for viewing in Euro currency.
ALOGRITHM
STEP 1: Start
STEP 5: Execute different Commands and extract information from the View.
STEP 6: Stop
49
COMMANDS EXECUTION
CREATION OF TABLE
--------------------------------
SQL> CREATE TABLE EMPLOYEE ( EMPLOYEE_NAMEVARCHAR2(10),
EMPLOYEE_NONUMBER(8),DEPT_NAME VARCHAR2(10),
Table created.
TABLE DESCRIPTION
CREATION OF VIEW
------------------------------
SQL> CREATE VIEW EMPVIEW AS SELECT EMPLOYEE_NAME,
EMPLOYEE_NO,DEPT_NAME,DEPT_NO,DATE_OF_JOIN FROM EMPLOYEE;
VIEW CREATED.
DESCRIPTION OF VIEW
--------------------------------
SQL> DESC EMPVIEW;
50
NAME NULL? TYPE
----------------------------------------- ---------- ----------------------------
EMPLOYEE_NAME VARCHAR2(10)
EMPLOYEE_NO NUMBER(8)
DEPT_NAME VARCHAR2(10)
DEPT_NO NUMBER(5)
DISPLAY VIEW:
INSERT STATEMENT:
SYNTAX:
DELETION OF VIEW:
DELETE STATEMENT:
SYNTAX:
1 ROW DELETED.
UPDATE STATEMENT:
SYNTAX:
1 ROW UPDATED.
52
EMPLOYEE_N EMPLOYEE_NO DEPT_NAME DEPT_NO
---------- ----------- ---------- ----------
KAVI 124 ECE 89
VIJAY 345 CSE 21
RAJ 98 IT 22
GIRI 100 CSE 67
DROP A VIEW:
SYNTAX:
EXAMPLE
VIEW DROPED
53
CREATE A VIEW WITH SELECTED FIELDS:
SYNTAX:
TYPE-1:
View created.
View created.
View created.
TYPE-2:
54
SQL> CREATE OR REPLACE VIEW EMP_TOTSAL AS SELECT EMPNO "EID",ENAME
"NAME",SALARY "SAL" FROM EMPL;
TYPE-3:
View created.
6 rows selected.
View created.
JOIN VIEW:
View created.
View created.
EMPNO ENAME DEPTNO DNAME LOC
------------------------------ -------------------- ---------- --------------------
7578 TOM 10 ACCOUNT NEW YORK
7548 TURNER 10 ACCOUNT NEW YORK
7369 SMITH 20 SALES CHICAGO
7678 JOHN 20 SALES CHICAGO
7499 MARK 30 RESEARCH ZURICH
7565 WILL 30 RESEARCH ZURICH
6 rows selected.
FORCE VIEW
6 rows selected.
View created.
6 rows selected
SYNONYM
SYNTAX:
57
FOR [schema .] object_name [@ dblink];
CREATE:
DROP:
1. DROP [PUBLIC] SYNONYM [schema .] synonym_name [force];
2. DROP PUBLIC SYNONYM suppliers;
SEQUENCE
SYNTAX
[ AS [ built_in_integer_type | user-defined_integer_type ] ]
[ INCREMENT BY <constant> ]
[ CYCLE | { NO CYCLE } ]
[;]
GO
58
A. Creating a sequence that increases by 1
START WITH 1
INCREMENT BY 1 ;
GO
START WITH 0
INCREMENT BY -1 ;
GO
START WITH 5
INCREMENT BY 5 ;
GO
INCREMENT BY 1 ;
GO
59
E. Creating a sequence using default values
AS smallint ;
AS decimal(3,0)
INCREMENT BY 25
MINVALUE 100
MAXVALUE 200
CYCLE
CACHE 3
INDEX
SYNTAX:
EXAMPLE:
60
CREATE INDEX PIndex
ON Persons (LastName)
DROP INDEX
61