Dbms Lab Manual
Dbms Lab Manual
&TECHNOLOGY
DEPARTMENTOFINFORMATION
TECHNOLOGY
LABMANUAL
DBMS LAB
INFORMATIONTECHNOLOGY(IT)
DATABASEMANAGEMENTSYSTEMS
EXPERIMENT:1
1
Aim:Queries for Creating, Dropping, and Altering Tables and insert row into
a table(use constraints while creating tables) examples using Select
Command.
Procedure:
2. ViewStructure/schemaofemp&depttableinsql:
DEPARTMENTOFIT
DATABASEMANAGEMENTSYSTEMS
SQL>desc emp;
Name Null? Type 2
DEPARTMENTOFIT
DATABASEMANAGEMENTSYSTEMS
SQL>/
3
Entervaluefordeptno:20
Entervaluefordname:admin Enter
value for loc: hyd
old1:insertintodeptvalues(&deptno,'&dname','&loc') 1
row created.
SQL>/
Entervaluefordeptno: 30
Entervaluefordname:marketing
Enter value for loc: vzg
old1:insertintodeptvalues(&deptno,'&dname','&loc')
new1: insert into dept values(30,'marketing','vzg')
1 rowcreated.
10sales vijayawada
20admin hyd
30marketing vzg
Viewrecordsbasingongivencriteriaonspecificcolumn.
Sales
Admin
Marketing
DEPARTMENTOF IT
DATABASEMANAGEMENTSYSTEMS
[Link](s)fromexistingtablebasedongivencondition.
4
SQL>select*fromdeptwheredname='sales';
DEPTNO DNAME LOC
10sales vijayawada
DMLCommands(DataManipulationLanguage)
[Link] 2. INSERT [Link] [Link]
TCL(TransactionControlLanguage)
[Link] [Link] [Link]
DCLCommands(DataControlLanguage)
[Link] [Link]
[Link]:
CREATETABLE:This is used to create a new relation and the corresponding
DEPARTMENTOFIT
DATABASEMANAGEMENTSYSTEMS
2. DESC:Itisusedtodescribeaschemaaswellastoretrieverowsfromtableindescending order.
SYNTAX:DESC
5
EX:SQL>DESC EMP1;
NAME NULL? TYPE
3. ALTER:This is used for add, remove or modify the structure of the existing table
(a) ALTERTABLE...ADD...:Thisisusedtoaddsomeextrafieldsintoexistingrelation.
(b) ALTERTABLE...MODIFY...:This is used to change the width as well as data type of fields of
existing relations.
Syntax:ALTER TABLE relation_nameMODIFY(field_1newdata_type(Size),field_2 newdata_type(Size),...
, field_newdata_type(Size));
Example:
SQL>ALTERTABLEemp1MODIFY(enameVARCHAR2(20),salaryNUMBER(5));
TABLE ALTERED.
DEPARTMENTOFIT
DATABASEMANAGEMENTSYSTEMS
SQL>DESC EMP1;
6
NAME NULL? TYPE
5. RENAME:Itisusedtomodifythenameoftheexistingdatabaseobject.
Syntax:RENAMEold_table_nameTO new_table_name;
Example:
SQL>RENAME EMP1 TOEMP2;
Tablerenamed.
DEPARTMENTOFIT
DATABASEMANAGEMENTSYSTEMS
[Link]:[Link].
Syntax: TRUNCATE TABLE<Tablename>
7
Example:
TRUNCATE TABLE EMP1;
EXPERIMENT _2
ToCreateemployeetable:
CREATE:
CREATE TABLE:This is used to create a new relation and the
corresponding
Syntax:CREATETABLErelation_name(field_1data_type(Size),
field_2data_type(Size),...);
Example:
CREATE TABLE employee ( fname VARCHAR2(20),
lname VARCHAR2(20),
position VARCHAR2(20),
hire_date DATE,
salary NUMBER );
1. INSERT Command: The INSERT command is used to add new rows to a table.
Syntax:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
Example:
Insert a new employee into the employees table
INSERT INTO employees (first_name, last_name, position, hire_date, salary)
VALUES ('Emily', 'Davis', 'Marketing Specialist', '2024-08-01', 60000);
In this example:
We insert a new row into the employees table with the columns first_name, last_name, position,
hire_date, and salary.
2. UPDATE Command: The UPDATE command is used to modify existing rows in a table.
Syntax:
UPDATE table_nameSET column1 = value1,
column2 = value2, ...
WHERE condition;
Example:
Update the position and salary of an employee
UPDATE employees
SET POSITION =’SALES EXECUTIVE’ SALARY=20000
WHERE FNAME=’XXXX’ AND LNAME=’YYYY’;
3. DELETE Command: The DELETE command is used to remove rows from a table.
Syntax:
DELETE FROM table_name
WHERE condition;
Example:
Delete an employee from the employees table
DELETE FROM employees
WHERE last_name = 'Davis' AND first_name = 'Emily';
In this example:
We delete the row from the employees table where first_name is 'Emily' and last_name is 'Davis'.
DEPARTMENTOFIT
DATABASEMANAGEMENTSYSTEMS
EXPERIMENT-3
Queries using i)SELECT statement ii) SELECT statement with where
clause(logicalOperators, AND, OR, NOT, IN, BETWEEN,LIKE) iii) ORDER BY
clause(sort by column name) iv) LIMIT clause
BasicSQL querying (select andproject)using where clause:
ThefollowingarethevariousSQLclauses:
1. Groupby:
SQL group by statement is used to arrange identical data into groups.
The group by statement is used with the SQL select statement.
The groupby statement follows the WHERE clause in a SELECT statement and precedes the
ORDERBY clause.
Syntax:
Select column from table_name where column group by column,
order by column;
Select Company from Product1 where Company groupby
Company, orderby Rate;
Sampletable:product
PRODUCT COMPANY QTY RATE COST
Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Com1 3 11 44
Example:
Select company Count(*) from product groupby company;
Output:
Com1 3
Com2 2
Com3 1
2. Having clause:
Having clause is used to specify a search condition for a group or an aggregate.
Having clause is used in agroup by clause,if you are not using groupby
clause then you can usehaving function like a where clause.
Syntax:
Selectcolumn1,column2fromtable_name
Whereconditions
Groupbycolumn1,colu
mn2Havingcondition
Orderbycolumn1,column2;
Example:
select
company, count (*) from product
Group by company Having count (*) > 1;
[Link] clause:
Theorderbyclausesortstheresult_setinascendingordescendingorder.
Syntax:
Selectcolumn1,column2,fromtable_name
Wherecondition
Orderbycolumn1,column2…asc;
Sampletable:
Output:
Logical Operations:
Logicaloperationsallowyoutotestforthetruthofacondition.
ThefollowingtableillustratestheSQLlogicaloperator.
OPERATOR MEANING
ALL Returns true if all comparisons are true
AND Returns true if both expressions are true
ANY Returns true if anyone of the comparisons is
true
BETWEEN Return true if the operand is within a range
IN Return true if the operand is equal to one of
The values in a list
EXISTS Return true if the sub query contains any rows
AND:The AND operator allows you to construct multiple condition in the WHERE
clause of an SQL statement such as select.
Thefollowingexamplefindsallemployeeswheresalariesaregreaterthanthe5000andlessthan7000
.
ALL: The ALL operator compares a value to all values in another value set.
The following example finds all employees whose salaries are greater than all
salaries of employees.
EX:
Between: The between operator searches for values that are with in a set of values.
For example ,the following statement finds all employees where salaries are between 9000
and 12000.
Ex:
Select first_name, last_name, salary from employees
where salary between 9000 AND 12000 order by
salary;
Output:
FIRST_NAME LAST_NAME SALARY
Alexander Hunold 9000.00
Den Richards 10000.00
Nancy Prince 12000.00
IN: The IN operator compares a value to list of specified [Link] IN operator return true if compared value
matches at least one value in the list.
The following statement finds all employees who work in department _id 8 or 9
EX:
`
SELECT * FROM EMPLOYEE
ORDER BY Salary DESC
FETCH FIRST 3 ROWS ONLY;
DEPARTMENTOFIT
DATABASEMANAGEMENTSYSTEMS
EXPERIMENT:4
14
QUERIES USING AGGREGATE FUNCTIONS(COUNT,SUM,AVG,MAXANDMIN)
GROUPBY,HAVING and Creation and dropping of Views.
SOLUTION:
[Link]:Calculatethenumberofemployeesindept20.
SQL>SELECT COUNT(*) NO_EMP FROM EMP WHERE DEPTNO=20;
NO_EMP
30 9400
20 10875
10 8750
[Link]:Calculatetheaveragesalariesforeachdept
SQL>SELECT DEPT_NO, AVG(SAL) FROM EMP GROUP BY DEPT_NO;
DEPT_NOAVG(SAL)
---------- ----------
30 1566.66667
20 2175
10 2916.66667
[Link]:Calculatethemaximumsalaryforeach dept
SQL>SELECT DEPTNO ,MAX(SAL) FROM EMP GROUP BY DEPTNO;
DEPTNOMAX(SAL)
30 2850
20 3000
10 5000
DEPARTMENT OF IT
DATABASEMANAGEMENTSYSTEMS
5. MIN
Calculate the minimum salary for each dept
15
SQL>SELECT DEPTNO , MIN(SAL) FROM EMP GROUP BY DEPTNO
DEPTNOMIN(SAL)
30 950
20 800
10 1300
6. GROUPBY:
The GROUP BY clause is a SQL command thatis used to group rows that have the same values. The
GROUP BY clause is used in the SELECT [Link] it is used in conjunction with
aggregate functions to produce summary reports from the database.
GROUP BY Syntax
SELECT statements…GROUPBY 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 Gender from data;
GENDER
male
female
female
female
female
female
male
male
male
female
male
male
female
male
male
female
16 rowsselected.
DEPARTMENT OF IT
DATABASEMANAGEMENTSYSTEMS
male
female
8 male
8 female
3 c
4 d
1 a
2 b
5 a
1 z
6 e
7rowsselected.
DEPARTMENTOF IT
DATABASEMANAGEMENTSYSTEMS
[Link]
17
The HAVING clause was added to SQL because the WHERE keyword could not be used with
aggregate functions.
The WHERE clause places conditions on the selected columns,where as 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
ORDER BY clause if used
HAVINGSyntax
SELECTcolumn_name(s)FROMtable_nameWHEREconditionGROUPBYcolumn_name(s)
HAVINGcondition
ID NAMEDEPT SAL
1 a cse 1000
2 b ece 2000
3 c eee 3000
4 d cse 4000
5 e ece 5000
DEPARTMENTOF IT
DATABASEMANAGEMENTSYSTEMS
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.
SQL>select*from emp;
Alter table Emp Add(LOCation Varchar(10));
SQL>select*from hyd;
ENO ENAME SALARYLOC
102 haji 20000 hyd
105 irfath 50000 hyd
DEPARTMENTOFAIML
DATABASEMANAGEMENTSYSTEMS
SQL>select*from hyd;
Select * from hyd
*
ERRORatline1:
ORA-00942:table or view does not exist
EXPERIMENT: 5
QUERIES (ALONG WITH SUB QUERIES) USING ANY, ALL, IN, EXISTS,
NOTEXISTS, UNION, INTERSECT
SOLUTION:
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 NUMBER(4) REFERENCES employee(Ssn),
Dno NUMBER(4)
);
Table created.
1111 SMITH M
2222 POOJA F
3333 MARTIN M
3333 RAJA M
1. ALL:
Retrieve the names of employees whose salary is greater than the salary of all the employees in department 10
SQL> SELECT FNAME, LNAME FROM EMPLOYEE
WHERE SALARY> ALL ( SELECT SALARY FROM EMPLOYEE WHERE DNO=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
Retrievethenameofeachemployeewho hasadependent withthefirstnameandsamegenderasthe employee
FNAME LNAME
SMITH
MARTIN
4. EXISTS
Retrievethenameofeachemployeewho hasadependent withthefirstnameandsamegenderasthe employee
FNAME LNAME
SMITH
MARTIN
[Link]
Retrievethenamesofemployeeswhohavenodependents
SQL>SELECT FNAME,LNAME FROM EMPLOYEE WHERE NOT EXISTS(SELECT*
FROM DEPENDENT WHERE SSN=ESSN);
FNAME LNAME
ALLEN
SQLConstraints
SQLconstraintsareused to specifyrulesforthe datainatable.
Constraints are used to limit the type of data that can be insertinto 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
action, 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.
ThefollowingconstraintsarecommonlyusedinSQL:
NOTNULL-EnsuresthatacolumncannothaveaNULLvalue
Example:
SQL>createtableperson1(idint,namevarchar2(10)notnull,ageint); Table
created.
UNIQUE-Ensuresthatallvaluesinacolumnare different
Example:
SQL>createtableperson(id intunique,namevarchar2(10),ageint);
Tablecreated.
[Link] row in
a table
Example:
SQL>createtableemp1(idnumber(10)primarykey,namevarchar2(10),salint); Table
created.
FOREIGNKEY-Uniquelyidentifiesarow/recordinanothertable
o AFOREIGNKEYisakeyusedtolinktwotablestogether.
o AFOREIGNKEYisa field(orcollectionoffields) inonetablethat referstothe
PRIMARY KEY in another table.
o Thetablecontainingthe foreignkeyiscalledthechildtable,andthetablecontainingthe
candidate key is called the referenced or parent table.
Example:
SQL>createtableemp2(eidint,cityvarchar2(10),foreign key(eid)referencesemp1(id));
Tablecreated.
CHECK - Ensures that all values in a column satisfies a specific condition
Example:
SQL> CREATE TABLE person1( ID int ,Age int, City varchar(10), CONSTRAINT chk
CHECK(Age>=18 AND City='vja');
Table created.
o The default value will be added to all new records IF no other value is specified.
DEPARTMENTOFIT
DATABASEMANAGEMENTSYSTEMS
EXPERIMENT:6
20
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)
SQL>select*from emp;
ENOENAME SALARY LOC
101 ali 15000 vja
102 haji 20000 hyd
103 mohammad 42000 vja
104 ravi 23000 gnt
105 irfath 50000 hyd
a)ConversionFunctions:
1.to_char:to_char is used to convert the attribute values to char.
SQL>select to_char(salary,'$99999.99')from emp;
TO_CHAR(SALARY)
$15000.00
$20000.00
$42000.00
$23000.00
$50000.00
SQL> TO_CHAR (
123.5
SQL>SELECT TO_
CHAR(123.4567,'99999.99')FROM DUAL; TO_CHAR(1
123.46
TO_CHAR(1 21
1,234.57
TO_CHAR(SY
2021/07/09
TO_CHAR(SY
09/07/2021
TO_CHAR
000023
TO_CHAR(
0000123
TO_CHA
00003
TO_CHA
00023
TO_CHA
######
DEPARTMENTOFIT
DATABASEMANAGEMENTSYSTEMS
22
1210.73
01-JAN-20
DEPARTMENTOF IT
DATABASEMANAGEMENTSYSTEMS
23
b) Stringfunctions:
1. Concatenation:CONCATisused toaddtwoattributevaluessuchasstring.
101vja
102hyd
103vja
104gnt
105hyd
2. lpad:LPAD()functionisusedtopaddingtheleftsideofastringwithaspecificsetofcharacters.
SQL>select lpad(ename,10,'*')fromemp;
LPAD(ENAME,10,'*')
*******ali
******haji
**mohammad
******ravi
****irfath
3. rpad:RPAD() functionisusedtopaddingtherightsideofastringwithaspecificsetofcharacters.
RPAD(ENAME,10,'*')
ali*******
haji******
mohammad**
ravi******
irfath****
DATABASEMANAGEMENTSYSTEMS
ltrim:LTRIM() function is used to remove all specified characters from the left ends id of a string
24
hi********
5. rtrim:RTRIM()functionisusedtoremoveallspecified charactersfromtheleftendsideofastring
******hi
6. lower:lower() function is used to convert the attribute value into lowercase.
SQL>select lower(ename) from emp;
LOWER(ENAM
ali
haji
mohammad
ravi
irfath
UPPER(ENAM
ALI
HAJI
MOHAMMAD
RAVI
IRFATH
INITCAP(EN 25
Ali
Haji
Mohammad
Ravi
Irfath
9. length:length() functionisusedtocalculatethelengthofthegivenattribute.
SQL>selectename,length(ename)fromemp;
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
DEPARTMENTOFAIML
DATABASEMANAGEMENTSYSTEMS
INSTR('WELCOMETO CRRCOE','TO') 26
c) Datefunctions:
SYSDATE
28-APR-21
2. next_day();itreurnsthedateofnextcomingday.
SQL>selectnext_day(sysdate,'sunday')fromdual;
NEXT_DAY
( 02-MAY-
21
3. add_months():itreturnsthenextdateafter addingnumberofmonthsintheorguments.
ADD_MONT
H 28-SEP-21
4. last_day(): The LAST_DAY()function takes a date value as argumentand returns the lastday of
month in that date
SQL>select last_day(sysdate)from dual;
LAST_DAY(
30-APR-21
SQL>selectlast_day('02-FEB-2020')fromdual; DEPARTMENTOFIT
DATABASEMANAGEMENTSYSTEMS
29-FEB-20
27
5. months_between():itreturnsthenumbersofmonthsbetweengiventwodates.
MONTHS_BETWEEN('02-FEB-2021','02-FEB-2020')
12
SQL>selectmonths_between(sysdate,'02-feb-2020')fromdual;
MONTHS_BETWEEN(SYSDATE,'02-FEB-2020')
14.8600769
6. least():itretunsleastvaluefromthegivenargument orattributes.
LEAST(300,450,100,440)
100
7. greatest():itreturnsmaximumvaluesfromthegivenargumentsorattributesintherelation.
SQL>select greatest(300,450,100,440)fromdual;
GREATEST(300,450,100,440)
450
8. trunc():TheTRUNC()functionreturnsaDATEvaluetruncatedtoaspecifiedunit.
SQL>select trunc(sysdate,'mm')fromdual;
TRUNC(SYS
01-APR-21
SQL>selecttrunc(sysdate,'yyyy')fromdual;
TRUNC(SYS
DEPARTMENTOFIT
DATABASEMANAGEMENTSYSTEMS
01-JAN-21
28
9. round():Roundfunctionround anumbertoaspecifiedlengthorprecision.
SQL>selectround(12.49,0)fromdual;
ROUND(12.49,0)
12
SQL>selectround(12.51,0)fromdual;
ROUND(12.51,0)
13
10. to_char():itconvertthegiven date type attributevalues totextand return the date in the specific format.
SQL>selectto_char(sysdate,'yyyy-mm-dd')fromdual;
TO_CHAR(S
Y 2021-04-28
EXPERIMENT-7
Q1)UNION:Findthenamesofsailorswhohavereservedaredoragreenboat.
Query:Using‘UNION’
SQL> [Link]
2 from sailors s,reserves r,
3 boats b
4 where [Link]=[Link] [Link]=[Link] and [Link]='red'
5 union
6 select [Link]
7 from sailors s2,boats b2,reserves r2
8 where [Link]=[Link] and [Link]=[Link]
and [Link]='green';
Output:
SNAME
dustin
Horatio
Lubber
Query:Using‘or’
SQL>[Link]
2 fromsailorss,reservesr,boats b
3 [Link]=[Link]=[Link]([Link]='red'[Link]='green');
Output:
SNAME
SMITH
MARTIN
6. EXISTS
Retrievethenameofeachemployeewho hasadependent withthefirstnameandsamegenderasthe employee
SQL>[Link],[Link] (SELECT
*[Link]=[Link]=GENDERAND [Link]
=DEPENDENT_NAME);
FNAME LNAME
SMITH
MARTIN
[Link]
Retrievethenamesofemployeeswhohavenodependents
SQL>SELECTFNAME,LNAMEFROMEMPLOYEEWHERENOTEXISTS(SELECT* FROM
DEPENDENT WHERE SSN=ESSN);
FNAME LNAME
ALLEN
Output: SNAME
brutus
andy
rusty
horatio
zorba
art
bob
7 rows selected.
Q6)EXISTS Query: Find the names of sailors who have reserved boat number 103 using EXISTS Operator
SQL> select [Link]
2 from sailors s
3 where exists (select * from reserves r where [Link] = 103 and [Link] = [Link] );
Output:
SNAME
dustin
lubber
horatio
Q7) NOT EXISTS: Find the names of sailors who have not reserved boat number 103 using NOT EXISTS
Operator.
7 rows selected.
Q8) ANY: Find sailors whose rating is better than some sailor called ‘BOB’ using ANY Operator. Query:
SQL> select [Link]
2 from sailors s
3 where [Link] > any (select [Link]
4 from sailors s2 where [Link] = 'bob' ); Output:
SID
58
71
74
31
32
64
22
7 rows selected
Q9)ALL: Find the sailor's with the highest rating using ALL Operator.
Query:
SQL> select [Link]
2 from sailors s
3 where [Link] >= all ( select [Link] from sailors s2 );
Output:
SID
58
71
EXPERIMENT-8
AIM: queries using SQL that illustrate the use of INNER JOIN, OUTER JOIN, USING, and NATURAL JOIN
Table Structures
1 students
student_id (Primary Key)
name
major
2 enrollments
student_id (Foreign Key)
course_id
semester
Queries
1. INNER JOIN using USING
This query retrieves the names of students along with their enrolled courses using the USING keyword.
sql
Copy code
SELECT [Link], enrollments.course_id
FROM students
INNER JOIN enrollments USING (student_id);
2. LEFT OUTER JOIN using USING
This query retrieves all students and their enrolled courses. Students who are not enrolled in any courses will still
appear, with NULL in the course_id field.
sql
Copy code
SELECT [Link], enrollments.course_id
FROM students
LEFT OUTER JOIN enrollments USING (student_id);
3. RIGHT OUTER JOIN using USING
This query retrieves all enrollments and the corresponding student names. If a course does not have an associated
student, the student name will be NULL.
sql
Copy code
SELECT [Link], enrollments.course_id
FROM students
RIGHT OUTER JOIN enrollments USING (student_id);
4. NATURAL JOIN
This query automatically joins the tables on columns with the same name, which in this case is student_id.
sql
Copy code
SELECT [Link], enrollments.course_id
FROM students
NATURAL JOIN enrollments;
5. FULL OUTER JOIN using USING
This query retrieves all students and all enrollments, showing NULLs where there are no matches.
sql
Copy code
SELECT [Link], enrollments.course_id
FROM students
FULL OUTER JOIN enrollments USING (student_id);
Summary
INNER JOIN: Returns only matching rows.
OUTER JOIN: Returns all rows from one table and matched rows from the other.
FULL OUTER JOIN enrollments USING (student_id);
Summary
INNER JOIN: Returns only matching rows.
OUTER JOIN: Returns all rows from one table and matched rows from the other.
USING: Simplifies the join condition for columns with the same name.
NATURAL JOIN: Automatically joins based on all columns with the same name.
Feel free to modify these queries based on your specific schema and requirements!
DATABASEMANAGEMENT
Experiment-9
i. Create a simple PL/SQLprogram which includes declaration section,executable section and exception –
29
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 PL/SQLblock..
i).We have to create the student table and insert the records into the table as follows:
SQL>insertintostudentvalues(502,'Raju','third');
1 rowcreated.
SQL>select*fromstudent;
501Ravi second
502Raju third
503Ramu
PL/SQLCODE:
DATABASEMANAGEMENTSYSTEMS
SQL>ed5a
30
Enterthefollowing [Link]
begin
select sid,sname into temp1,temp2 from student where rank='first';
dbms_output.put_line('StudentNo:'||temp1||'Name:'||temp2||'gotfirst 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
PL/SQLproceduresuccessfullycompleted.
SQL>updatestudentsetrank='first'wheresid=503; 1
row updated.
SQL>select*fromstudent;
SIDSNAME RANK
501Ravi second
502Raju third
503Ramu first
SQL>@5a
StudentNo:503Name:Ramugotfirstrank
PL/SQLproceduresuccessfullycompleted.
ii)
SQL>select*fromstudent;
DEPARTMENTOF IT
DATABASEMANAGEMENTSYSTEMS
SIDSNAME RANK 31
501Ravi second
502Raju third
503Ramu first
PL/SQLCODE:
SQL>ed5b
serveroutput on;
DECLARE
sno [Link]%type;
[Link]%type;
srank [Link]%type;
BEGIN
sno := &sno;
name:='&name';
srank:='&srank';
INSERTinto student values(sno,name,srank);
dbms_output.put_line('One record inserted');
COMMIT;
--addingsavepoint
SAVEPOINT s1;
--secondtimeaskinguserforinput
sno := &sno;
name:='&name';
srank:='&srank';
INSERTinto student values(sno,name,srank);
dbms_output.put_line('One record inserted');
ROLLBACK TO SAVEPOINT s1;
END;
/
SQL>@5b;
DEPARTMENTOFIT
DATABASEMANAGEMENTSYSTEMS
SQL>@5b 32
Enter value for sno: 504
old7: sno:=&sno;
new7: sno:=504;
Entervalueforname:ali
old8: name:='&name';
new8: name := 'ali';
Enter value for srank: first
old9: srank:='&srank';
new9: srank := 'first';
PL/SQLproceduresuccessfullycompleted.
SQL>select*fromstudent;
SIDSNAME RANK
501Ravi second
502Raju third
503Ramu first
504ali first
DEPARTMENTOFIT
DATABASEMANAGEMENTSYSTEMS
EXPERIMENT:10
Develop a program that includes the features NESTEDIF,CASE andCASE [Link] program
33
Can be extended using the NULLIF and COALESCE functions.
[Link]:
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;
endif;
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
anumber:=10;
bnumber:=12;
cnumber:=5;
begin
dbms_output.put_line('a='||a||'b='||b||'c='||c);
if a>b AND a>c then
dbms_output.put_line('aisgreatest');
else
ifb>a AND b>cthen
dbms_output.put_line('bisgreatest');
else
dbms_output.put_line('cisgreatest');
endif;
endif;
end;
/
SQL>@6a
DEPARTMENTOFIT
DATABASEMANAGEMENTSYSTEMS
a=10b=12c=5
34
bisgreatest
PL/SQLproceduresuccessfullycompleted.
ExampleofCASE Expression:
DEPARTMENTOFIT
DATABASEMANAGEMENTSYSTEMS
SQL>select loc,case(loc)when'vja'thensalary+2000when'hyd'thensalary+1000elsesalary
35
end"rev_salary"fromemp;
LOC rev_salary
vja 17000
hyd 26000
gnt 35000
vja 47000
PL/SQLCODE:PL/SQLCODEtodemonstrateCASE
SQL> ed 6b
setserveroutputon;
declare
grade char(1);
begin
grade:='&grade';
case
when grade='a'then
dbms_output.put_line('Excellent');
when grade='b' then
dbms_output.put_line('verygood');
when grade='c' then
dbms_output.put_line('good');
when grade='d' then
dbms_output.put_line('fair');
when grade='f' then
dbms_output.put_line('poor');
else
dbms_output.put_line('No suchgrade');
endcase;
end;
/
SQL>@6b
Entervalueforgrade:c
old4:grade:='&grade';
new4:grade:='c';
good
PL/SQLproceduresuccessfullycompleted.
SQL> @6b
Entervalueforgrade:g
old4:grade:='&grade';
DEPARTMENTOF IT
DATABASEMANAGEMENTSYSTEMS
new4:grade:='g';
Nosuchgrade 36
PL/SQLproceduresuccessfullycompleted.
C. NULLIF: Takes two arguments. If the two arguments are equal, then NULL is returned. otherwise
the first argument is returned.
Syntax:selectcolumn_name,NULLIF(argument1,arguement2)fromtable_name;
Example:
SQL>selectename,nullif('ali','ali1')fromemp;
ENAME NUL
ali ali
ravi ali
raju ali
rakesh ali
SQL>selectename,nullif('ali','ali')fromemp;
ENAME NUL
aliravi
raju
rakesh
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,'dbms','IT')from dual;
COALE
dbms
DEPARTMENT OFIT
DATABASEMANAGEMENTSYSTEMS
EXPERIMENT:11 37
ProgramdevelopmentusingWHILELOOPS,numericFORLOOPS,nestedloopsusingERROR
Handling,BUILT–INExceptions,USEdefinedExceptions,RAISEAPPLICATIONERROR.
WHILE LOOP: AWHILE LOOPstatementin PL/SQL programminglanguage repeatedly
executes a target statement as long as a given condition is true.
Syntax:
WHILE condition LOOP
sequence_of_statements
END LOOP;
PL/SQLCode:APL/SQLProgramtofindsumofODDnumberupto givennumberusingWhile loop SQL> ed
7a
setserveroutputon;
declare
inval number;
endvalnumber;
snumberdefault0;
begin
inval:=1;
endval:=&endval;
whileinval<endvalloop
s:=s+inval;
inval:=inval+2;
endloop;
dbms_output.put_line('sumofoddnumbersbetween1and '||endval||'is'||s); end;
/
SQL>@7a
Enter value for endval: 100
old7: endval:=&endval;
new7: endval:=100;
sumofoddnumbersbetween1and100is2500
DEPARTMENTOFIT
DATABASEMANAGEMENTSYSTEMS
thatneedstoexecuteaspecificnumber oftimes.
38
Syntax
FORcounterINinitial_value..final_valueLOOP sequence_of_statements;
ENDLOOP;
PL/SQLCODE:APL/SQLcodetoprintmultiplicationtableusingforloop
SQL>ed 7b
setserveroutputon;
DECLARE
VAR1NUMBER;
VAR2NUMBER;
BEGIN
dbms_output.put_line('Enternumbertoprintmultiplicationtable');
VAR1:=&VAR1;
FOR VAR2 IN 1..10 LOOP DBMS_OUTPUT.PUT_LINE(VAR1||'X'||
VAR2||'='||VAR1*VAR2);
ENDLOOP;
END;
/
SQL>@7b
Enter value for var1: 2
old6:VAR1:=&VAR1;
new6:VAR1:=2;
Enternumertoprintmultiplicationtable 2X1=2
2X2=4
2X3=6
2X4=8
2X5=10
2X6=12
2X7=14
2X8=16
2X9=18
2X10=20
PL/SQLproceduresuccessfullycompleted.
DEPARTMENTOFIT
DATABASEMANAGEMENTSYSTEMS
[Link]:PL/[Link]
39
basic,whileorforloop.
Syntax:
WHILE condition1 LOOP
sequence_of_statements1
WHILE condition2 LOOP
sequence_of_statements2
ENDLOOP;
END LOOP;
PL/SQLCODE:APL/SQLprogramto print nprimenumberusingnestedloop. SQL>
ed 7c
DECLARE
inumber(3);
jnumber(3);
BEGIN
i := 2;
LOOP
j:= 2;
LOOP
exitWHEN((mod(i,j)=0)or(j=i)); j := j
+1;
END LOOP;
IF(j=i)THEN
dbms_output.put_line(i||'isprime');
END IF;
i:= i+1;
exitWHENi=50;
END LOOP;
END;
/
SQL>@7c
DEPARTMENTOFIT
DATABASEMANAGEMENTSYSTEMS
2is prime
3is prime
40
5is prime
7is prime
11isprime
13is prime
17is prime
19is prime
23is prime
29is prime
31is prime
37is prime
41is prime
43is prime
47is prime
PL/SQLproceduresuccessfullycompleted.
DEPARTMENTOFIT
DATABASEMANAGEMENTSYSTEMS
EXPERIMENT:12
41
Programs development using creationofprocedures,passing parametersINand OUTof
PROCEDURES.
SQL>createtableenquiry(enqno1number(3),fnamevarchar2(30));
Tablecreated.
SQL>insertintoenquiryvalues(111,'sai');
1 rowcreated.
SQL>insertintoenquiryvalues(112,'sindhu');
1 rowcreated.
PL/SQLCODEtocreateprocedure
SQL>edfindname
createprocedurefindname(enquiryno1INnumber,fname1OUTvarchar2)is
fname2 varchar2(30);
begin
selectfnameintofname2fromenquirywhereenqno1=enquiryno1;
fname1:=fname2;
exceptionwhenno_data_found then
raise_application_error(-20100,'Thegivennumberisnotpresent'); end;
/
SQL>@findname
Procedurecreated
PL/SQLCodeforcallingprocedureinprogram
DEPARTMENTOFIT
DATABASEMANAGEMENTSYSTEMS
SQL>ed pro8
42
setserveroutputon;
declare
enqno2 number(5);
fname2varchar2(30);
begin
enqno2:=&enqno2;
findname(enqno2,fname2);
dbms_output.put_line('Personnameofequiryid'||enqno2||'is'||fname2); end;
/
SQL>@pro8
Entervalueforenqno2:114
old5: enqno2:=&enqno2;
new5:enqno2:=114;
declare
*
ERRORatline1:
ORA-20100: The given number is not present
ORA-06512:at"[Link]",line7
ORA-06512:atline6
SQL>@pro8
Entervalueforenqno2:112
old5: enqno2:=&enqno2;
new5:enqno2:=112;
PL/SQLproceduresuccessfullycompleted.
DEPARTMENTOFIT
DATABASEMANAGEMENTSYSTEMS
EXPERIMENT:13
43
Programdevelopmentusingcreationofstoredfunctions,invokefunctionsinSQLstatementsandwrite
complexfunctions.
Sol:
SQL>createtabledept(deptnoint,dnamevarchar(10));
Tablecreated.
SQL>insertinto dept values(1219,'sai');
1 rowcreated.
PL/SQLCODEtocreateuserdefine function
createorreplacefunctiongetname(dnonumber) return
varchar2 as
fname1varchar2(30);
begin
selectdnameintofname1fromdeptwheredeptno=dno;
return(fname1);
exception
whenno_data_foundthen
raise_application_error(-20100,'YourenteredDepartmentnumberisnotexists');
end;
/
SQL>@getname
Functioncreated.
DEPARTMENTOFIT
DATABASEMANAGEMENTSYSTEMS
44
SQL>ed pro9
setserveroutputon;
declare
fname2varchar2(30);
deptno2 number(5);
begin
deptno2:=&deptno;
fname2:=getname(deptno2);
dbms_output.put_line(fname2||'isindeptno'||deptno2);
end;
/
SQL>@pro9
Entervaluefordeptno:1219
old5: deptno2:=&deptno;
new5:deptno2:=1219;
saiis indeptno1219
PL/SQLproceduresuccessfullycompleted.
SQL> @pro9
Entervaluefordeptno:1001
old5: deptno2:=&deptno;
new5:deptno2:=1001;
declare
*
ERRORatline1:
ORA-20100:YourenteredDepartmentnumberisnotexists
ORA-06512: at "[Link]", line 9
ORA-06512:atline6
DEPARTMENTOFIT
DATABASEMANAGEMENTSYSTEMS
EXPERIMENT:14
Develop programs using features parameters in a CURSOR, FOR UPDATECURSOR,WHERE CURRENT
45
of clause and CURSOR variables.
Sol:
SQL>createtablecustomers(idnumber(3),namevarchar2(10),agenumber(3),address varchar2(10),
salary number(10,2));
Tablecreated.
SQL>insertintocustomersvalues(1,'ramesh',32,'ahmedabad',2000);
1 rowcreated.
SQL>insert intocustomersvalues(2,'khilan',25,'Delhi',1500);
1 rowcreated.
SQL>insert intocustomersvalues(3,'kaushik',23,'Kota',2000);
1 rowcreated.
SQL>insertintocustomersvalues(4,'chitali',25,'Mumbai',6500);
1 rowcreated.
SQL>select*from customers;
IDNAME AGEADDRESS SALARY
-
1ramesh 32ahmedabad 2000
2khilan 25 Delhi 1500
3kaushik 23 Kota 2000
4chitali 25Mumbai 6500
4 rowsselected.
SQL>ed pro10
DECLARE
SIRCRREDDYCOLLEGEOFENGINEERING DEPARTMENTOFINFORMATIONTECHNOLOGY
c_idcustomers.id%type;
c_namecustomers.name%type;
c_addrcustomers.address%type;
DATABASEMANAGEMENTSYSTEMS
46
SQL>@pro10
1 rameshahmedabad
2 khilanDelhi
3 kaushikKota
4 chitaliMumbai
PL/SQLproceduresuccessfullycompleted.
EXPERIMENT:15
Develop programs using before and after triggers, row and statement triggers and instead of triggers.
DEPARTMENTOFIT
DATABASEMANAGEMENTSYSTEMS
Sol:
47
SQL>createtablecustomers(idnumber(3),namevarchar2(10),agenumber(3),address
varchar2(10),salarynumber(10,2));
Tablecreated.
SQL>insertintocustomersvalues(1,'ramesh',32,'ahmedabad',2000);
1 rowcreated.
SQL>insert intocustomersvalues(2,'khilan',25,'Delhi',1500);
1 rowcreated.
SQL>insert intocustomersvalues(3,'kaushik',23,'Kota',2000);
1 rowcreated.
SQL>insertintocustomersvalues(4,'chitali',25,'Mumbai',6500);
1 rowcreated.
SQL>select*fromcustomers;
IDNAME AGEADDRESS SALARY
-
1 ramesh 32ahmedabad 2000
2 khilan 25 Delhi 1500
3 kaushik 23 Kota 2000
4 chitali 25Mumbai 6500
4 rowsselected.
SQL> @pro11
Triggercreated.
SQL>insertintocustomersvalues(5,'Hardik',27,'Mumbai',5500); Old
salary:
Newsalary:5500
Salarydifference:
1 rowcreated.
SQL>updatecustomerssetsalary=salary+500whereid=2;
Old salary: 1500
Newsalary:2000
Salarydifference:500
1rowupdated.
EXPERIMENT:16
Createatableand performthesearchoperationontableusingindexing and non-indexing techniques.
DEPARTMENTOFIT
DATABASEMANAGEMENTSYSTEMS
Sol:
SQL>CREATETABLETEACHER(STAFF_IDVARCHAR2(4)PRIMARYKEY,STAFF_NAME
VARCHAR2(30),QUALIFICATIONVARCHAR2(10),HIREDATEDATE,JOBVARCHAR2(30),
ADDRESSVARCHAR2(15),PH_NUMNUMBER(10),SALARYNUMBER(7,2),DEPARTMENT
VARCHAR2(10));
Tablecreated.
SQL>insertintoteachervalues('T101','SUNITHA','MCA','29-JUN-06','ASSOCIATE
PROFESSOR','VIJAYAWADA',9985061308,23000,'MCA');
1 rowcreated.
SQL>insertintoteachervalues('T102','FREDSMITH','MTECH','07-MAR-03','ASSOCIATE
PROFESSOR','GUNTUR',9985063445,36000,'MBA');
1 rowcreated.
SQL>insertintoteachervalues('T103','JACKBARNES','BTECH','27-JUN-
07','PROFESSOR','TENALI',9985012345,27000,'MTECH');
1 rowcreated.
SQL>insertintoteachervalues('T104','JANEDOE','MCA','04-JUL-06','ASSISTANT
PROFESSOR','VIJAYAWADA',9985045678,29000,'BTECH');
1 rowcreated.
SQL>insertintoteachervalues('T105','JOESHMOE','MBA','16-AUG-08','ASSOCIATE
PROFESSOR','ELURU',9987651308,36000,'MCA');
1 rowcreated.
SQL>insertintoteachervalues('T106','JONBAKER','MSC(COM)','12-JAN-
03','PROFESSOR','HYDERABAD',8876561308,46000,'MCA');
1 rowcreated.
DEPARTMENTOFIT
DATABASEMANAGEMENTSYSTEMS
SQL>insertintoteachervalues('T107','JOHNDOE','MSC(PHY)','06-FEB-04','ASSISTANT
50
PROFESSOR','VIJAYAWADA',8345661308,31000,'MBA');
1 rowcreated.
SQL>insertintoteachervalues('T108','KIMSMITH','MCA','10-MAR-08','ASSISTANT
PROFESSOR','VIZAG',8374561308,26000,'MTECH');
1 rowcreated.
SQL>insertintoteachervalues('T109','MARYPARKER','MTECH','02-APR-
09','PROFESSOR','NELLORE',7893427649,52000,'MBA');
1 rowcreated.
SQL>insertintoteachervalues('T114','RAMESHNARAYANA','MCA','24-NOV-
04','ASSOCIATEPROFESSOR','NARASARAOPET',9988776655,34000,'MBA');
1 rowcreated.
DEPARTMENTOF IT
DATABASEMANAGEMENTSYSTEMS
SQL>insertintoteachervalues('T115','JOYCEENGLISH','MBA','22-DEC-06','ASSISTANT
51
PROFESSOR','VIJAYAWADA',9998765443,45000,'MBA');
1 rowcreated.
Retrievedetailsofteacherbeforecreationofindex.
SQL>select*fromteacher;
STAFSTAFF_NAMEQUALIFICATHIREDATEJOBADDRESSPH_NUMSALARYDEPARTMENT
T101SUNITHAMCA29-06-06ASSOCIATEPROFESSORVIJAYAWADA998506130823000MCA T102
FREDSMITH MTECH 07-MAR-03 ASSOCIATEPROFESSOR GUNTUR 9985063445 36000 MBA
T103JACK BARNES BTECH27-JUN-07PROFESSORTENALI998501234527000MTECH
T104 JANE DOE MCA04-JUL-06 ASSISTANT PROFESSORVIJAYAWADA 9985045678 29000 BTECH
T105JOE SHMOEMBA16-AUG-08ASSOCIATE PROFESSORELURU998765130836000MCA
T106JONBAKERMSC(COM)12-JAN-03PROFESSORHYDERABAD887656130846000MCA
T107JOHNDOEMSC(PHY)06-FEB-04ASSISTANTPROFESSORVIJAYAWADA834566130831000MBA T108KIM
SMITHMCA10-MAR-08ASSISTANT PROFESSORVIZAG837456130826000MTECH
T109MARYPARKERMTECH02-APR-09PROFESSORNELLORE789342764952000MBA
T110SAMUEL JOHNBTECH19-MAY-05ASSISTANT PROFESSORELURU998222220826000MBA
T111FRANKLIN WONGMBA20-AUG-06ASSOCIATE PROFESSORVIZAG998503333320000MTECH
T112SLICIAZELAYAMCA16-SEP-04ASSISTANTPROFESSORVIJAYAWADA998520202033000BTECH
T113JENNIFERWALLACEMSC(MATHS)25-OCT-03PROFESSORHYDERABAD990219203354000MCA
T114RAMESHNARAYANAMCA24-NOV-04ASSOCIATEPROFESSORNARASARAOPET998877665534000MBA
T115JOYCE ENGLISHMBA22-DEC-06ASSISTANT PROFESSORVIJAYAWADA999876544345000MBA
15rows selected.
Elaps[Link].24
Indexcreation:
DEPARTMENTOFIT
DATABASEMANAGEMENTSYSTEMS
SQL>createindexteacher_job_indonteacher(job);
52
Indexcreated.
Elaps[Link].00
Retrievedetailsofteacheraftercreationof index.
SQL>select*fromteacher;
STAFSTAFF_NAMEQUALIFICATHIREDATEJOBADDRESSPH_NUMSALARYDEPARTMENT
T101SUNITHAMCA29-06-06ASSOCIATEPROFESSORVIJAYAWADA998506130823000MCA T102
FREDSMITH MTECH 07-MAR-03 ASSOCIATEPROFESSOR GUNTUR 9985063445 36000 MBA
T103JACK BARNES BTECH27-JUN-07PROFESSORTENALI998501234527000MTECH
T104 JANE DOE MCA04-JUL-06 ASSISTANT PROFESSORVIJAYAWADA 9985045678 29000 BTECH
T105JOE SHMOEMBA16-AUG-08ASSOCIATE PROFESSORELURU998765130836000MCA
T106JONBAKERMSC(COM)12-JAN-03PROFESSORHYDERABAD887656130846000MCA
T107JOHNDOEMSC(PHY)06-FEB-04ASSISTANTPROFESSORVIJAYAWADA834566130831000MBA T108KIM
SMITHMCA10-MAR-08ASSISTANT PROFESSORVIZAG837456130826000MTECH
T109MARYPARKERMTECH02-APR-09PROFESSORNELLORE789342764952000MBA
T110SAMUEL JOHNBTECH19-MAY-05ASSISTANT PROFESSORELURU998222220826000MBA
T111FRANKLIN WONGMBA20-AUG-06ASSOCIATE PROFESSORVIZAG998503333320000MTECH
T112SLICIAZELAYAMCA16-SEP-04ASSISTANTPROFESSORVIJAYAWADA998520202033000BTECH
T113JENNIFERWALLACEMSC(MATHS)25-OCT-03PROFESSORHYDERABAD990219203354000MCA
T114RAMESHNARAYANAMCA24-NOV-04ASSOCIATEPROFESSORNARASARAOPET998877665534000MBA
T115JOYCE ENGLISHMBA22-DEC-06ASSISTANT PROFESSORVIJAYAWADA999876544345000MBA
15rows selected.
Elaps[Link].13
DEPARTMENTOFIT