Complete DBMS Lab Record
Complete DBMS Lab Record
Aim: Queries for Creating, Dropping, and Altering Tables and insert row into a table (use constraints
while creating tables) examples using Select Command.
Procedure:
There are several ways to insert the values in the existing table
SQL>/
4. Select Command: this command is used to print the record from the existing table.
View all records in dept table:
SQL> select *from dept;
DEPTNO DNAME LOC
---------- -------------- -------------
10 sales vijayawada
20 admin hyd
30 marketing vzg
View records basing on given criteria on specific column.
1. view single column from existing table.
SQL>select dname dept;
DNAME
---------------
Sales
Admin
Marketing
1. CREATE:
CREATE TABLE: This is used to create a new relation and the corresponding
Example:
SQL>CREATE TABLE Student(id number,name varchar2(10));
RESULT: Table created.
2. DESC: It is used to describe a schema as well as to retrieve rows from table in descending order.
SYNTAX: DESC
EX: SQL> DESC EMP1;
NAME NULL? TYPE
----------------------------------------- -------- ---------------------------
EMPNO NOT NULL NUMBER(10)
ENAME VARCHAR2(15)
JOB CHAR(10)
DEPTNAME VARCHAR2(10)
DEPTNO NUMBER(9)
HIREDATE DATE
SALARY NUMBER(8)
EXP NUMBER(5)
3. ALTER: This is used for add, remove or modify the structure of the existing table
(a)ALTER TABLE ...ADD...: This is used to add some extra fields into existing relation.
Syntax: ALTER TABLE relation_name ADD(new field_1 data_type(size), new field_2
data_type(size),..);
(b)ALTER TABLE...MODIFY...: This is used to change the width as well as data type of fields of
existing relations.
Syntax: ALTER TABLE relation_name MODIFY (field_1 newdata_type(Size), field_2
newdata_type(Size),...., field_newdata_type(Size));
Example:SQL>ALTER TABLE emp1 MODIFY(ename VARCHAR2(20), salary NUMBER(5));
TABLE ALTERED.
4. DROP TABLE: This is used to delete the structure of a relation. It permanently deletes the table.
Syntax: DROP TABLE tablename;
Example: SQL>DROP TABLE EMP1;
Table dropped;
DROP: this command is used to remove the date from the existing table
DROP COLUMN IN TABLE
Syntax
To DROP A COLUMN in an existing table, the Oracle ALTER TABLE syntax is:
ALTER TABLE table_name DROP COLUMN column_name;
Example
ALTER TABLE customers DROP COLUMN customer_name;
6. TRUNCATE: This command will remove the data permanently. But structure will not be removed.
Syntax: TRUNCATE TABLE <Table name>
Example TRUNCATE TABLE EMP1;
Experiment 2.
QUERIES (ALONG WITH SUB QUERIES) USING ANY, ALL, IN, EXISTS,
NOTEXISTS, UNION, INTERSECT
SOLUTION:
To Create employee table:
SQL> CREATE TABLE EMPLOYEE(
FNAME VARCHAR2(20),
LNAME VARCHAR2(20),
SSN NUMBER(4) PRIMARY KEY,
B_DATE DATE,
ADDRESS VARCHAR2(30),
GENDER CHAR(1),
SALARY NUMBER(7,2),
SUPER_SSN REFERENCES EMPLOYEE(SSN),
DNO NUMBER(4)
);
Table created.
Like this we can insert the values into the table. To view data in the table following
query is used.
1. ALL
RETRIEVE THE NAMES OF EMPLOYEES WHOSE SALARY IS GREATER THAN THE
SALARY OF ALL THE EMPLOYEES IN DEPARTMENT 10
FNAME LNAME
-------------------- --------------------
ALLEN
MARTIN
TURNER
2. ANY
RETRIEVE THE NAMES OF EMPLOYEES WHOSE SALARY IS GREATER THAN THE
SALARY OF ANY ONE OF THE EMPLOYEES IN DEPARTMENT 10
SQL> SELECT FNAME, LNAME FROM EMPLOYEE
WHERE SALARY> ANY( SELECT SALARY FROM EMPLOYEE WHERE DNO=10);
FNAME LNAME
-------------------- --------------------
TURNER
MARTIN
ALLEN
BLAKE
SMITH
3. IN
RETRIEVE THE NAME OF EACH EMPLOYEE WHO HAS A DEPENDENT WITH THE
FIRSTNAME AND SAME GENDER AS THE EMPLOYEE
FNAME LNAME
-------------------- --------------------
SMITH
MARTIN
4. EXISTS
RETRIEVE THE NAME OF EACH EMPLOYEE WHO HAS A DEPENDENT WITH THE
FIRSTNAME AND SAME GENDER AS THE EMPLOYEE
FNAME LNAME
-------------------- --------------------
SMITH
MARTIN
5.NOT EXISTS
RETRIEVE THE NAMES OF EMPLOYEES WHO HAVE NO DEPENDENTS
FNAME LNAME
-------------------- --------------------
ALLEN
SQL Constraints
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can be insert into a table. This ensures the accuracy
and reliability of the data in the table. If there is any violation between the constraint and the data ac -
tion, the action is aborted.
Constraints can be column level or table level. Column level constraints apply to a column, and table
level constraints apply to the whole table.
Experiment 3.
QUERIES USING AGGREGATE FUNCTIONS (COUNT, SUM, AVG, MAX AND
MIN) GROUP BY, HAVING and Creation and dropping of Views.
SOLUTION:
1. COUNT
CALCULATE THE NUMBER OF EMPLOYEES IN DEPT 20.
SQL> SELECT COUNT (*) NO_EMP FROM EMP WHERE DEPTNO=20;
NO_EMP
----------
5
2. SUM
CALCULATE THE TOTAL SALARIES FOR EACH DEPT
SQL> SELECT DEPTNO, SUM(SAL) FROM EMP GROUP BY DEPTNO
DEPTNO SUM(SAL)
---------- ----------
30 9400
20 10875
10 8750
3. AVG
CALCULATE THE AVERAGE SALARIES FOR EACH DEPT
SQL> SELECT DEPT_NO, AVG (SAL) FROM EMP GROUP BY DEPT_NO;
DEPT_NO AVG(SAL)
---------- ----------
30 1566.66667
20 2175
10 2916.66667
4. MAX
CALCULATE THE MAXIMUM SALARY FOR EACH DEPT
SQL> SELECT DEPTNO, MAX (SAL) FROM EMP GROUP BY DEPTNO;
DEPTNO MAX(SAL)
---------- ----------
30 2850
20 3000
10 5000
5. MIN
CALCULATE THE MINIMUM SALARY FOR EACH DEPT
SQL> SELECT DEPTNO, MIN(SAL) FROM EMP GROUP BY DEPTNO
DEPTNO MIN(SAL)
---------- ----------
30 950
20 800
10 1300
6. GROUP BY:
The GROUP BY clause is a SQL command that is used to group rows that have the same values.
The GROUP BY clause is used in the SELECT statement .Optionally it is used in conjunction with ag-
gregate functions to produce summary reports from the database.
GROUP BY Syntax
SELECT statements... GROUP BY column_name1[,column_name2,...];
Grouping using a Single Column:
Create a table called data with gender column and values as male and female.
SQL> select * from data;
GENDER
----------
male
female
female
female
female
female
male
male
male
female
male
male
female
male
male
female
16 rows selected.
GENDER
----------
male
female
COUNT(GENDER) GENDER
------------- ----------
8 male
8 female
Grouping using Multiple Columns
Syntax
SELECT
column1,
column2,
AGGREGATE_FUNCTION (column3)
FROM
table1
GROUP BY
column1,
column2;
Examples :
SQL> select * from emp;
ID NAME DEPT SAL
---------- ---------- ---------- ----------
1a cse 1000
2b ece 2000
3c eee 3000
4d cse 4000
1z cse 5000
5a ece 6000
6e ece 7000
2b eee 9000
8 rows selected.
SQL> select id, name from emp group by id, name;
ID NAME
---------- ----------
3c
4d
1a
2b
5a
1z
6e
7 rows selected.
7. HAVING
The HAVING clause was added to SQL because the WHERE keyword could not be used with ag-
gregate functions.
The WHERE clause places conditions on the selected columns, whereas the HAVING clause places
conditions on groups created by the GROUP BY clause.
The HAVING clause must follow the GROUP BY clause in a query and must also precede the OR -
DER BY clause if used
HAVING Syntax
SELECT column_name(s) FROM table_name WHERE condition GROUP BY column_name(s)
HAVING condition
SQL> select * from emp;
ID NAME DEPT SAL
---------- ---------- ---------- ----------
1a cse 1000
2b ece 2000
3c eee 3000
4d cse 4000
5e ece 5000
SQL> select count(id),dept from emp group by dept having count(id)>1;
COUNT(ID) DEPT
---------- ----------
2 cse
2 ece
SQL> select * from emp;
ID NAME DEPT SAL
---------- ---------- ---------- ----------
1a cse 1000
2b ece 2000
3c eee 3000
4d cse 4000
5e ece 5000
SQL> select max(sal),dept from emp group by dept;
MAX(SAL) DEPT
---------- ----------
4000 cse
3000 eee
5000 ece
SQL> select max(sal),dept from emp group by dept having max(sal)>3000;
MAX(SAL) DEPT
---------- ----------
4000 cse
5000 ece
8. View :
o Views in SQL are considered as a virtual table. A view also contains rows and columns.
o To create the view, we can select the fields from one or more tables present in the database.
o A view can either have specific rows based on certain condition or all the rows of a table.
View dropped.
Experiment 4:
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)
b) String functions:
1. Concatenation: CONCAT is used to add two attribute values such as string.
SQL> select concat(eno,loc) from emp;
CONCAT(ENO,LOC)
--------------------------------------------------
101vja
102hyd
103vja
104gnt
105hyd
2. lpad: LPAD() function is used to padding the left side of a string with a specific set of characters.
SQL> select lpad(ename,10,'*') from emp;
LPAD(ENAME,10,'*')
----------------------------------------
*******ali
******haji
**mohammad
******ravi
****irfath
3. rpad: RPAD() function is used to padding the right side of a string with a specific set of characters.
SQL> select rpad(ename,10,'*') from emp;
RPAD(ENAME,10,'*')
----------------------------------------
ali*******
haji******
mohammad**
ravi******
irfath****
4. ltrim: LTRIM() function is used to remove all specified characters from the left end side of a string
SQL> select ltrim('******hi********','*') from dual;
LTRIM('***
----------
hi********
5. rtrim: RTRIM() function is used to remove all specified characters from the left end side of a string
SQL> select rtrim('******hi********','*') from dual;
RTRIM('*
--------
******hi
6. lower: lower() function is used to convert the attribute value in to lower case.
SQL> select lower(ename) from emp;
LOWER(ENAM
----------
ali
haji
mohammad
ravi
irfath
7. upper: upper() function is used to convert the attribute values in to upper case.
SQL> select upper(ename) from emp;
UPPER(ENAM
----------
ALI
HAJI
MOHAMMAD
RAVI
IRFATH
8. initcap: initcap() is used to convert the attribute values first character in capital letter.
SQL> select initcap(ename) from emp;
INITCAP(EN
----------
Ali
Haji
Mohammad
Ravi
Irfath
9. length: length() function is used to calculate the length of the given attribute.
SQL> select ename,length(ename) from emp;
ENAME LENGTH(ENAME)
---------- -------------
ali 3
haji 4
mohammad 8
ravi 4
irfath 6
10. substr:substr() function is used to find the substring of the given attribute value. It retuns size-1 of
the given string/ attribute as a sub string.
SQL> select ename, substr(ename,4) from emp;
ENAME SUBSTR(ENAME,4)
---------- ----------------------------
ali
haji i
mohammad ammad
ravi i
irfath ath
11. instr: instr() function return the location of starting passion of the sub string in the existing value.
SYSDATE
---------
28-APR-21
NEXT_DAY(
---------
02-MAY-21
3. add_months(): it returns the next date after adding number of months in the orguments.
SQL> select add_months(sysdate,5) from dual;
ADD_MONTH
---------
28-SEP-21
4. last_day(): The LAST_DAY() function takes a date value as argument and returns the last day of
month in that date
SQL> select last_day(sysdate) from dual;
LAST_DAY(
---------
30-APR-21
LAST_DAY(
---------
29-FEB-20
MONTHS_BETWEEN('02-FEB-2021','02-FEB-2020')
-------------------------------------------
12
SQL> select months_between(sysdate,'02-feb-2020') from dual;
MONTHS_BETWEEN(SYSDATE,'02-FEB-2020')
-------------------------------------
14.8600769
6. least(): it retuns least value from the given argument or attributes.
SQL> select least(300,450,100,440) from dual;
LEAST(300,450,100,440)
----------------------
100
7. greatest(): it returns maximum values from the given arguments or attributes in the relation.
SQL> select greatest(300,450,100,440) from dual;
GREATEST(300,450,100,440)
-------------------------
450
8. trunc(): The TRUNC() function returns a DATE value truncated to a specified unit.
SQL> select trunc(sysdate,'mm') from dual;
TRUNC(SYS
---------
01-APR-21
TRUNC(SYS
---------
01-JAN-21
ROUND(12.49,0)
--------------
12
ROUND(12.51,0)
--------------
13
10. to_char(): it convert the given date type attribute values to text and return the date in the specific
format.
SQL> select to_char(sysdate,'yyyy-mm-dd') from dual;
TO_CHAR(SY
----------
2021-04-28
Experiment 5.
i. Create a simple PL/SQL program which includes declaration section, executable section and excep-
tion –Handling section (Ex. Student marks can be selected from the table and printed for those who se-
cured 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 PL/SQL block..
i). We have to create the student table and insert the records in to the table as follows:
SQL> create table student(sid number(10),sname varchar2(20),rank varchar(10));
Table created.
PL/SQL CODE:
SQL>ed 5a
Enter the following code into the text editor and save the file with .sql format
set serveroutput on;
declare
temp1 number(10);
temp2 varchar2(10);
begin
select sid,sname into temp1,temp2 from student where rank='first';
dbms_output.put_line('Student No:'|| temp1 ||' Name:'||temp2||' got first
rank');
exception
when no_data_found then
dbms_output.put_line('********************************************');
dbms_output.put_line('# Error: there is no student got first rank');
end;
/
SQL> @5a;
********************************************
# Error: there is no student got first rank
SQL> @5a
Student No:503 Name:Ramu got first rank
ii)
SQL> select *from student;
PL/SQL CODE:
SQL>ed 5b
Enter the following code into the text editor and save the file with .sql format
DECLARE
sno student.sid%type;
name student.sname%type;
srank student.rank%type;
BEGIN
sno := &sno;
name := '&name';
srank := '&srank';
INSERT into student values(sno,name,srank);
dbms_output.put_line('One record inserted');
COMMIT;
-- adding savepoint
SAVEPOINT s1;
-- second time asking user for input
sno := &sno;
name := '&name';
srank := '&srank';
INSERT into student values(sno,name,srank);
dbms_output.put_line('One record inserted');
ROLLBACK TO SAVEPOINT s1;
END;
/
SQL> @5b;
SQL> @5b
Enter value for sno: 504
old 7: sno := &sno;
new 7: sno := 504;
Enter value for name: ali
old 8: name := '&name';
new 8: name := 'ali';
Enter value for srank: first
old 9: srank := '&srank';
new 9: srank := 'first';
a. NESTED IF:
A nested if-then is an if statement that is the target of another if statement. Nested if-then statements
mean an if statement inside another if statement
Syntax:-
if (condition1) then
-- Executes when condition1 is true
if (condition2) then
-- Executes when condition2 is true
end if;
end if;
PL/SQL CODE: PL/SQL Program to find biggest of three number using nested if.
SQL>ed 6a
Enter the following code into the text editor and save the file with .sql format
declare
a number:=10;
b number:=12;
c number:=5;
begin
dbms_output.put_line('a='||a||' b='||b||' c='||c);
if a>b AND a>c then
dbms_output.put_line('a is greatest');
else
if b>a AND b>c then
dbms_output.put_line('b is greatest');
else
dbms_output.put_line('c is greatest');
end if;
end if;
end;
/
SQL> @6a
a=10 b=12 c=5
b is greatest
PL/SQL procedure successfully completed.
b. CASE and CASE Expression : CASE statement selects one sequence of statements to execute.
However, to select the sequence, the CASE statement uses a selector rather than multiple Boolean
expressions. A selector is an expression, the value of which is used to select one of several alternatives.
Syntax
CASE selector
WHEN 'value1' THEN S1;
WHEN 'value2' THEN S2;
WHEN 'value3' THEN S3;
...
ELSE Sn; -- default case
END CASE;
SQL> create table emp(eno number(5), ename varchar2(10), loc varchar(10), salary number(10,2));
Table created.
SQL> insert into emp values(101,'ali','vja',15000);
1 row created.
LOC rev_salary
---------- ----------
vja 17000
hyd 26000
gnt 35000
vja 47000
SQL> ed 6b
SQL> @6b
Enter value for grade: g
old 4: grade:='&grade';
new 4: grade:='g';
No such grade
c.NULLIF: Takes two arguments. If the two arguments are equal, then NULL is returned. otherwise
the first argument is returned.
Syntax:
select column_name,NULLIF(argument1,arguement2) from table_name;
Example:
SQL> select ename, nullif('ali','ali1') from emp;
ENAME NUL
---------- ---
ali ali
ravi ali
raju ali
rakesh ali
d.COALESCE: COALESCE() function accepts a list of arguments and returns the first one that
evaluates to a non-null value.
Syntax:
coalesce("expression1","expression2",...);
Example:
SQL> select coalesce(NULL,'PSCMR','CSE') from dual;
COALE
-----
PSCMR
Experiment 7:
Program development using WHILE LOOPS, numeric FOR LOOPS, nested loops using ERROR Han-
dling, BUILT –IN Exceptions, USE defined Exceptions, RAISEAPPLICATION ERROR.
a. WHILE LOOP: A WHILE LOOP statement in PL/SQL programming language repeatedly ex-
ecutes a target statement as long as a given condition is true.
Syntax:
PL/SQL Code: A PL/SQL Program to find sum of ODD number upto given number using While loop
SQL> ed 7a
SQL> @7a
Enter value for endval: 100
old 7: endval:=&endval;
new 7: endval:=100;
sum of odd numbers between 1 and 100 is 2500
b. FOR Loop: A FOR LOOP is a repetition control structure that allows us to efficiently write a loop
that needs to execute a specific number of times.
Syntax
FOR counter IN initial_value .. final_value LOOP
sequence_of_statements;
END LOOP;
PL/SQL CODE: A PL/SQL code to print multiplication table using for loop
SQL> ed 7b
set serveroutput on;
DECLARE
VAR1 NUMBER;
VAR2 NUMBER;
BEGIN
dbms_output.put_line('Enter number to print multiplication table');
VAR1:=&VAR1;
FOR VAR2 IN 1..10 LOOP
DBMS_OUTPUT.PUT_LINE(VAR1||'X'||VAR2||'='||VAR1*VAR2);
END LOOP;
END;
/
SQL> @7b
Enter value for var1: 2
old 6: VAR1:=&VAR1;
new 6: VAR1:=2;
Enter numer to print multiplication table
2X1=2
2X2=4
2X3=6
2X4=8
2X5=10
2X6=12
2X7=14
2X8=16
2X9=18
2X10=20
c. NESTED LOOP: PL/SQL allows using one loop inside another loop. It may be
either basic, while or for loop.
Syntax:
WHILE condition1 LOOP
sequence_of_statements1
WHILE condition2 LOOP
sequence_of_statements2
END LOOP;
END LOOP;
PL/SQL CODE: A PL/SQL program to print n prime number using nested loop.
SQL> ed 7c
DECLARE
i number(3);
j number(3);
BEGIN
i := 2;
LOOP
j:= 2;
LOOP
exit WHEN ((mod(i, j) = 0) or (j = i));
j := j +1;
END LOOP;
IF (j = i ) THEN
dbms_output.put_line(i || ' is prime');
END IF;
i := i + 1;
exit WHEN i = 50;
END LOOP;
END;
/
SQL> @7c
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
Experiment 8:
Programs development using creation of procedures, passing parameters IN and OUT of
PROCEDURES.
SQL> @pro8
Enter value for enqno2: 112
old 5: enqno2:=&enqno2;
new 5: enqno2:=112;
Experiment 9:
Program development using creation of stored functions, invoke functions in SQL statements and write
complex functions.
Sol:
SQL> @getname
Function created.
SQL> ed pro9
SQL> @pro9
Enter value for deptno: 1001
old 5: deptno2:=&deptno;
new 5: deptno2:=1001;
declare
*
ERROR at line 1:
ORA-20100: Your entered Department number is not exists
ORA-06512: at "SYSTEM.GETNAME", line 9
ORA-06512: at line 6
Experiment 10:
Develop programs using features parameters in a CURSOR, FOR UPDATE CURSOR, WHERE
CURRENT of clause and CURSOR variables.
Sol:
SQL> create table customers(id number(3), name varchar2(10), age number(3), address varchar2(10),
salary number(10,2));
Table created.
4 rows selected.
SQL> ed pro10
DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/
SQL> @pro10
1 ramesh ahmedabad
2 khilan Delhi
3 kaushik Kota
4 chitali Mumbai
PL/SQL procedure successfully completed.
Experiment 11:
Develop programs using before and after triggers, row and statement triggers and instead of triggers.
Sol:
SQL> create table customers(id number(3), name varchar2(10), age number(3), address varchar2(10),
salary number(10,2));
Table created.
4 rows selected.
PL/SQL Code for creation of trigger while insert / update records into a table.
SQL>ed pro11
SQL> @pro11
Trigger created.
Sol:
Table created.
SQL> insert into teacher values('T101','SUNITHA','MCA','29-JUN-06','ASSOCIATE
PROFESSOR','VIJAYAWADA',9985061308,23000,'MCA');
1 row created.
15 rows selected.
Elapsed: 00:00:00.24
Index creation:
SQL> create index teacher_job_ind on teacher(job);
Index created.
Elapsed: 00:00:00.00
Retrieve details of teacher after creation of index.
15 rows selected.
Elapsed: 00:00:00.13