22IT480 - DBMS - LabManual UPDATED
22IT480 - DBMS - LabManual UPDATED
22IT480 - DBMS - LabManual UPDATED
LAB MANUAL
Semester : IV
Course Outcomes
On the successful completion of the course, students will be able to
Remember
Understand 20 20
Apply 80 80
Analyse
Evaluate
Create
22IT480-Lab Manual 2023_24
Index Sheet
Cos No.of
S.No List of Experiments
Hours
1. Identification of Mini Project and UI design CO1 2
2. Creation and Modification of relations CO1 2
Integrity constraint enforcement and simple SQL CO1 2
3.
queries
4. Creation and updation of views CO2 2
5. Complex SQL Queries -Date, String, Joins, Subquery CO3 2
6. Query tuning and Normalization CO1 2
PL/SQL block creation and usage of various CO4 2
7.
composite data types
Cursor management, Creation of Triggers and CO5 2
8.
Exceptions in SQL
9. Procedures, functions, and packages in PL/SQL CO5 2
10. Installation of MongoDb and creation of Collections CO6 2
11. Simple and Join Queries in MongoDb CO6
12. Perform MongoDb Query and Projection operation CO6 2
13. Demonstrate Mini-Project as Web application CO5 2
Total 24
22IT480-Lab Manual 2023_24
Aim:
Description:
• The data which is stored in the database at a particular moment of time is called an
instance of the database.
• A database schema is the skeleton structure of the database. It represents the logical
view of the entire database
Procedure
• Identify the application based on your Area of Interest/SIH problems which you will
use throughout all the experiments.
ER Diagram Example:
22IT480-Lab Manual 2023_24
Result:
Thus the application __________is identified and Schema and ER diagram were drawn.
22IT480-Lab Manual 2023_24
Description:
DDL
DDL is short name of Data Definition Language, which deals with database schemas and
descriptions, of how the data should reside in the database.
• CREATE – to create database and its objects like (table, index, views, store procedure,
function and triggers)
• ALTER – alters the structure of the existing database
• DROP – delete objects from the database
• TRUNCATE – remove all records from a table, including all spaces allocated for the records
are removed
• COMMENT – add comments to the data dictionary
• RENAME – rename an object
DML
22IT480-Lab Manual 2023_24
DML is short name of Data Manipulation Language which deals with data manipulation, and
includes most common SQL statements such SELECT, INSERT, UPDATE, DELETE etc, and it is used
to store, modify, retrieve, delete and update data in database.
Procedure
1 Create a table.
2 Execute different DDL commands such as Create, Alter, Drop and Truncate.
Query:
1. CREATE TABLE:
To create a table, you have to name that table and define its columns and datatype for each column.
22IT480-Lab Manual 2023_24
Example:
a)CREATE TABLE new_table AS (SELECT * FROM old_table);
b)CREATE TABLE newcustomers AS (SELECT * FROM customers WHERE customer_id < 5000);
Syntax:
CREATE TABLE new_table AS (SELECT column_1, column2, ... column_n FROM old_table);
Example:
2. ALTER TABLE
22IT480-Lab Manual 2023_24
ALTER TABLE statement specifies how to add, modify, drop or delete columns in a table. It is
also used to rename a table.
Syntax:
Example:
Consider that already existing table customers. Now, add a new column customer_age into
the table customers.
Syntax:
Example
Now, two columns customer_type and customer_address will be added in the table
customers.
Syntax:
Example:
Now the column column_name in the customers table is modified to varchar2 (100) and
forced the column to not allow null values.
Syntax:
Example:
This will modify both the customer_name and city columns in the table.
Syntax:
Example:
Syntax:
2g)Rename table
Syntax:
Example:
3a) DROP TABLE statement is used to remove or delete a table from the Oracle database.
Syntax
Example
This statement will drop the table called customers and issue a PURGE so that the space associated
with the customers table is released and the customers table is not placed in recycle bin. So, it is not
possible to recover that table if required.
4. TRUNCATE TABLE
Syntax
Example
Result Thus the Data Definition Language command was executed and verified successfully.
22IT480-Lab Manual 2023_24
Aim:
To create Primary key, Foreign key, Not null, Unique, Check constraints for the relations
and to execute simple SQL queries.
Description
A.KEYS
1. Primary key
It is the first key which is used to identify one and only one instance of an entity uniquely. An entity
can contain multiple keys as we saw in PERSON table. The key which is most suitable from those
lists become a primary key.
In the EMPLOYEE table, ID can be primary key since it is unique for each employee. In the
EMPLOYEE table, we can even select License_Number and Passport_Number as primary key since
they are also unique.
For each entity, selection of the primary key is based on requirement and developers.
SYNTAX:
Example:
22IT480-Lab Manual 2023_24
2. Candidate key
o A candidate key is an attribute or set of an attribute which can uniquely identify a tuple.
o The remaining attributes except for primary key are considered as a candidate key. The
candidate keys are as strong as the primary key.
For example: In the EMPLOYEE table, id is best suited for the primary key. Rest of the attributes
like SSN, Passport_Number, and License_Number, etc. are considered as a candidate key.
3. Super Key
Super key is a set of an attribute which can uniquely identify a tuple. Super key is a superset of a
candidate key.
For example: In the above EMPLOYEE table, for(EMPLOEE_ID, EMPLOYEE_NAME) the name of two
employees can be the same, but their EMPLYEE_ID can't be the same. Hence, this combination can
also be a key.
4. Foreign key
o Foreign keys are the column of the table which is used to point to the primary key of
another table.
o In a company, every employee works in a specific department, and employee and
department are two different entities. So we can't store the information of the department
in the employee table. That's why we link these two tables through the primary key of one
table.
o We add the primary key of the DEPARTMENT table, Department_Id as a new attribute in the
EMPLOYEE table.
22IT480-Lab Manual 2023_24
o Now in the EMPLOYEE table, Department_Id is the foreign key, and both the tables are
related.
"Persons" table:
"Orders" table:
OrderID OrderNumber PersonID
The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.
The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
Example :
CREATE TABLE Orders (
OrderID int NOT NULL PRIMARY KEY,
OrderNumber int NOT NULL,
PersonID int REFERENCES Persons(PersonID)
);
INSERT QUERIES
1) Insert Query
Insert Statement
In Oracle, INSERT statement is used to add a single record or multiple records into the table.
INSERT INTO table (column1, column2, ... column_n ) VALUES (expression1, expression2, ...
expression_n );
22IT480-Lab Manual 2023_24
Example:
Output:
1 row(s) inserted.
Syntax:
INSERT INTO table (column1, column2, ... column_n ) SELECT expression1, expression2, ...
expression_n FROM source_table WHERE conditions;
Parameters:
3) expression1, expression2, ... expression_n: The values to assign to the columns in the table. So
column1 would be assigned the value of expression1, column2 would be assigned the value of
expression2, and so on.
4) source_table: The source table when inserting data from another table.
5) conditions: The conditions that must be met for the records to be inserted.
Example:
In this method, we insert values to the "suppliers" table from "customers" table. Both tables are
already created with their respective columns.
INSERT INTO suppliers (supplier_id, supplier_name) SELECT age, address FROM customers WHERE
age > 20;
Output:
4 row(s) inserted.
Example
Output:
Count(*)
4
22IT480-Lab Manual 2023_24
B.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 go 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
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.
Query:
Syntax:
Example 1
Example 2:
2.UNIQUE CONSTRAINT
Syntax:
Example 1:
22IT480-Lab Manual 2023_24
3.CHECK Constraint
Syntax
Example 1 :
Example 3:
ALTER TABLE Persons ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City='Sandnes');
4. DEFAULT CONSTRAINT
Example 1:
22IT480-Lab Manual 2023_24
Example 2:
5.INDEX
Syntax:
Example:
SIMPLE QUERIES
1)Select Query
Syntax:
SELECT expressions FROM tables WHERE conditions;
Example:
= Equal
The SQL DISTINCT command is used with SELECT key word to retrieve only distinct or unique
data.
In a table, there may be a chance to exist a duplicate value and sometimes we want to retrieve only
unique values. In such scenarios, SQL SELECT DISTINCT statement is used.
Note: SQL SELECT UNIQUE and SQL SELECT DISTINCT statements are same.
Here is a table of students from where we want to retrieve distinct information For example:
distinct home-town.
HOME_TOWN
Lucknow
Varanasi
The SQL COUNT() function is used to return the number of rows in a query.
Syntax
22IT480-Lab Manual 2023_24
It will return the total number of names of employee_table. But null fields will not be counted.
The "select count(*) from table" is used to return the number of records in table.
The SQL SELECT TOP Statement is used to select top data from a table. The top clause specifies that
how many rows are returned.
Example:
The SQL first() function is used to return the first value of the selected column.
Syntax:
Example:
SELECT FIRST(customer_name) AS first_customer FROM customers;
Example:
SELECT LAST (CUSTOMER_NAME) AS LAST_CUSTOMER FROM CUSTOMERS;
22IT480-Lab Manual 2023_24
7) Update Query
Syntax:
Example:
8) Delete Query
Example:
9. SQL AND
The SQL AND condition is used in SQL query to create two or more conditions to be met.
Syntax:
Example:UPDATE suppliers
SET supplier_name = 'HP' WHERE supplier_name = 'IBM' AND offices = 8;
10.SQL OR
The SQL OR condition is used in a SQL query to create a SQL statement where records are
returned when any one of the condition met. It can be used in a SELECT statement, INSERT
statement, UPDATE statement or DELETE statement.
Syntax:
Example:
SELECT * FROM suppliers WHERE city = 'New York' OR available_products >= 250;
11.SQL ORDER BY Clause
The SQL ORDER BY clause is used for sorting data in ascending and descending order based on one
or more columns.
22IT480-Lab Manual 2023_24
Syntax:
SELECT expressions FROM tables WHERE conditions ORDER BY expression [ASC | DESC];
Example:
Example:
The MIN() function returns the smallest value of the selected column.
The MAX() function returns the largest value of the selected column.
MIN() Syntax
SELECT MIN(column_name) FROM table_name WHERE condition;
Example
SELECT MIN(Price) AS SmallestPrice FROM Products;
MAX() Syntax
SELECT MAX(column_name) FROM table_name WHERE condition;
Example
SELECT MAX(Price) AS LargestPrice FROM Products;
Example:
14.SUM() Syntax
SELECT SUM(column_name) FROM table_name WHERE condition;
Example;
The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to
group the result-set by one or more columns.
GROUP BY Syntax
SELECT column_name(s) FROM table_name WHERE condition GROUP BY column_name(s)
ORDER BY column_name(s);
Example
SELECT COUNT(CustomerID), Country FROM Customers
GROUP BY Country;
22IT480-Lab Manual 2023_24
Example
SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
The HAVING clause was added to SQL because the WHERE keyword could not be used with
aggregate functions.
HAVING Syntax
SELECT column_name(s) FROM table_name WHERE condition GROUP BY column_name(s)
HAVING condition ORDER BY column_name(s);
Example:
Result:
Thus Primary key, Foreign key, Not null, Unique, Check constraints were created for the
relations and simple SQL queries were executed.
22IT480-Lab Manual 2023_24
AIM:
VIEW:
A view contains rows and columns, just like a real table. The fields in a view are fields from one or
more real tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the
data were coming from one single table.
QUERIES:
1. Create view
Table created.
1 row created.
SYNTAX:
CREATE OR REPLACE VIEW view_name AS SELECT column1, column2, ... FROM table_name
WHERE condition;
EXAMPLE
View created.
2. Insert in view
1 row created.
3. Delete in view
1 row deleted.
22IT480-Lab Manual 2023_24
SYS_NO GAMETYPE
---------- --------------------------------------------------
1 Racing
2 Cooking games
4 VR games
5 VR games
6 Racing
4. Update view
1 row updated.
5. Drop view
View dropped.
6. Order by command
SYS_NO GAMETYPE
---------- --------------------------------------------------
1 Racing
3 Cooking games
4 VR games
5 VR games
6 Racing
SQL> create view part_view as select *from particulars with read only constraint rea
dcons;
View created.
8. Execute DML commands in view table and check whether it is reflected in main table.
SQL> insert into particulars_view(sys_no, gametype)values('08', 'Racing');
22IT480-Lab Manual 2023_24
1 row created.
SYS_NO GAMETYPE
---------- --------------------------------------------------
1 Racing
3 Cooking games
4 VR games
5 VR games
6 Racing
8 Racing
6 rows selected.
1 Racing 30
3 Cooking games 25
4 VR games 50
5 VR games 50
6 Racing 30
8 Racing
6 rows selected.
IT IS REFELECTED.
9. Execute DML commands in main table and check whether it is reflected in view table.
1 row created.
1 Racing 30
3 Cooking games 25
4 VR games 50
5 VR games 50
6 Racing 30
8 Racing
10 Cooking games 25
12 Racing 30
8 rows selected.
SYS_NO GAMETYPE
---------- --------------------------------------------------
1 Racing
3 Cooking games
4 VR games
5 VR games
6 Racing
8 Racing
10 Cooking games
12 Racing
IT IS REFLECTED.
10. Do DML operations in view table with read only constraint and tell what happens.
ERROR at line 1:
RESULT:
Thus the commands on creation and updation of views were executed and verified
successfully.
22IT480-Lab Manual 2023_24
Aim:
To execute the given Queries and to perform different Join operation for the application chosen .
Description:
SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a related column between
them.
• (INNER) JOIN: Returns records that have matching values in both tables
• LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from
the right table
• RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records
from the left table
• FULL (OUTER) JOIN: Return all records when there is a match in either left or right table
22IT480-Lab Manual 2023_24
INNER JOIN:
Syntax:
EXAMPLE:
The LEFT JOIN keyword returns all records from the left table (table1), and the matched records
from the right table (table2). The result is NULL from the right side, if there is no match.
Syntax:
SELECT column_name(s) FROM table1 LEFT JOIN table2 ON
table1.column_name = table2.column_name;
Example
The RIGHT JOIN keyword returns all records from the right table (table2), and the matched records
from the left table (table1). The result is NULL from the left side, when there is no match.
Syntax
SELECT column_name(s) FROM table1 RIGHT JOIN table2
ON table1.column_name = table2.column_name;
Example:
The FULL OUTER JOIN keyword return all records when there is a match in either left (table1) or
right (table2) table records.
SYNTAX
22IT480-Lab Manual 2023_24
EXAMPLE
Syntax
SELECT column_name(s) FROM table1 T1, table1 T2 WHERE condition;
EXAMPLE
The UNION operator is used to combine the result-set of two or more SELECT statements.
• Each SELECT statement within UNION must have the same number of columns
• The columns must also have similar data types
• The columns in each SELECT statement must also be in the same order
Syntax
SELECT column_name(s) FROM table1 UNION SELECT column_name(s) FROM table2;
Example
SELECT City FROM Customers UNION SELECT City FROM Suppliers ORDER BY City;
UNION ALL
The UNION operator selects only distinct values by default. To allow duplicate values, use UNION
ALL:
Syntax
SELECT column_name(s) FROM table1 UNION ALL SELECT column_name(s) FROM table2;
EXAMPLE
SELECT City FROM Customers UNION ALL SELECT City FROM Suppliers ORDER BY City;
SQL Aliases
22IT480-Lab Manual 2023_24
SQL aliases are used to give a table, or a column in a table, a temporary name.Aliases are often used
to make column names more readable.An alias only exists for the duration of the query.
QUERIES:
Customer Table:
Orders Table:
Salesman Table:
1. Write a query to list the number of jobs available in the employees table.
2. Write a query to get the total salaries payable to employees.
3. Write a query to get the minimum salary from employees table
4. Write a query to get the maximum salary of an employee working as a Programmer.
5. Write a query to get the average salary and number of employees working the department 90.
6. Write a query to get the highest, lowest, sum, and average salary of all employees
7. Write a query to get the number of employees with the same job.
8. Write a query to get the difference between the highest and lowest salaries
9. Write a query to find the manager ID and the salary of the lowest-paid employee for that
manager.
10. Write a query to get the department ID and the total salary payable in each department
22IT480-Lab Manual 2023_24
String functions:
1. Write a query to update the portion of the phone_number in the employees table, within the
phone number the substring '124' will be replaced by '999'.
2. Write a query to get the details of the employees where the length of the first name greater
than or equal to 8
3. Write a query to display leading zeros before maximum and minimum salary.
4. Write a query to append '@example.com' to email field.
5. Write a query to get the employee id, email id (discard the last three characters)
6. Write a query to extract the last 4 character of phone numbers.
7. Write a query to get the locations that have minimum street length
8. Write a query to display the length of first name for employees where last name contain
character 'c' after 2nd position.
9. Write a query that displays the first name and the length of the first name for all employees
whose name starts with the letters 'A', 'J' or 'M'. Give each column an appropriate label. Sort
the results by the employees' first names.
10. Write a query to display the first name and salary for all employees. Format the salary to be
10 characters long, left-padded with the $ symbol. Label the column SALARY.
Date functions :
1. Write a query to display the first day of the month (in datetime format) three months before
the current month.
2. Write a query to get the distinct Mondays from hire_date in employees tables.
3. Write a query to get the last day of the current year
4. Write a query to get the current date in the following format.
Result:
Thus the given Queries were executed and Join operations were performed for the application
chosen
22IT480-Lab Manual 2023_24
Aim:
Procedure:
5) Use EXISTS Instead of DISTINCT when using joins which includes tables
having the one-to-many relationship.
Distinct sorts the retrieved rows before suppressing the duplicate rows
6) Use UNION ALL instead of UNION.
NORMALIZATION:
Normalization is a database design technique that reduces data redundancy and eliminates
undesirable characteristics like Insertion, Update and Deletion Anomalies. Normalization rules
divides larger tables into smaller tables and links them using relationships. The purpose of
Normalisation in SQL is to eliminate redundant (repetitive) data and ensure data is stored logically.
Example:
22IT480-Lab Manual 2023_24
A relation is in first normal form only if the relational table doesn’t contain any multivalued
attributes. (The relation contains only single-valued attributes).
Result:
Thus, 15 Query tuning commands and normalization are executed with reasoning.
22IT480-Lab Manual 2023_24
Ex.No: 7 PL/SQL BLOCK CREATION AND USAGE OF VARIOUS COMPOSITE DATA TYPES
Aim:
To practice with PL/SQL block creation and various composite data types
Description:
PL/SQL is a combination of SQL along with the procedural features of programming languages. It
was developed by Oracle Corporation to enhance the capabilities of SQL.
LOOP
//Sequence of statements;//
END LOOP;
Procedure:
Example:
PL/SQL program to add two numbers or integers and fetching the result into a third variable. This
program takes two inputs one for each variable and adds the result to a third variable and prints it.
Declare
Var1 integer;
Var2 integer;
Var3 integer;
Begin
Var1:=&var1;
Var2:=&var2;
Var3:=var1+var2;
Dbms_output.put_line(var3);
End;
/
22IT480-Lab Manual 2023_24
declare
n number;
fac number:=1;
i number;
begin
n:=&n;
for i in 1..n
loop
fac:=fac*i;
end loop;
dbms_output.put_line('factorial='||fac);
end;
/
Sample Output
declare
n number:=407;
22IT480-Lab Manual 2023_24
s number:=0;
r number;
len number;
m number;
begin
m:=n;
len:=length(to_char(n));
while n>0
loop
r:=mod(n,10);
s:=s+power(r,len);
n:=trunc(n/10);
end loop;
if m=s
then
dbms_output.put_line('armstrong number');
else
dbms_output.put_line('not armstrong number');
end if;
end;
/
Sample Output
armstrong number
declare
n number:=&n;
begin
if mod(n,2)=0
then
dbms_output.put_line('number is even');
else
dbms_output.put_line('number is odd');
end if;
22IT480-Lab Manual 2023_24
end;
Sample output:
Result
Thus the PL/SQL block has been created and executed successfully.
22IT480-Lab Manual 2023_24
Aim:
To practice and implement the concepts of cursor management in different ways so as to get a
complete knowledge about the implementation of cursors
Description:
Cursor:
A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A
cursor holds the rows (one or more) returned by a SQL statement. The set of rows the cursor holds
is referred to as the active set.
You can name a cursor so that it could be referred to in a program to fetch and process the rows
returned by the SQL statement, one at a time. There are two types of cursors −
• Implicit cursors
• Explicit cursors
Sample input:
Program to write a Cursor to list all the Administrators in the Database Table named as
Admin
Declare
CURSOR c1 IS
rec c1%rowtype;
begin
for rec in c1
loop
dbms_output.put_line(rec.aname);
end loop;
end;
Sample Output:
22IT480-Lab Manual 2023_24
Update the table and increase the salary of each customer by 500 and use
the SQL%ROWCOUNT attribute to determine the number of rows affected
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
IF sql%notfound THEN
total_rows := sql%rowcount;
END IF;
END;
Sample Output:
6 customers selected
Explicit Cursors
22IT480-Lab Manual 2023_24
Explicit cursors are programmer-defined cursors for gaining more control over the context area. An
explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created on a
SELECT Statement which returns more than one row.
CURSOR c_customers IS
OPEN c_customers;
CLOSE c_customers;
Example
Following is a complete example to illustrate the concepts of explicit cursors
DECLARE
c_id customers.id%type;
22IT480-Lab Manual 2023_24
c_name customerS.No.ame%type;
c_addr customers.address%type;
CURSOR c_customers is
BEGIN
OPEN c_customers;
LOOP
END LOOP;
CLOSE c_customers;
END;
When the above code is executed at the SQL prompt, it produces the following result
1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP
Triggers:
Triggers are stored programs, which are automatically executed or fired when some events occur.
Triggers are, in fact, written to be executed in response to any of the following events −
• A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
• A database definition (DDL) statement (CREATE, ALTER, or DROP).
• A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).
Triggers can be defined on the table, view, schema, or database with which the event is associated.
22IT480-Lab Manual 2023_24
Creating Triggers
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
22IT480-Lab Manual 2023_24
Exception:
An exception is an error condition during a program execution. PL/SQL supports programmers to
catch such conditions using EXCEPTION block in the program and an appropriate action is taken
against the error condition. There are two types of exceptions −
• System-defined exceptions
• User-defined exceptions
The general syntax for exception handling is as follows. Here you can list down as many exceptions
as you can handle. The default exception will be handled using WHEN others THEN −
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements
........
WHEN others THEN
exception-handling-statements;
end;
DECLARE
22IT480-Lab Manual 2023_24
c_id customers.id%type := 8;
c_name customerS.Name%type;
c_addr customers.address%type;
BEGIN
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
No such customer!
Raising Exceptions
Exceptions are raised by the database server automatically whenever there is any internal
database error, but exceptions can be raised explicitly by the programmer by using the
command RAISE. Following is the simple syntax for raising an exception −
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;
You can use the above syntax in raising the Oracle standard exception or any user-defined
exception. In the next section, we will give you an example on raising a user-defined exception.
You can raise the Oracle standard exceptions in a similar way.
User-defined Exceptions
PL/SQL allows you to define your own exceptions according to the need of your program. A user-
defined exception must be declared and then raised explicitly, using either a RAISE statement or
the procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.
22IT480-Lab Manual 2023_24
Example
The following example illustrates the concept. This program asks for a customer ID, when the user
enters an invalid ID, the exception invalid_id is raised.
DECLARE
c_id customers.id%type := &cc_id;
c_name customerS.Name%type;
c_addr customers.address%type;
-- user defined exception
ex_invalid_id EXCEPTION;
BEGIN
IF c_id <= 0 THEN
RAISE ex_invalid_id;
ELSE
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
END IF;
EXCEPTION
WHEN ex_invalid_id THEN
dbms_output.put_line('ID must be greater than zero!');
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Enter value for cc_id: -6 (let's enter a value -6)
old 2: c_id customers.id%type := &cc_id;
new 2: c_id customers.id%type := -6;
ID must be greater than zero!
Result
Thus the implementation of cursor, triggers and exceptions have been done and verified
successfully
22IT480-Lab Manual 2023_24
Aim:
Description
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.
SYNTAX
2 num number;
3 fact number;
5 RETURN number
6 IS f number;
7 BEGIN
8 IF x=0 THEN
9 f:=1;
10 ELSE
11 f:=x*factorial(x-1);
22IT480-Lab Manual 2023_24
12 END IF;
13 RETURN f;
14 END;
15 BEGIN
16 num:='&num';
17 fact:=factorial(num);
19 END;
20 /
FACTORIAL OF 8 IS 40320
Application :
2 RETURN number IS
3 total number(2) := 0;
4 BEGIN
6 where bloodtype='O+ve';
7 RETURN total;
8 END;
9 /
Function created.
22IT480-Lab Manual 2023_24
SQL> DECLARE
2 c number(2);
3 BEGIN
4 c :=bloodstock1();
5 dbms_output.put_line(c);
6 END;
7 /
Procedures :
• A procedure is a group of PL/SQL statements that you can call by name.
• A procedure is a module performing one or more actions , it does not need
to return any values.
Creating a Procedure:
Syntax
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
22IT480-Lab Manual 2023_24
{IS | AS}
BEGIN
< procedure_body >
END
procedure_name;
Sample Programs:
Creation and dropping of procedure:
2 AS
3 BEGIN
4 dbms_output.put_line('Hello World!');
5 END;
6 /
Procedure created.
Hello World!
Procedure dropped.
SQL> DECLARE
2 a number;
3 b number;
4 c number;
6 BEGIN
7 IF x < y THEN
8 z:= x;
22IT480-Lab Manual 2023_24
9 ELSE
10 z:= y;
11 END IF;
12 END;
13 BEGIN
14 a:= 23;
15 b:= 45;
16 findMin(a, b, c);
18 END;
19 /
Square of a number:
SQL> DECLARE
2 a number;
4 BEGIN
5 x:=power(x,x);
6 END;
7 BEGIN
8 a:='&a';
9 squareNum(a);
11 END;
12 /
old 8: a:='&a';
22IT480-Lab Manual 2023_24
new 8: a:='8';
SQUARE :: IS 16777216
PACKAGES:
Packages are schema objects that groups logically related PL/SQL types, variables,
and subprograms.
A package will have two mandatory parts −
• Package specification
• Package body or definition .
SYNTAX:
For creating package:
CREATE [OR REPLACE] PACKAGE <package_name>
IS
<sub_program and public element declaration>
.
.
END <package name>
6 rows selected.
2 -- Adds a customer
4 c_name customers.name%type,
5 c_age customers.age%type,
6 c_addr customers.address%type,
7 c_sal customers.salary%type);
9 -- Removes a customer
12 PROCEDURE listCustomer;
13
14 END c_package;
15 /
Package created.
3 c_name customers.name%type,
4 c_age customers.age%type,
5 c_addr customers.address%type,
22IT480-Lab Manual 2023_24
6 c_sal customers.salary%type)
7 IS
8 BEGIN
11 END addCustomer;
12
14 BEGIN
16 WHERE id = c_id;
17 END delCustomer;
18
19 PROCEDURE listCustomer IS
20 CURSOR c_customers is
25 BEGIN
28 name_list.extend;
29 name_list(counter) := n.name;
31 END LOOP;
32 END listCustomer;
33
22IT480-Lab Manual 2023_24
34 END c_package;
35 /
SQL> DECLARE
2 code customers.id%type:= 8;
3 BEGIN
6 c_package.listcustomer;
7 c_package.delcustomer(code);
8 c_package.listcustomer;
9 END;
10 /
Output:
Customer(1)Meena
Customer(2)Kalai
Customer(3)Vani
Customer(4)Sri
Customer(5)Vidhya
Customer(6)Devi
Customer(7)Rajnish
Customer(8)Subham
Customer(1)Meena
Customer(2)Kalai
Customer(3)Vani
Customer(4)Sri
22IT480-Lab Manual 2023_24
Customer(5)Vidhya
Customer(6)Devi
Customer(7)Rajnish
Result:
Thus the functions , procedures and packages are successfully executed in SQL.
22IT480-Lab Manual 2023_24
Aim:
To install MongoDB and create a collection with it.
Description:
MongoDB is an open-source document database and leading NoSQL database.
MongoDB iswritten in C++. It is a cross-platform document-oriented database program.
Classified as a NoSQLdatabase program, MongoDB uses JSON-like documents with
optional schemas.
Procedure:
Installation:
STEP 1: Go to https://www.mongodb.com/download-center/community. Select the
necessaryconfiguration and click on the Download button.
22IT480-Lab Manual 2023_24
STEP 3: Accept the user agreement and Select the setup type as Complete and click Next.
22IT480-Lab Manual 2023_24
STEP 7: MongoDB requires a data directory under the C drive which will have a db file. Create it.
22IT480-Lab Manual 2023_24
STEP 8: In the command prompt, enter the following command “cd C:\Program Files\MongoDB\Server\4.2\bin”.
Once inside the folder, type “mongod” command.
STEP 9: After the service is started open another command prompt and move to the directory
specified before. Type “mongo” in order to open the mongo shell.
22IT480-Lab Manual 2023_24
“db.collectionname.insert({"key":value,"key":"value})” command.
Result:
Thus, the MongoDB was installed and the collections is created successfully.
22IT480-Lab Manual 2023_24
EX.NO.11
Aim:
To perform simple queries and join operations using MongoDB.
Procedure:
INSERT:
Single Record:
db.collection_name.insert({key:value,…})
Multiple Records:
db. collection_name.insertMany([
{key:value,…},
{key:value,…},
{key:value,…}
])
All columns
Specific column(s)
UPDATE:
Single record:
db.collection_name.update({“Identifier”:value},{$set:{“updating coloumn”:value}}})
Multiple records:
db.collection_name.updateMany({“identifier”:val},{$set:{“updating coloumn”:val}}})
DELETE:
Single Record:
db.collection_name.remove({“key”:value})
Multiple Records:
db.collection_name.deleteMany({“key”:value})
COUNT:
SORT:
22IT480-Lab Manual 2023_24
db.collec
tion_na
me.coun
t()
JOIN:
db.collection_name.aggregation([
{
$lookup:
{
{
from: <collection to join>,
localField: <field from the input documents>,
foreignField: <field from the documents of the "from" collection>,as:
<output array field>
}
}
}
])
Result:
Thus, simple queries are executed and join operations are performed successfully.
22IT480-Lab Manual 2023_24
Aim:
To execute queries and projection operations using MongoDB.
Procedure:
PROJECTION:
MongoDB Projection is used when we want to get the selected fields of the documentsrather
than all fields.
Specific column(s)
QUERIES:
SELECT DISTINCT:
db.collection_name.distinct(“key”)
22IT480-Lab Manual 2023_24
AND:
db.collection_name.find( { $and: [ {key:value},…,{key:value} ] } )
OR:
db.collection_name.find( { $or: [ {key:value},…,{key:value} ] } )
COUNT:
db.collection_name.count()
22IT480-Lab Manual 2023_24
SORT:
Ascending:
db.collection_name.find().sort({key:1})
Descending:
db.collection_name.find().sort({key:-1})
Display certain column(s) after sorting
db.collection_name.find({},{key:0}).sort({key:-1})
SKIP:
To skip the top number of rows as specified in the query result
db.collection_name.find().skip(number)
DROP COLLECTION:
db.collection_name.drop()
Result:
Thus, queries are executed and projection operations are performed successfully.
22IT480-Lab Manual 2023_24
Aim:
To develop and demonstrate the application chosen as a Miniproject.
Procedure:
• List the functionalities implemented in Web application.
• Design Webpage for the functionalities mentioned.
• Create the Database for your application
• Connect the Database with Webapplication
• Have the screenshot of the Webpage , Queries and output
Result:
Thus Web application has been created for the application chosen with Database Connectivity.