Dbms Manual
Dbms Manual
SINHGAD COLLEGE OF
ENGINEERING
Vadgaon(Bk), Pune
Department of Computer Engineering
LABORATORY MANUAL
2022-23
CERTIFICATE
Database Connectivity:
Write a program to implement MySQL/Oracle database
connectivity with any front end
9 language to implement Database navigation operations (add,
delete, edit etc.)
Group B NOSQL Databases
2 MongoDB Queries:
Title
ER Modeling and Normalization:
Signature
Ans:
Questions that are addressed during conceptual design: – What are the entities and relationships of
interest (miniworld)? – What information about entities and relationships among entities needs to
be stored in the database? – What are the constraints (or business rules) that (must) hold for the
entities and relationships? • A database schema in the ER model can be represented pictorially
(Entity-Relationship diagram)
• Entity: real-world object or thing with an independent existence and which is distinguishable f
rom other objects. Examples are a person, car, customer, product, gene, book etc. • Attributes: an
entity is represented by a set of attributes (its descriptive properties), e.g., name, age, salary, price
etc. Attribute values that describe each entity become a major part of the data eventually stored in a
database. • With each attribute a domain is associated, i.e., a set of permitted values for an attribute.
Possible domains are integer, string, date, etc.
• Entity Type: Collection of entities that all have the same attributes, e.g., persons, cars, customers
etc. • Entity Set: Collection of entities of a particular entity type at any point in time; entity set is
typically referred to using the same name as entity type.
• Degree of a relationship: refers to the number of entity types that participate in the relationship
type (binary, ternary, . . . ).
• Roles: The same entity type can participate more than once in a relationship type.
• Relationship Attributes:
A relationship type can have attributes describing properties of a relationship. “customer ’Smith’
ordered product ’PC42’ on January 11, 2005, for $2345”. These are attributes that cannot be
associated with participating entities only, i.e., they make only sense in the context of a relationship.
• Note that a relationship does not have key attributes! The identification of a particular relationship
in a relationship set occurs through the keys of participating entities.
An ER diagram shows the relationship among entity sets. An entity set is a group of similar entities nd
hese entities can have attributes. In terms of DBMS, an entity is a table or attribute of a table in
database, so by showing relationship among tables and their attributes, ER diagram shows the
complete logical structure of a database. Lets have a look at a simple ER diagram to understand this
concept
A simple ER Diagram:
however a student cannot study in multiple colleges at the same time. Student entity has attributes
such as Stu_Id, Stu_Name & Stu_Addr and College entity has attributes such as Col_ID &
Col_Name.
Here are the geometric shapes and their meaning in an E-R Diagram. We will discuss these terms
in detail in the next section(Components of a ER Diagram) of this guide so don’t worry too much
Components of a ER Diagram
Conversion of ER diagram to TableThe database can be represented using the notations, and these
notations can be reduced to a collection of tables.In the database, every entity set or relationship set
can be represented in tabular form.
In the given ER diagram, LECTURE, STUDENT, SUBJECT and COURSE forms individual tables.
In the STUDENT entity, STUDENT_NAME and STUDENT_ID form the column of STUDENT table.
Similarly, COURSE_NAME and COURSE_ID form the column of COURSE table and so on.
In the given ER diagram, COURSE_ID, STUDENT_ID, SUBJECT_ID, and LECTURE_ID are the key attribute
of the entity.
In the student table, a hobby is a multivalued attribute. So it is not possible to represent multiple
values
STUDENT_ID and HOBBY. Using both the column, we create a composite key.
In the given ER diagram, student address is a composite attribute. It contains CITY, PIN, DOOR#,
STREET, and STATE. In the STUDENT table, these attributes can merge as an individual column.
In the STUDENT table, Age is the derived attribute. It can be calculated at any point of time by
calculating
Using these rules, you can convert the ER diagram to tables and columns and assign the mapping
between the tables. Table structure for the given ER diagram is as below
• student_id is the primary key and will be unique for every row, hence we can
use student_id to fetch any row of data from this table
• This is Dependency and we also call it Functional Dependency.
• student_id + subject_id.----pk
Conclusion : Thus we have studied how to modify E-R Model & Normalization.
Lab Exercise
1 : Suppose you are given the following requirements for a simple database for the National Hockey
League (NHL): the NHL has many teams, each team has a name, a city, a coach, a captain, and a set
of players, each player belongs to only one team, each player has a name, a position (such as left
wing or goalie), a skill level, and a set of injury records, a team captain is also a player, a game is
played between two teams (referred to as host_team and guest_team) and has a date (such as May
11th, 1999) and a score (such as 4 to 2). Construct a clean and concise ER diagram for the NHL
database
2. A university registrar’s office maintains data about the following entities: 1. courses, including
number, title, credits, syllabus, and prerequisites; 2. course offerings, including course number, year,
semester, section number, instructor(s), timings, and classroom; 3. students, including student-id,
name, and program; 4. instructors, including identi-cation number, name, department, and title.
Further, the enrollment of students in courses and grades awarded to students in each course they
are enrolled for must be appropriately modeled. Construct an E-R diagram for the registrar’s of-
ce.Document all assumptions that you make about the mapping constraints.
3(a) Construct an E-R diagram for a car-insurance company whose customers own one or more cars
each. Each car has associated with it zero to any number of recorded accidents.
3(b) Construct appropriate tables for the above ER Diagram ?
4(a) Construct an E-R diagram for a hospital with a set of patients and a set of medical doctors.
Associate with each patient a log of the various tests and examinations conducted.
4(b) Construct appropriate tables for the above ER Diagram :
5. Consider a database used to record the marks that students get in different exams of different
course offerings.
a) Construct an E-R diagram that models exams as entities, and uses a ternary relationship, for the
above database.
b) Construct an alternative E-R diagram that uses only a binary relationship between students and
course-offerings. Make sure that only one relationship exists between a particular student and course-
offering pair, yet you can represent the marks that a student gets in different exams of a course
offering
Roll No.
Class T.E. (C.E.)
Date
Subject Database Management System Laboratory
Signature
Title: Design and Develop SQL DDL statements which demonstrate the use of SQL objects
such as Table, View , Index, Sequence, Synonym
Data
Definition in
SQL Creating
Tables
Syntax:-
Create table<table
name>
(colume_name 1
datatype size(),
colume_name 2
datatype size(),
….
CREATE TABLE<TableName>(<ColumnName>,
<Columnname>)ASSELECT <ColumnName>,
<Columnname> FROM <TableName>;
- If the source table contains the records, then new table is also created with the same
records present in the source table.
• Syntax:
CREATE TABLE <TableName> (<ColumnName>, <Columnname>) AS SELECT
<ColumnName>, <Columnname> FROM <TableName> WHERE 1=2; (Or)
Constraints
The definition of a table may include the specification of integrity constraints. Basicallytwo
types of constraints are provided: column constraints are associated with a single column
whereas table constraints are typically associated with more than one column. A constraint
can be named. It is advisable to name a constraint in order to get more meaningful
information when this constraint is violated due to, e.g., an insertion of a tuple that violates
the constraint. If no name is specified for the constraint, Oracle automatically generates a
name of the pattern SYS C<number>.Rules are enforced on data being stored in a table, are
called Constraints.
Both the Create table & Alter Table SQL can be used to write SQL
sentences that attach constraints.
Basically constraints are of three types :
1) Domain
- Not Null
- Check
2) Entity
- Primary Key
- Unique
3) Referential
- Foreign key
-
4) Not Null:-Not null constraint can be applied at column level only.
<ColumnName> datatype(size),…. );
CREATE TABLE
<table Name> (<Column Name> data type(size),
<Column Name> data type(size),….,
CHECK (column Name
condition)); After table
creation
Alter table tablename
Add constraints constraintname
• A table can have only one primary key. Can not be left blank Data must be
UNIQUE.
• Not allows null values
• Not allows duplicate values.
• Unique index is created automatically if there is a
primary key. Primary key constraint defined at column level
Syntax:
CREATE TABLE <Table Name>
(<ColumnName1> <Data Type>(<Size>)PRIMARY
KEY,<columnname2
<data type(<size>),…..);
• Primary key constraint defined at
Table level Syntax:
CREATE TABLE <Table Name>
(<ColumnName1><Data Type>(<Size>) ,…,PRIMARY
KEY(<ColumnName1> <ColumnName2>));
• key constraint defined at Table level
Syntax:
CREATE TABLE <Table Name>
(<ColumnName1><DataType>(<Size>)<columnname2 data
type<(size)<,<columnname3 data type<size>constraint
constraint name PRIMARY KEY(<ColumnName1>));
After table creation
Alter table table name
Add(constraint constraint name primary key(column name));
The Unique Key Constraint
To drop the
constraints Syntax:-
Drop constraint constraint name;
Describe commands
To view the structure of the table created use the DESCRIBE command.The command
displays the column names and datatypes
Syntax:-
Desc[ribe]<table_name>
e.g desc student
Restrictions for creating a table:
Case1:-
Alter table <table_name>
Add( colume_name 1
datatype size(),
colume_name 2
datatype size(),
After you create a table, you may need to change the table structures because you need to
havea column definition needs to be changed. Alter table statement can be used for this
purpose.
You can add columns to a table using the alter table statement with the ADD clause.
E.g. Suppose you want to add enroll_no in the student table then we write
Alter table student Add(enroll_no number(10));
You can modify existing column in a table by using the alter table statement with modify
clause.
E.g. Suppose you want to modify or chang the size of previously defined field name in the
student table then we write
Alter table student modify (name char(25)); Dropping a column from a table
Syntax :
ALTER TABLE <Tablename> DROP COLUMN <ColumnName> ;
Drop table command remnoves the definitions of an oracle table.When you drop a table
,the database loses all the data in the table and all the indexes associated with it.
e.g drop table student;
Truncate table command Syntax:-
Trunc table<table_name>
The truncate table statement is used to remove all rows from a table and to release the
storagespace used by the table.
e.g. Trunc table student;
eg.
Select ic.index_name, ic.column_name, ic.colun_position col_pos, ix.uniqueness from
user_indexes ix, user_ind_columns ic where
ic.index_name=ix.index_name and ic.table_name=‟emp‟;
Removing an Index
Syntax:-
Drop index
<index_name>; eg. Drop index
emp_name_idx;
Note: 1) we cannot modify indexes.
2) To change an index, we must drop it and the re-create it.
Views
View is a logical representation of subsets of data from one or more tables. A view takes the
output of a query and treats it as a table therefore view can be called as stored query or a
virtual table.The tables upon which a view is based are called base tables. In Oracle the SQL
command to create a view (virtual table) has the form
The optional clause or replace re-creates the view if it already exists. <column(s)> names the
columns of the view. If <column(s)> is not specified in the view definition, the columns of the
In the select statement the column alias ANNUAL SALARY is specified for the
expression SAL∗12 and this alias is taken by the view. An alternative
formulation of the above view
definition is
Create view DEPT20 (ENAME, JOB, ANNUAL SALARY) as select ENAME, JOB, SAL
A view can be used in the same way as a table, that is, rows can be retrieved from a view(also
respective rows are not physically stored, but derived on basis of the select statement inthe
viewdefinition), or rows can even be modified. A view is evaluated again each time it is
accessed. In Oracle SQL no insert, update, or delete modifications on views are allowed
that use one of the following constructs in the view definition:
• Joins
• Aggregate function such as sum, min, max etc.
• set-valued sub queries (in, any, all) or test for existence (exists)
• group by clause or distinct clause
In combination with the clause with check option any update or insertion of a
row into the view is rejected if the new/modified row does not meet the view
definition, i.e., these rows would not be selected based on the select statement. A
with check option can be named using the constraint clause.
A view can be deleted using the command delete <view-name>. To describe the structure of a
view
e.g. Describe stud;
In the select statement the column alias ANNUAL SALARY is specified for the expression
SAL∗12 and this alias is taken by the view. An alternative formulation of the above view
definition is
12 from EMP where DEPTNO = 20;
Create view DEPT20 (ENAME, JOB, ANNUAL SALARY) as select ENAME, JOB, SAL
A view can be used in the same way as a table, that is, rows can be retrieved from a view(also
respective rows are not physically stored, but derived on basis of the select statement in the
viewdefinition), or rows can even be modified.
Sequence:
A sequence is a database object, which can generate unique, sequential integer
values. It can be used to automatically generate primary key or unique key
values. A sequence can be either in an ascending or descending order.
Syntax : Create
sequence<sequence_name>
[increment by n]
[start with n]
[{maxvalue n | nomaxvalue}] [{minvalue n| nominvalue}]
[{cycle |nocycle}]
[{cache n| nocache}];
After creating a sequence we can access its values with the help of pseudo
columns like curval & nextval.
Nextval :
nextval returns initial value of the sequence when reference to for the first time. Last references
to the nextval will increment the sequence using the increment by clause & returns the new
value.
Curval :
curval returns the current value of the sequence which is the value returned by the last
reference to last value
Modifyning a sequence:
The sequence can be modified when we want to perform the following :
Set or eliminate minvalue or maxvalue
Syntax :
Tables
In relational database systems (DBS) data are represented using tables (relations).
A query issued against the DBS also results in a table. A table has the following
structure:
Variable length
national
character 4000 32767
STRING
NVARCHAR2 set string bytes 4000 bytes bytes
N/A VARCHAR
(size) having minimu minimum is minimum is
maximum m is 1 1 1
length size
bytes.
Now
deprecated
- VARCHAR is
VARCHAR - - -
a synonym
for
VARCHAR2
but this usage
may change in
future versions.
Fixed length
character data 255 bytes 2000 32767
oflength size Default bytes 2000 bytes bytes
bytes. This and Default Default and Default CHARAC
CHAR(size) should be used minimum and minimum and TER
for fixed length size is 1 minimu size is 1 byte. minimum
data. Such as byte. m size is1 size is 1
codes A100, byte. byte.
B102...
NCHAR Fixed length 2000 2000 bytes 32767
(size) national N/A bytes Default and bytes
character set Default minimum Default
size
Date
Signature
Title :- Write at least 10 SQL queries for suitable database application using SQL DML
statements: Insert, Select, Update, Delete with operators, functions, and set operator.
To insert string data types, it is required to keep all the values into double or
single quote, for example:-"value".
□ You can use one or more tables separated by comma to include various
conditions using a WHERE clause, but WHERE clause is an optional part
of SELECT command.
□ You can fetch one or more fields in a single SELECT command.
□ You can specify star (*) in place of fields. In this case, SELECT will return all the fields.
□ You can specify any condition using WHERE clause.
□ You can specify an offset using OFFSET from where SELECT will start
returning records. By default offset is zero.
□ You can limit the number of returns using LIMIT attribute.
The SQL SELECT statement returns a result set of records from one or more tables. A SELECT
statement retrieves zero or more rows from one or more database tables or database
views. In most applications, SELECT is the most commonly used Data Manipulation Language
(DML) command. As SQL is a declarative programming language, SELECT queries specify a
result set, but do not specify how to calculate it. The database translates the query into a
"query plan" which may vary between executions, database versions and database software.
This functionality is called the "query optimizer" as it is responsible for finding the best
possible execution plan for the query, within applicable constraints.
The SELECT statement has many optional clauses:
□ WHERE specifies which rows to retrieve.
GROUP BY groups rows sharing a property so that an aggregate function can
be applied to each group.
□ HAVING selects among the groups defined by the GROUP BY clause.
□ ORDER BY specifies an order in which to return the rows.
□ AS provides an alias which can be used to temporarily rename tables or columns.
WHERE Clause
We have seen SQL SELECT command to fetch data from table. We can use a conditional
clause called WHERE clause to filter out results. Using WHERE clause, we can specify a
selection criteria to select required records from a table.
Syntax:
Here is generic SQL syntax of SELECT command with WHERE clause to
fetch data from table:
□ You can use one or more tables separated by comma to include various
conditions using a WHERE clause, but WHERE clause is an optional part
of SELECT command.
□ You can specify any condition using WHERE clause.
□ You can specify more than one conditions using AND or OR operators.
The WHERE clause works like an if condition in any programming language. This clause is
used to compare given value with the field value available in table. If given value from outside
is equal to the available field value in table, then it returns that row.
Here is the list of operators, which can be used with
WHERE clause. Assume field A holds 10 and field B
holds 20, then:
Checks if the value of left operand is greater than or equal (A >= B) is not
to thevalue of right operand, if yes then condition true.
>=
becomes true.
The WHERE clause is very useful when you want to fetch selected rows from a
Unless performing a LIKE comparison on a string, the comparison is not case sensitive. You
can make your search case sensitive using BINARY keyword as follows:
LIKE Clause
We have seen SQL SELECT command to fetch data from table. We can also use a conditional
clause called WHERE clause to select required records.
A WHERE clause with equals sign (=) works fine where we want to do an exact match.
Like if "tutorial_author = 'Sanjay'". But there may be a requirement where we want to filter
out all the results where tutorial_author name should contain "jay". This can be
handled using SQL LIKE clause along with WHERE clause.
If SQL LIKE clause is used along with % characters, then it will work like a meta character (*) in
UNIX while listing out all the files or directories at command prompt.
Without a % character, LIKE clause is very similar to equals sign along with WHERE clause.
Syntax:
A WHERE...LIKE clause can be used along with DELETE or UPDATE SQL command also to
specify a condition.
Example:
Following example will return all the records from tutorials_tbl table for which
author nameends with jay:
GROUP BY Clause
You can use GROUP BY to group values from a column, and, if you wish, perform calculations
on that column. You can use COUNT, SUM, AVG, etc., functions on the grouped column.
To understand GROUP BY clause, consider an employee_tbl table, which is
having thefollowing records:
Now, suppose based on the above table we want to count number of days
each employee didwork.
If we will write a SQL query as follows, then we will get the following result:
But this is not serving our purpose, we want to display total number of
pages typed by each person separately. This is done by using aggregate
functions in conjunction with a GROUP BY clause as follows:
We will see more functionality related to GROUP BY in other functions like SUM, AVG, etc.
COUNT Function
COUNT Function is the simplest function and very useful in counting the
number of records, which are expected to be returned by a SELECT statement.
To understand COUNT function, consider an employee_tbl table, which is
having the following records:
> SELECT * FROM employee_tbl;
+ + + + +
| id | name | work_date | daily_typing_pages |
+ + + + +
| 1 | John | 2007-01-24 | 250 |
| 2 | Ram | 2007-05-27 | 220 |
| 3 | Jack | 2007-05-06 | 170 |
| 3 | Jack | 2007-04-06 | 100 |
| 4 | Jill | 2007-04-06 | 220 |
| 5 | Zara | 2007-06-06 | 300 |
| 5 | Zara | 2007-02-06 | 350 |
+ + + + +
7 rows in set (0.00 sec)
Now, suppose based on the above table you want to count total number of rows in
this table, then you can do it as follows:
Similarly, if you want to count the number of records for Zara, then it can be done as follows:
NOTE: All the SQL queries are case insensitive so it does not make any
difference if you give ZARA or Zara in WHERE condition.
MAX Function
MAX function is used to find out the record with maximum value among a record set.
To understand MAX function, consider an employee_tbl table, which is having
the following records:
Now, suppose based on the above table you want to fetch maximum
value ofdaily_typing_pages, then you can do so simply using the
following command:
You can find all the records with maximum value for each name using GROUP
BY clause as follows:
| 1 | John | 250 |
| 2 | Ram | 220 |
| 5 | Zara | 350 |
+ + + +
5 rows in set (0.00 sec)
You can use MIN Function along with MAX function to find out minimum
value as well. Tryout the following example:
MIN Function
MIN function is used to find out the record with minimum value among a record set.
To understand MIN function, consider an employee_tbl table, which is
having the following records:
You can find all the records with minimum value for each name using GROUP
BY clause as follows:
You can use MIN Function along with MAX function to find out minimum
value as well. Tryout the following example:
AVG Function
AVG function is used to find out the average of a field in various records.
To understand AVG function, consider an employee_tbl table, which is
SUM Function
SUM function is used to find out the sum of a field in various records.To understand SUM
function, consider an employee_tbl table, which is having the following records:
HAVING clause
The HAVING clause is used in the SELECT statement to specify filter conditions for group of
rows or aggregates. The HAVING clause is often used with the GROUP BY clause. When using
with the GROUP BY clause, you can apply a filter condition to the columns that appear in the
GROUP BY clause. If the GROUP BY clause is omitted, the HAVING clause behaves like the
WHERE clause. Notice that the HAVING clause applies the condition to each group of rows,
while the WHERE clause applies the condition to each individual row.
Now, we can find which order has total sales greater than $1000. We use the HAVING clauseon the
aggregate as follows
SELECT ordernumber,
SUM(quantityOrdered) AS itemsCount,
SUM(priceeach) AS total
FROM orderdetails
GROUP BY ordernumber
HAVING total > 1000
We can construct a complex condition in the HAVING clause using logical operators such as
OR and AND. Suppose we want to find which order has total sales greater than $1000 and
contains more than 600 items, we can use the following query:
The HAVING clause is only useful when we use it with the GROUP BY clause to generate the
output of the high-level reports. For example, we can use the HAVING clause to answer
some kinds of queries like give me all the orders in this month, this quarter and this year that
have total sales greater than 10K.
UPDATE Query
There may be a requirement where existing data in a table needs to be modified. You can do
so by using SQL UPDATE command. This will modify any field value of any table.
Syntax:
Here is generic SQL syntax of UPDATE command to modify data into table:
Example:
Following example will update tutorial_title field for a record having tutorial_id as 3.
UPDATE tutorials_tbl
SET tutorial_title='Learning JAVA'
WHERE tutorial_id=3;
DELETE Query
Syntax:
Here is generic SQL syntax of DELETE command to delete data from a table:
□ If WHERE clause is not specified, then all the records will be deleted
from the given table.
□ You can specify any condition using WHERE clause.
□ You can delete records in a single table at a time.
The WHERE clause is very useful when you want to delete selected
rows in a table. Deleting Data from Command Prompt:
This will use SQL DELETE command with WHERE clause to delete selected
data into tabletutorials_tbl.
Example:
3. List out the employees who are earning salary between 3000 and 4500
7. List out the employees whose name start with “S” and end with “H”
Select * from employee where last_name Like 'S%H';
8. List out the employees whose name length is 5 and start with “S”
9. List out the employees who are working in department 10 and draw
the salaries more than 3500
Select * from employee where department_id=10 and salary>3500
10. List out the employees who are not receiving commission.
Select * from employee where commission is Null
11. List out the employee id, last name in ascending order based on the employee id.
Select employee_id, last_name from employee order by employee_id
12. List out the employee id, name in descending order based on salary column
Select employee_id, last_name, salary from employee order by salary desc
Conclusion: Thus we have studied to use & implement various DML queries.
1. Explain DML.
Assignment No. 3
SQL Queries – all types of Join, Sub-Query and
Title View:
Design at least 10 SQL queries for suitable database
application using SQL DML statements: all types of
Join,
Sub-Query and View.
Roll No.
Class T.E. (C.E.)
Date
Subject Database Management System Laboratory
Signature
Assignment No: 3
Title :- Design at least 10 SQL queries for suitable database application using
SQL DML statements: all types of Join, Sub-Query and View.
Objectives :- To study all types of Join, Sub-Query and View SQL statements.
1) Inner
2) Outer(left, right,full)
3) Cross
1) Inner join :
- Also known as equi join.
- Statements generally compares two columns from two columns with the equivalence
operator =.
- This type of join can be used in situations where selecting only those rows that have
values in common in the columns specified in the ON clause, is required.
• Syntax :
(ANSI style)
Emp(empno,fname,lname,dept,desig,branchno) Branch(bname,branchno)
Select e.empno,e.fname,e.lname,e.dept, b.bname, e.desig from emp e inner join branch
b on b.branchno=e.branchno;
Select e.empno, e.fname, e.lname, e.dept, b.bname, e.desig from emp e, branch b on where
b.branchno=e.branchno;
Eg. List the customers along with the account details associated with them.
Customer(custno,fname,lname)
Acc_cust_dtls(fdno,custno)
Acc_mstr(accno,branchno,curbal) Branch_mstr(name,branchno)
Outer joins are similar to inner joins, but give a little bit more flexibility when selecting data
from related tables. This type of joins can be used in situations where it is desired, to select
all rows from thetable on left( or right, or both) regardless of whether the other table has
values in common & ( usually) enter NULL where data is missing. Tables
Emp_mstr(empno,fname,lna
me,det)
Cntc_dtls(codeno,cntc_type,c
ntc_ data)
Select e.empno, e.fname, e.lname, e.dept, c.cntc_type, c.cntc_data from emp_mstr e left join
cntc_dtls c on e.empno=c.codeno;
• Select e.empno, e.fname, e.lname, e.dept, c.cntc_type, c.cntc_data from
emp_mstr e cntc_dtls c where e.empno=c.codeno(+);
All the employee details have to be listed even though their corresponding contact
information is not present. This indicates all the rows from the first table will be displayed
even though there exists no matching rows in the second table.
A cross join returns what known as a Cartesian Product. This means that the join
combines every row from the left table with every row in the right table. As can be
imagined, sometimes
join can be used in situation where it is desired, to select all possible combinations of
rows & columns from both tables. The kind of join is usually not preferred as it may
run for a very long time & produce a huge result set that may not be useful.
• Create a report using cross join that will display the maturity amounts for predefined
deposits,based on min & max period fixed/ time deposit.
• Tables Tem_fd_amt(fd_amt) Fd_mstr(minprd,maxprd,intre)
• Select fd_amt, s.minprd, s.maxprd, s.intrate,round (t.fd_amt+(s.intrate/100 ) *
(s.minprd/365)
)) “amount_min_period”,round(t.fd_amt+(s.intrate/100)*(s.maxprd/365)))
“amount_max_period” from fd_mstr s cross join tem_fd_amt t;
• Select t.fd_amt, s.minprd, s.maxprd, s.intrate, round(t.fd_amt+(s.intrate/100) *
(s.minprd/365))) “amount_min_period”,
round(t.fd_amt+(s.intrate/100)*(s.maxprd/365))) “amount_max_period”
from fd_mstr s, tem_fd_amt t;
Self join
- Emp_mgr(empno,fname, lname,mgrno)
• Select e.empno,e.fname,e.lname, m.fname “manager” from emp_mgr e, emp_mgr m
wheree.mgrno=m.empno;
Views
Queries are the principle means of extracting information from data streams and relations. A
view represents an alternative selection on a stream or relation that you can use to create
subqueries.
A view is only accessible by the queries that reside in the same processor and cannot be
exposed beyond that boundary.
Syntax :
Purpose
Use view statement to create a view over a base stream or relation that you reference by
identifier in subsequent Oracle CQL statements.
Syntax
schema: Optionally, specify the schema of the view as a space delimited list of attribute
names.
Oracle CEP server infers the types.
Examples
]]></view>
<view id="MAXBIDMINASK" schema="cusip bidseq bidSrcId bid askseq askSrcId ask bidQty
askQty"><![CDATA[
select bid.cusip, bid.seq, bid.srcId as bidSrcId, bid.bid, ask.seq, ask.srcId as askSrcId, ask.ask,
bid.bidQty, ask.askQty
from BIDMAX as bid, ASKMIN as ask
where bid.cusip = ask.cusip
]]></view>
<query id="BBAQuery"><![CDATA[
ISTREAM(select bba.cusip, bba.bidseq, bba.bidSrcId, bba.bid, bba.askseq, bba.askSrcId, bba.ask,
bba.bidQty, bba.askQty, "BBAStrategy" as intermediateStrategy, p.seq as correlationId, 1 as priority
from MAXBIDMINASK as bba, filteredStream[rows 1] as p where bba.cusip = p.cusip)
Using this technique, you can achieve the same results as in the subquery case. However, using views
you can better control the complexity of queries and reuse views by name in other queries.
database system to access data. The business logic of the application, which says what actions to carry
out under what conditions, is embedded in the application server, instead of being distributed across
multiple clients. Three-tier applications are more appropriate for large applications, and for
applications that run on the World Wide We
Three-tier architecture allows any one of the three tiers to be upgraded or replaced
independently. The user interface is implemented on a desktop PC and uses a standard
graphical user interface with different modules running on the application server. The
relational database management system on thedatabase server contains the computer data
storage logic. The middle tiers are usually multitiered.
The three tiers in a three-tier architecture are:
1. Presentation Tier: Occupies the top level and displays information related to
services available on a website. This tier communicates with other tiers by
sending results to the browser and other tiers in the network.
2. Application Tier: Also called the middle tier, logic tier, business logic or logic
tier, this tier is pulled from the presentation tier. It controls application
functionality by performing detailed processing.
3. Data Tier: Houses database servers where information is stored and retrieved.
Data in this tier iskept independent of application servers or business logic.
Employee ( Eno, Ename, Deptno, Salary ) Eno=pk,
Deptno=fk Department ( Deptno, Dname )
Deptno=pk
Implement all join operation –cross join, natural join ,equi join, left outer ,right outer join etc
&
Write
SQL Queries for following questions
i) List of employee names of 'Computer' department.
ii) Find the Employee who‟sSalary above 50000 of each department.
iii) Find department name of employee name 'Amit'.
Conclusion: Thus we have studied to use & implement various join operation with nested
Querie
FAQ:
Assignment No. 4
Unnamed PL/SQL code block: Use of Control
Title structure and Exception handling is mandatory.
Roll No.
Class T.E. (C.E.)
Date
Subject Database Management System Laboratory
Signature
Assignment No: 4
Title:- Unnamed PL/SQL code block: Use of Control structure and Exception handling
is mandatory. Write a PL/SQL block of code for the following requirements:-
Schema :
1. Borrower(Rollin, Name, DateofIssue, NameofBook, Status)
2. Fine(Roll_no,Date,Amt)
Accept roll_no & name of book from user.
Check the number of days (from date of issue), if days are between 15 to 30 then fine
amount will be Rs 5per day.
If no. of days>30, per day fine will be Rs 50 per day & for days less than 30, Rs. 5 per day.
After submitting the book, status will change from I to R.
If condition of fine is true, then details will be stored into fine table.
Frame the problem statement for writing PL/SQL block inline with
above statement. Objective:- Learn the concept of PL/SQL
Theory:
Introduction :-PL/SQL
PL/SQL allows users and designers to develop complex database applications that require the
usage ofcontrol structures and procedural elements such as procedures, functions, and
modules
The basic construct in PL/SQL is a block. Blocks allow designers to combine logically related
(SQL-) statements into units. In a block, constants and variables can be declared, and variables
can be used to store query results. Statements in a PL/SQL block include SQL statements,
control structures (loops), condition statements (if-then-else), exception handling, and calls of
other PL/SQL blocks.
PL/SQL blocks that specify procedures and functions can be grouped into packages. A
package
is similar to a module and has an interface and an implementation part. Oracle o ffers
several predefined packages, for example, input/output routines, file handling, job
scheduling etc. (see directory
$ORACLE HOME/rdbms/admin).
Another important feature of PL/SQL is that it o ffers a mechanism to process query results
in a tuple-
oriented way, that is, one tuple at a time. For this, cursors are used. A cursor basically is a
pointer
to a
query result and is used to read attribute values of selected tuples into variables. A cursor
typically is used in combination with a loop construct such that each tuple read by the cursor
can be processed individually.
Advantages of PL/SQL:-
Following are some advantages of Pl/SQL
1) Support for SQL :-PL/SQL is the procedural language extension to SQL supports
all thefunctionalities of SQL.
2) Improved performance:- In SQL every statement individually goes to the ORACLE
server, get processed and then execute. But in PL/SQL an entire block of statements can be
sent to ORACLE server at one time, where SQL statements are processed one at
atime.PL/SQL block statements drastically reduce communication between the application
and ORACLE. This helps in improving theperformance.
3) Higher Productivity:- Users use procedural features to build applications.PL/SQL code is
written in the form of PL/SQL block.PL/SQL blocks can also used in other ORACLE Forms,
ORACLE reports. This code reusability increases the programmers productivity.
4) Portability :- Applications written in PL/SQL are portable. We can port them from
one environment to any computer hardware and operating system environment
running ORACLE.
5) Integration with ORACLE :-Both PL/SQL and ORACLE are SQL based.PL/SQL variables have
data types native to the oracle RDBMS dictionary. This gives tight integration with ORACLE.
Features of PL/SQL:-
The basic unit of code in any PL/SQL program is a block. All PL/SQL programs are
composed ofblocks. These blocks can be written sequentially.
DECLARE
Declaratio
n section BEGIN
Executabl
e section
EXCEPTION
Exception handling section
END;
Where
1) Declaration section
PL/SQL variables, types, cursors, and local subprograms are defined here.
2) Executable section
Procedural and SQL statements are written here. This is the main section of the block.
This section is required.
3) Exception handling
4) Section Error handling code is written here
Conditional statements check the validity of a condition and accordingly execute a set
of statements. The conditional statements supported by Pl/SQL is
1) IF..THEN
2) IF..THEN..ELSE
3) IF..THEN..ELSIF
1) IF..THN
Syntax1:-
If condition
THEN
Statement
list END IF;
2) IF..THEN..ELSE
Syntax 2:-
IF condition THEN
Statement list
ELSE
Statements
END IF;
3) IF..THEN..ELSIF
Syntax 3:-
If condition THEN
Stateme
nt list ELSIF
condition THEN
Statement list
ELSE
Statement list
END IF; END IF;
CASE
WHEN <expression> THEN
<statements>; WHEN
<expression> THEN
<statements>;
.
ELSE
<stat
emen
ts>;
END
CASE;
Here expression in WHEN clause is evaluated sequentially. When result of expression is TRUE,
then corresponding set of statements are executed and program flow goes to END CASE.
The LOOP does not facilitate a checking for a condition and so it is an endless
loop. To end theiterations, the EXIT statement can be used.
LOOP
<statement list>
IF
condition
THEN EXIT;
END IF;
END LOOP;
The statements here is executable statements,which will be executed repeatedly until the
condition given if IF..THEN evaluates TRUE.
The WHILE…LOOP is a condition driven construct i.e the condition is a part of the loop
construct and
The condition is evaluated before each iteration of loop. If it evaluates to TRUE, sequence
of statements are executed. If the condition is evaluated to FALSE or NULL, the loop is
finished and the control resumes after the END LOOP statement.
3) THE FOR LOOP :The number of iterations for LOOP and WHILE LOOP is not known in
advance. THE number of iterations depends on the loop condition. The FOR LOOP can
be used to have a definite numbers of iterations.
The syntax
is:-
1) Predefined exceptions
2) User defined exceptions
1) Predefined exceptions:- Predefined exceptions are the error condition that are defined by
ORACLE. Predefined exceptions cannot be changed. Predefined exceptions correspond to
common SQL errors. The predefined exceptions are raised automatically whenever a PL/SQL
program violates an ORACLE rule.
Syntax :
DECLARE
<Exception Name>
EXCEPTION; BEGIN
….
RAISE <Exception Name>
…
EXCEPTION
WHEN <Exception name> THEN
<Action>
END;
Exception Handling
A PL/SQL block may contain statements that specify exception handling routines. Each
error or warning during the execution of a PL/SQL block raises an exception. One can
distinguish between two types of exceptions
System defined exceptions
• User defined exceptions (which must be declared by the user in the declaration part
of a block where the exception is used/implemented)
Syntax:-
<Exception_name>Exception;
Handling Exceptions:- Exceptions handlers for all the exceptions are written in the
exception handling section of a PL/SQL block.
Syntax:-
Exception
When exception_name then
Sequence_of_statements1;
When exception_name then
Sequence_of_statements2;
When exception_name then
Sequence_of_statements3;
End;
Example:
Declare
emp sal
EMP.SAL%TYPE; emp
no
EMP.EMPNO%TYPE;
too_high_sal exception;
begin
exception
when NO DATA FOUND – – no tuple
selec
tedthen rollback;
when too_high_sal then insert into high sal emps
values(emp no); commit;
end;
After the keyword when a list of exception names connected with or can be specified. The
last whenclause in the exception part may contain the exception name others. This
introduces the default exception handling routine, for example, a rollback.
If a PL/SQL program is executed from the SQL*Plus shell, exception handling routines may contain
statements that display error or warning messages on the screen. For this, the procedure raise
application error can be used. This procedure has two parameters <error number> and <message
text>.
<error number> is a negative integer defined by the user and must range between -20000
and -20999.
select EMPNO, SAL into emp no, emp sal from EMP
where ENAME = ‟KING‟;
if emp sal ∗1.05 > 4000 then raise too high sal
else update EMP set SQL . . . end if
Example:
Conclusion: Thus we have studied how to use control structure and exception handling.
Lab Exercise
1) Write a PL/SQL block to calculate factorial. Use Exception Handling.
2) Write a PL/SQL block to find prime number for first 30 numbers.
3) Write a PL/SQL block to find Fibonacci series for first 50 numbers.
4) Write a PL/SQL block to find a raised to power b i.e. a b
5) Write a PL/SQL block to find the grade of a student. Enter marks for 5 subjects.
6) Write a PL/SQL block to update the table. Table: ACCT_MSTR ==>ACCT_NO CURBAL
SB1 500
7) Write on your own one PL/SQL block for the problem statement. SB5 500
SB9 500
SB13 500
FAQ :
1) What is PL/SQL? Explain.
2) What is the difference between "SQL" and "PL/SQL"?
3) What are the different Goals of PL/SQL?
4) What are exceptions? What are the different types of exceptions?
5) What are the different conditional statements used in PL/SQL?
6) What are the different iterative construct used in PL/SQL? Explain in short.
7) What are the features of PL/SQL? Explain.
8) What are the advantages of PL/SQL? Explain
9) How will you stop an infinite loop without closing the program?
10) Why PL/SQL does not support retrieving multiple records?
Assignment No. 5
Write a PL/SQL code block to calculate the area of
Title a circle for a value of radius varying from 5
to 9. Store the radius and the corresponding values
of calculated area in an empty table named
areas, consisting of two columns, radius and area.
Roll No.
Class T.E. (C.E.)
Date
Signature
Assignment No: 5
Title: Write a PL/SQL code block to calculate the area of a circle for a value of radius
varying from 5to 9. Store the radius and the corresponding values of calculated area in an empty
table named areas, consisting of two columns, radius and area.
Declare
r number(5);
area number(14,2);
begin
r:=5;
while r<=9
loop
area:=pi*power(r,2);
r:=r+1;
end loop;
end;
Conclusion : Thus we have studied how to calculate area of circle using PLSQL
Lab Exercise :
1. Write a PL/SQL code block to calculate the area of a circle for a value of radius varying from 6
to 10. Store the radius and the corresponding values of calculated area in an empty table named
areas, consisting of two columns, radius and area.
2. Write a PL/SQL code block to calculate the area of a circle for a value of radius varying from 10
to 15. Store the radius and the corresponding values of calculated area in an empty table named
areas, consisting of two columns, radius and area.
3. Write a PL/SQL code block to calculate the area of a circle for a value of radius varying from 4
to 9. Store the radius and the corresponding values of calculated area in an empty table named
areas, consisting of two columns, radius and area.
4. Write a PL/SQL code block to calculate the area of a circle for a value of radius varying from 5
to 9. Store the radius and the corresponding values of calculated area in an empty table named
areas, consisting of two columns, radius and area.
Assignment No. 6
Signature
Assignment No: 6
Title :- PL/SQL Stored Procedure and Stored Function Write a Stored Procedure
namely proc_Grade for the categorization of student. If marks scored by students in
examination is <=1500 and marks>=990 then student will be placed in distinction
category if marks scored are between 989 and900 category is first class, if marks 899
and 825 category is Higher Second Class. Write a PL/SQL block for using procedure
created with above requirement. Stud_Marks(name, total_marks) Result(Roll,Name,
Class).
IS/AS
Procedure_body :
Where
Procedure_name: – is the name of the procedure to be created Argument:- is the name
of the procedure
parameter
Type:- Is the data type of the associated parameter
Procedure_body:-Is a PL/SQL block that makes up the code of the procedure.
IN:-This is default mode. The value of the actual parameter is passed into the procedure. Inside
the procedure the formal parameter is considered read only.
OUT:-Any value the actual parameter has when the procedure is called ignored. Inside the
procedure ,the formal parameters are considered as write only.
IN OUT:-this mode is combination of IN and OUT
FUNCTION:-
A function is a subprogram, which is used to compute values. It is similar to a procedure,
function also takes arguments and can be in different modes. Function also can be stored in
the database. It is a PL/SQL block consisting of declarative, executable and exception section.
Difference between procedure and function is that the procedure call is a PL/SQL
statement by itself, while a function call is called as a part of an expression.
A function can return more than one value using OUT parameter. A function can be called
using positional or named notation.
Syntax for creating a function:-
Create [or replace] FUNCTION
function_name [(argument1 [IN /
OUT / IN OUT] type), (argument2
[IN / OUT / IN OUT] type),
….]
Return return_type IS / AS
Where
Function_body
Function_name: – is the name of the function to be created Argument: - is the name of the
function parameter
Type:- Is the data type of the associated parameter
Function_body:-Is a PL/SQL block containing code for the function.
IN:-This is default mode. The value of the actual parameter is passed into the procedure.
Insidethe procedure the formal parameter is considered read only.
OUT:-Any value the actual parameter has when the procedure is called ignored. Inside the
procedure ,the formal parameters are considered as write only.
INOUT:-this mode is combination of IN and OUT
Package Body:
The package body is separate data dictionary object from the package header. It cannot be
successfully compiled unless the package header has already been successfully compiled.
Syntax:
CREATE OR REPLACE PACKAGE BODY package_name
ASProcedure definition;
Function definition;
…….
End package_name
To drop the package(both specification & the body) use the drop package command as
follows:
Syntax :
Conclusion: Thus we have studied how to calculated students marks using stored
procedure method.
Lab Exercise
1) Write a procedure on EMP table. It should increase commission of an employee.
Employeenumber and commission are passed as parameters to the called
procedure.
2) Write a function that returns the number of employees working in a department. Pass
departmentnumber as an input to the function.
3) Create table classes with the following fields
(Deptno, course, cur_student, max_student) Insert 4 or 5 records and
Write a function which returns true if the specified class is 80 percent full or more, and
false otherwise.
Write a PL/SQL block to call this function and use cursor in PL/SQL block to holdthe
records of all department.
4) Write a procedure to update records of classes table and write a PL/SQL block to
call thatprocedure.
5) Create a package which consist of procedures for insert ,delete and update the data of
classestable.
FAQ :
1) Explain the term procedure and function of PL/SQL in short.
2) What is the difference between "procedure" and "function"?
3) What is the difference between "%type" and "%rowtype"?
4) What is package? Explain.
5) What is the use of package?
6) What are the different modes of argument passing?
7) What is difference between IN & IN OUT?
8) Write a package which consists of cursor, trigger, procedure & function.
9) What are the advantages of procedure & function?
10) Write the syntax to drop function, procedure & package/
Assignment No. 7
Signature
Assignment No: 7
Title :- Cursors: (All types: Implicit, Explicit, Cursor FOR Loop, Parameterized Cursor)
Write a PL/SQL block of code using parameterized Cursor, that will merge the data
available in the newly created table Cust_New with the data available in the table
Cust_Old. If the data in the first table already exist in the second table then that data
should be skipped.
PL/SQL Cursor :
When an SQL statement is processed, Oracle creates a memory area known as context area.
A cursor is a pointer to this context area. It contains all information needed for processing
the statement. In PL/SQL, the context area is controlled by Cursor. A cursor contains
information
A cursor is used to referred to a program to fetch and process the rows returned by the SQL
o Implicit Cursors
o Explicit Cursors
The implicit cursors are automatically generated by Oracle while an SQL statement is executed,
if you don't use an explicit cursor for the statement. These are created by default to process the
statements when DML statements like INSERT, UPDATE, DELETE etc. are executed.Orcale
provides some attributes known as Implicit cursor's attributes to check the status of DML
operations. Some of them are: %FOUND, %NOTFOUND, %ROWCOUNT and %ISOPEN.
For example: When you execute the SQL statements like INSERT, UPDATE, DELETE then the
cursor attributes tell whether any rows are affected and how many have been affected. If you
run a SELECT INTO statement in PL/SQL block, the implicit cursor attribute can be used to find
out whether any row has been returned by the SELECT statement. It will return an error if there
no data is selected.The following table soecifies the status of the cursor with each of its
attribute.
Attribute Description
%FOUND Its return value is TRUE if DML statements like INSERT, DELETE
and UPDATE affect at least one row or more rows or a SELECT
INTO statement returned one or more rows. Otherwise it
returns FALSE.
%NOTFOUND Its return value is TRUE if DML statements like INSERT, DELETE
and UPDATE affect no row, or a SELECT INTO statement return
no rows. Otherwise it returns FALSE. It is a just opposite of
%FOUND.
%ISOPEN It always returns FALSE for implicit cursors, because the SQL
cursor is automatically closed after executing its associated
SQL statements.
Let's execute the following program to update the table and increase salary of each customer
by 5000. Here, SQL%ROWCOUNT attribute is used to determine the number of rows affected:
Create procedure:
DECLARE
total_rows number(2);
BEGIN
UPDATE customers SET salary = salary + 5000;
IF sql%notfound THEN
dbms_output.put_line('no customers updated');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers updated ');
END IF;
END;
/
Output:
6 customers updated
PL/SQL procedure successfully completed.
Now, if you check the records in customer table, you will find that the rows are updated.
The Explicit cursors are defined by the programmers to gain more control over the context
area.
These cursors 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.
Steps:`
You must follow these steps while working with an explicit cursor.
It defines the cursor with a name and the associated SELECT statement.
CURSOR name IS
SELECT statement;
It is used to allocate memory for the cursor and make it easy to fetch the rows returned by the
OPEN cursor_name;
It is used to access one row at a time. You can fetch rows from the above-opened cursor as
follows:
It is used to release the allocated memory. The following syntax is used to close the above-
opened cursors.
Close cursor_name;
Explicit cursors are defined by programmers to gain more control over the context area. It is
defined
in the declaration section of the PL/SQL block. It is created on a SELECT statement which
returns more than one row.
Let's take an example to demonstrate the use of explicit cursor. In this example, we are using
the already created CUSTOMERS table.
Create procedure:
Execute the following program to retrieve the customer name and address.
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;
/
Output:
1 Ramesh Allahabad
2 Suresh Kanpur
3 Mahesh Ghaziabad
4 Chandan Noida
5 Alex Paris
6 Sunita Delhi
Even if your query returns only a single row, you might still decide to use an explicit cursor.
Theimplicit cursor has the following drawbacks:
An explicit cursor is, at least theoretically, more efficient than an implicit cursor. An implicit
cursor executes as a SQL statement and Oracle's SQL is ANSI-standard. ANSI dictates that a
single-row query must not only fetch the first record, but must also perform a second fetch
to determine if too many rows will be returned by that query (such a situation will RAISE the
TOO_MANY_ROWS PL/SQL exception). Thus, an implicit query always performs a minimum of
two fetches, while an explicit cursor only needs to perform a single fetch.
This additional fetch is usually not noticeable, and you shouldn't be neurotic about
using an implicitcursor for a single-row query (it takes less coding, so the
temptation is always there). Look out for indiscriminate use of the implicit cursor in
the parts of your application where that cursor will be executed repeatedly. A good
example is the Post-Query trigger in the Oracle Forms.
Post-Query fires once for each record retrieved by the query (created from the base
table block and the criteria entered by the user). If a query retrieves ten rows, then an
additional ten fetches are needed with an implicit query. If you have 25 users on your
system all performing a similar query, your server must process 250 additional
(unnecessary) fetches against the database. So, while it might be easier to write an
implicit query, there are some places in your code where you will want to make that
extra effort and go with the explicit cursor.
If an implicit SELECT statement returns more than one row, it raises the
TOO_MANY_ROWS exception. When this happens, execution in the current block terminates
and control is passed to theexception section. Unless you deliberately plan to handle this
scenario, use of the implicit cursor is a declaration of faith. You are saying, "I trust that query
to always return a single row!"
It may well be that today, with the current data, the query will only return a single row.
If the nature ofthe data ever changes, however, you may find that the SELECT
statement which formerly identified a single row now returns several. Your program will
raise an exception.
Conclusion: Thus we have studied how to use the concept of cursor in PL/SQL
Lab Exercise
1) Create table with name student having the field rollno, first name, last name
& branch. Insert 10 records into table. Write a PL/SQL to create a cursor to hold
all the record of student table having branch „Computer Science‟. Display all
the records.
2) Write a PL/SQL block to update the record of rollno =100 & set the branch to E
and TC’, if it is not present then insert the record into the student table with the
id=100; (use implicit cursor sql%notfound).
3) Write a cursor and use it to raise the employee salaries as follows:
i) All employees of department 20 get 5% raise
ii) All employees of department 30 get 10% raise
iii) Rest of employees get
7.5% raiseUse separate
cursor.
FAQ :
1) What is cursor?
2) What are the different types of cursors?
3) What are the different attributes of explicit cursor? Explain in brief.
4) What is implicit cursor?
5) Explain the FOR loop of Cursor.
6) What is difference between simple loop, while loop & for loop?
7) What is difference between Implicit & Explicit Cursor?
8) Explain FOR UPDATE cursor with an example.
9) What is CURRENT OF clause in cursor? Give an example.
10) List all predefined cursor
Assignment No. 8
Roll No.
Class T.E. (C.E.)
Date
Subject Database Management System Laboratory
Signature
Assignment No: 8
Title :- Database Trigger (All Types: Row level and Statement level triggers, Before
and After Triggers). Write a database trigger on Library table. The System should
keep track of the records that are being updated or deleted. The old value of
updated or deleted records should be added in Library_Audit table.
Frame the problem statement for writing Database Triggers of all types, in-
line with above statement. The problem statement should clearly state the
requirements.
Trigger types
There are two types of triggers
1. Statement Trigger:-A statement trigger is a trigger in which the trigger action is
executed once for the manipulation operation that fires the trigger.
2. Row Trigger:-A row trigger is a trigger in which the trigger action is performed
repeatedly for each row of the table that is affected by the manipulation operation that
fires the trigger.
Triggering time :
Triggers can specify the time of trigger action.
1) Before the triggering event
The trigger action is performed before the operation that fires the trigger is executed.
This trigger isused when execution of operation depends on trigger action.
2) After the triggering event
The trigger action is performed after the operation that fires the trigger is executed. This
trigger is used when triggering action depends on the execution of operation. Triggering
Events
Triggering events are the DML operations.
These operations are insert, update and delete When these operations are performed on a
table, the trigger which is associated with the operation is fired.
Triggering events divide triggers into three types.
1) DELETE TRIGGER
2) UPDATE TRIGGER 3) INSERT TRIGGER
General syntax for creation of Trigger
Create [or replace] TRIGGER <trigger_name>
<BEFORE | AFTER>
DELETE | [OR] INSERT | [OR] UPDATE[OF <column1>[,<column2>…..]
ON <table_name>
[for each row[when <condition>] Begin
……… ………
………
……….
End;
Where
Trigger_name:-trigger name is the name of the trigger. Table_name :-is thye table name
for which ger is defined.Trigger-condition:-The trigger condition in the when clause,if
present is evaluates
The bodyof the trigger is executed only when this condition evaluates to true.
Dropping trigger
Suppose you want to drop trigger then the syntax is
Syntax:-
Alter TRIGGER trigger name (DISABLE/ENABLE) all triggers;
Lab Exercise :-
FAQ :
Assignment No. 9
Title
Database Connectivity:
Write a program to implement MySQL/Oracle database
connectivity with any front end
language to implement Database navigation operations (add,
delete, edit etc.)
Roll No.
Class T.E. (C.E.)
Date
Subject Database Management System Laboratory
Signature
Assignment No: 9
In this experiment we are going to learn how to do basic database operations using JDBC (Java
Database Connectivity) API. These basic operations are INSERT, SELECT, UPDATE and DELETE
statements in SQL language. Although the target database system is Oracle
Database, but the same techniques can be applied to other database systems as well
because of the query syntax used is standard SQL is generally supported by all relational database
systems.
Prerequisites :
JDK
Oracle Database
JDBC driver for Oracle Database You
need to add ojdbc6.jar to project library.
Open oracle using cmd. For that type sqlplus in cmd and press Enter.
Create a user-id protected by a password. This user-id is called child user.
create user identified by ;
Grant required permissions to child user. For simplicity we grant database administrator privilege
to child user. conn / as sys dba; grant dba to ;
Class.forName() : Here we load the driver’s class file into memory at the runtime. No
need of using new or creation of object.
Class. For Name("oracle. jdbc. driver. Oracle Driver");
DriverManager: This class is used to register driver for a specific database type (e.g. Oracle
Database in this tutorial) and to establish a database connection with the server via
its getConnection() method.
from which we can create statements to execute queries and retrieve results, get
metadata about the database, close connection, etc. ection con =
DriverManager.getConnection@localhost:1521:orcl", "login1", "pwd1");
Statement and PreparedStatement: These interfaces are used to execute static SQL
query and parameterized SQL query, respectively. Statement is the super interface of
the PreparedStatement interface. Their commonly used methods are:
boolean execute(String sql): executes a general SQL statement. It returns true if
the query returns a ResultSet, false if the query returns an update count or returns
nothing. This method can be used with a Statement only.
int executeUpdate(String sql): executes an INSERT, UPDATE or DELETE statement and
returns an update account indicating number of rows affected (e.g. 1 row inserted, or 2 rows
updated, or 0 rows affected). (
q1);
ResultSet executeQuery(String sql): executes a SELECT statement and returns a ResultSet
object which contains results returned by the query.
ResultSet: contains table data returned by a SELECT query. Use this object to iterate
over rows in the result set using next() method.
Java
import java.sql.*;
try
Class.forName("oracle.jdbc.driver.OracleDriver");
// Establishing Connection
if (con != null)
System.out.println("Connected");
else
System.out.println("Not Connected");
con.close();
catch(Exception e)
System.out.println(e);
ed
Note: Here oracle in database URL in getConnection() method specifies SID of Oracle
Database. For Oracle database 11g it is orcl and for oracle database 10g it is xe.
Java
import java.sql.*;
String id = "id1";
try
Class.forName("oracle.jdbc.driver.OracleDriver");
int x = stmt.executeUpdate(q1);
if (x > 0)
System.out.println("Successfully Inserted");
else
System.out.println("Insert Failed")
con.close();
catch(Exception e)
System.out.println(e);
Java
import java.sql.*;
String id = "id1";
try
// Updating database
"' WHERE id = '" +id+ "' AND pwd = '" + pwd + "'";
int x = stmt.executeUpdate(q1);
if (x > 0)
else
con.close();
catch(Exception e)
System.out.println(e);
Java
import java.sql.*;
String id = "id2";
try
if (x > 0)
else
con.close();
catch(Exception e)
System.out.println(e);
Java
import java.sql.*;
String id = "id1";
try
Class.forName("oracle.jdbc.driver.OracleDriver");
// SELECT query
String q1 = "select * from userid WHERE id = '" + id + "' AND pwd = '" + pwd +
if (rs.next())
Else
con.close();
catch(Exception e)
System.out.println(e);
} }}
Output:
User-id- id1
Full Name -geeks for geeks
E-mail –[email protected]
GROUP B
NoSQL Databases
Assignment No. 1
Roll No.
Class T.E. (C.E.)
Date
Subject Database Management System Laboratory
Signature
Assignment No. 1
Theory :
Difference between SQL and NOSQL
NOSQL
Motivations for this approach include: simplicity of design, simpler "horizontal" scaling to
clusters of machines (which is a problem for relational databases), [2] and finer control over
availability. The data structures used by NoSQL databases (e.g. key-value, wide column, graph,
or document) are different from those used by default in relational databases, making some
operations faster in NoSQL. The particular suitability of a given NoSQL database depends on
the problem it must solve. Sometimes the data structures used by NoSQL databases are also
viewed as "more flexible" than relational database tables.
Many NoSQL stores compromise consistency (in the sense of the CAP theorem) in favor of
availability, partition tolerance, and speed. Barriers to the greater adoption of NoSQL stores
include the use of low- level query languages (instead of SQL, for instance the lack of ability
to perform ad-hoc joins across tables), lack of standardized interfaces, and huge previous
investments in existing relational databases. Most NoSQL stores lack true ACID transactions,
although a few databases, such as MarkLogic, Aerospike, FairCom c-treeACE, Google Spanner
(though technically a NewSQL database), Symas LMDB, and OrientDB have made them
central to their designs. (See ACID and join support.)
MongoDB
MongoDB is a cross-platform, document oriented database that provides, high
performance, high availability, and easy scalability. MongoDB works on concept of collection
and document.Database
Database is a physical container for collections. Each database gets its own set of files
on the filesystem. A single MongoDB server typically has multiple databases.
Collection
Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A
collection exists within a single database. Collections do not enforce a schema. Documents
within a collection can have different fields. Typically, all documents in a collection are of
similar or related purpose.
Document
A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema
means that documents in the same collection do not need to have the same set of fields or
structure, and common fields in a collection's documents may hold different types of data.
Sample Document
Following example shows the document structure of a blog site, which is
simply a comma separated key value pair.
{
_id: ObjectId(7df78ad8902c) title: 'MongoDB Overview',
description: 'MongoDB is no sql database', by: 'tutorials point',
url:'http://www.tutorialspoi
nt.com',
MongoDB ─ Advantages:
Any relational database has a typical schema design that shows number of tables and
the relationship between these tables. While in MongoDB, there is no concept of
relationship.
different documents. Number of fields, content and size of the document can differ from one
document to another.
Structure of a single object is clear..0
No complex joins.
Deep query -ability.
MongoDB Help
To get a list of commands, type db.help() in MongoDB client. This will give you a list of
commands as shown in the following screenshot.
>show dbs
local
0.78125
GBtest
0.23012
GB
Your created database (mydb) is not present in list. To display database, you need to insert at
least onedocument into it.
>db.movie.insert({"name":"tutorials point"})
In MongoDB default database is test. If you didn't create any database, then collections will
be stored in test database.
The dropDatabase() Method
MongoDB db.dropDatabase() command is used to drop a existing database.
Syntax
db.dropDatabase()
The createCollection() Method
MongoDB db.createCollection(name, options) is used to create collection.
Syntax : db.createCollection(name, options)
In the command, name is name of collection to be created. Options is a document and is used
to specify configuration of collection.
Integer: This type is used to store a numerical value. Integer can be 32 bit or 64 bit
depending upon
your server.
Boolean : This type is used to store a boolean (true/ false) value.
>db.COLLECTION_NAME.insert(document)
MongoDB ─ Query Document
Syntax
>db.mycol.find().pretty()
Apart from find() method, there is findOne() method, that returns only one document.
RDBMS Where Clause Equivalents in MongoDB
To query the document on the basis of some condition, you can use following operation
Logical operators
AND in MongoDB
Syntax
In the find() method, if you pass multiple keys by separating them by ','
then MongoDBtreats it as AND condition. Following is the basic syntax
of AND −
>db.mycol.find({key1:value1, key2:value2}).pretty()
OR in MongoDB
Syntax
The following example will show the documents that have likes greater than 100 and whose
title is either 'MongoDB Overview' or by is 'tutorials point'. Equivalent SQL where clause is
'where
likes>10 AND (by = 'tutorials point' OR title = 'MongoDB Overview')'
Overview"
}]}).pretty()
{ "_id":
ObjectId(7df78ad8902c)
, "title": "MongoDB
Overview",
"description": "MongoDB is no sql
database", "by": "tutorials point",
"url":
"http://www.tutorialspoint.com",
"tags": ["mongodb", "database",
"NoSQL"], "likes": "100" }
MongoDB's update()
MongoDB's update() and save() methods are used to update document into a
collection. The update() method updates the values in the existing document while the save()
method replaces the existing document with the document passed in save() method.
The update() method updates the values in the existing document. Syntax
The basic syntax of update() method is as follows:
>db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)
The save() method replaces the existing document with the new document passed in the
save() method. Syntax
The basic syntax of MongoDB save() method is −
>db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA}).
>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)
>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)
>db.mycol.remove()
>db.mycol.find()
To limit the records in MongoDB, you need to use limit() method. The method accepts one
number type argument, which is the number of documents that you want to be displayed.
Syntax
The basic syntax of limit() method is as follows:
>db.COLLECTION_NAME.find().limit(NUMBER)
MongoDB Skip() Method
Apart from limit() method, there is one more method skip() which also accepts number type
argument and is used to skip the number of documents.
Syntax
The basic syntax of skip() method is as follows:
db.COLLECTION_NAME.find().limit(NUMBER).skip(N
UMBER)
To sort documents in MongoDB, you need to use sort() method. The method accepts
a document containing a list of fields along with their sorting order. To specify sorting
order 1 and -1 are used. 1 isused for ascending order while -1 is used for descending
order.
Syntax
>db.COLLECTION_NAME.find().sort({KEY:1})
FAQ :
2. If you remove an object attribute, is it deleted from the database? Explain with
example.
4. Define MongoDB.
9. Which method is used to remove the document form the collection? Explain with
example
Assignment No. 2
Design and Develop MongoDB Queries using
Title CRUD operations. (Use CRUD operations,
SAVE method, logical operators)
Roll No.
Class T.E. (C.E.)
Date
Subject Database Management System Laboratory
Signature
Assignment No. 2
Database
Database is a physical container for collections. Each database gets its own set of files on
the file system. A single MongoDB server typically has multiple databases.
Collection
Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A
collection exists within a single database. Collections do not enforce a schema. Documents
within a collection can have different fields. Typically, all documents in a collection are of
similar or related purpose.
Document
A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema
means that documents in the same collection do not need to have the same set of fields or
structure, and common fields in a collection's documents may hold different types of data.
The following table shows the relationship of RDBMS terminology with MongoDB .
CRUD is the basic operation of Mongodb ,it stands CREATE , READ , UPDATE, DELETE.
Options parameter is optional, so you need to specify only the name of the collection.
Following is the list of options you can use:
>use test
switched to db test
>db.createCollection("mycollection")
{ "ok" : 1 }
>
You can check the created collection by using the command show collections.
>show
collecti
ons
mycolle
ction
system.
indexes
>db.COLLECTION_NAME.find()
"_id":
ObjectId(7df78ad8
902c), "title":
"MongoDB
Overview",
"description": "MongoDB is no
sql database", "by": "tutorials
point",
"url":
"http://www.tutorialspoint.co
m", "tags": ["mongodb",
"database",
"NoSQL"], "likes": "100"
}
>
Apart from find() method, there is findOne() method, that returns only one document.
UPDATE
MongoDB's update() and save() methods are used to update document into a collection.
The update() method updates the values in the existing document while the save() method
replaces the existing document with the document passed in save() method.
The update() method updates the values in the existing document. The basic syntax of
update() method is as follows:
>db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)
Example
The save() method replaces the existing document with the new document
passed in the save() method.
The basic syntax of MongoDB save() method is −
>db.COLLECTION_NAME.save({_id:ObjectId(),NEW_D
ATA}) Example
Following example will replace the document with the _id '5983548781331adf45ec7'.
>db.mycol.save(
{
"_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials
Point NewTopic",
"by":"Tutorials Point"
})
>db.mycol.find()
remove() method accepts two parameters. One is deletion criteria and second is justOne flag.
>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)
Example
'MongoDB Overview'.
>db.mycol.remove({'title':'MongoDB Overview'})
>db.mycol.find()
LOGICAL OPERATORS:
Syntax
AND in MongoDB In the find() method, if you pass multiple keys by separating
them by ',' then MongoDB treats it as AND condition. Following is the basic
syntax of AND −
>db.mycol.find({key1:value1, key2:value2}).pretty() Example
Following example will show all the tutorials written by 'tutorials point' and
whose title is 'MongoDB Overview'.
>db.mycol.find({"by":"tutorials point","title": "MongoDB Overview"}).pretty()
For the above given example, equivalent where clause will be ' where by='tutorials point'
AND title = 'MongoDB Overview' '. You can pass any number of key, value pairs in find clause.
OR in MongoDB
Syntax : To query documents based on the OR condition, you need to use $or keyword.
Following is the basic syntax of OR −
>db.mycol.find( { $or: [ {key1: value1}, {key2:value2} ] } ).pretty()
Example will show all the tutorials written by 'tutorials point' or whose title is 'MongoDB
Overview'.
{
"_id":
ObjectId(7df78ad890
2c), "title": "MongoDB
Overview",
"description": "MongoDB is no sql
FAQ:-
Assignment No. 3
Signature
Assignment No. 3
Aim : Implement aggregation and indexing with suitable example using MongoDB.
Aggregations operations process data records and return computed results. Aggregation
operations group values from multiple documents together, and can perform a variety of
operations on the grouped data to return a single result. In SQL count(*) and with group by is
an equivalent of mongodb aggregation.
The aggregate() Method For the aggregation in MongoDB, you should use aggregate()
method. Basic syntax of aggregate() method is as follows:
>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
Example
{
_id:
ObjectId(7df78ad
8902c) title:
'MongoDB
Overview',
description: 'MongoDB is no sql
database', by_user: 'tutorials point',
url: 'http://www.tutorialspoint.com', tags: ['mongodb', 'database', 'NoSQL'], likes: 100
},
{
_id: ObjectId(7df78ad8902d)
_id:
ObjectId(7df78ad8902e) title: 'Neo4j Overview',
description: 'Neo4j is no sql
database', by_user: 'Neo4j',
url: 'http://www.neo4j.com',
"result" : [
},
{
"_id" : "Neo4j","num_tutorial" : 1
}],
"ok" : 1
}>
Sql equivalent query for the above use case will be select by_user, count(*) from
mycol group byby_user Pipeline Concept
In UNIX command, shell pipeline means the possibility to execute an operation on
some input and usethe output as the input for the next command and so on.
MongoDB also supports same concept in aggregation framework. There is a set of
possible stages and each of those is taken as a set of documents as an input and
produces a resulting set of documents (or the final resulting JSON document at the
end of the pipeline). This can then in turn be used for the next stage and so on.
Indexes support the efficient resolution of queries. Without indexes, MongoDB must scan
every document of a collection to select those documents that match the query statement
This scan is highly inefficient and require MongoDB to process a large volume of data.
Indexes are special data structures, that store a small portion of the data set in an easy -to-
traverse form. The index stores the value of a specific field or set of fields, ordered by the
value of the field as specified in the index.
To create an index you need to use ensureIndex() method of MongoDB. The basic syntax
ofensureIndex() method is as follows().
>db.COLLECTION_NAME.ensureIndex({KEY:1})
Here key is the name of the file on which you want to create index and 1 is for ascending
order. To create index in descending order you need to use -1.
Example
>db.mycol.ensureIndex({"title":1})
In ensureIndex() method you can pass multiple fields, to create index on multiple fields.
>db.mycol.ensureIndex({"title":1,"description":-1})
ensureIndex() method also accepts list of options (which are optional). Following is the list:
Conclusion: - Thus we have studied use and implementation of aggregation function &indexing
function.
FAQ : -
Assignment No. 4
Implement Map reduces operation with suitable
Title
example
using MongoDB
Roll No.
Class T.E. (C.E.)
Date
Subject Database Management System Laboratory
Signature
Assignment No. 4
Aim : Implement Map reduces operation with suitable example using Mongo DB
Theory :
As per the Mongo DB documentation, Map Reduce is a data processing paradigm for
condensing large volumes of data into useful aggregated results. Mongo DB uses map
Reduce command for map-reduce operations. Map Reduce is generally used for processing
large data sets.
Map Reduce Command
Following is the syntax of the basic mapReduce command
>db.collection.map Reduce (
function() { emit(key,value); },
//map function function(key,values)
{return reduceFunction},
{ //reduce function
out:
collectio
n, query:
docume
nt, sort:
docume
nt, limit:
number
})
The map-reduce function first queries the collection, then maps the result documents to
emit key-value pairs, which is then reduced based on the keys that have multiple values. In
the above syntax –
map is a javascript function that maps a value with a key and emits a key-value pair
reduce is a javascript function that reduces or groups all the documents having the same key
out specifies the location of the map -reduce query result
query specifies the optional selection criteria for selecting d ocuments
sort specifies the optional sort criteria
limit specifies the optional maximum number of documents to be returned Using
MapReduce Consider the following document structure storing user posts. The document
stores user_name of the user and the status of post.
{"post_text": "tutorialspoint is an awesome website for tutorials" , "user_name":
"mark",
"status":"active" }
We will use a mapReduce function on our posts collection to select all the active posts, group
them on the basis of user_name and then count the number of posts by each user
using the following code
>db.posts.mapReduce(
function() { emit(this.user_id,1); },
{
"result" : "post_total", "timeMillis" : 9,"counts" :
{
"input" : 4,
"emit" : 4,
"reduce" : 2,
"output" : 2
},
"ok" : 1,
}
The result shows that a total of 4 documents matched the query (status:"active"), the map
function emitted 4 documents with key-value pairs and finally the reduce function
To see the result of this mapReduce query, use the find operator –
The above query gives the following result which indicates that
both users tomand mark have two posts in active states −
FAQ : -
4. What are NoSQL databases? What are the different types of NoSQL databases?
Assignment No. 5
Signature
Assignment No. 5
Write a program to implement Mongo DB database connectivity with any front end language
to
implement Database navigation operations(add, delete, edit etc.)
port:
Or:
Or:
After the connection is established, we can obtain a database and make authentication (if the
server is running in secure mode), for example:
1 MongoClient mongoClient = new MongoClient();
2 DB db = mongoClient.getDB("test");
3
4 char[] password = new char[] {'s', 'e', 'c', 'r', 'e', 't'};
5 boolean authenticated = db.authenticate("root", password);
6
7 if (authenticated) {
8 System.out.println("Successfully logged in to MongoDB!");
9 } else {
10 System.out.println("Invalid username/password");
11 }
By default, MongoDB server is running in trusted mode which doesn’t require authentication.
3 import java.net.UnknownHostException;
4 import java.util.List;
5 import java.util.Set
8 import com.mongodb.DB;
9 import com.mongodb.MongoClient;
10
11 public class JavaMongoDBConnection {
12
13 public static void main(String[] args) {
14 try {
15
16 MongoClient mongoClient = new MongoClient("localhost");
17
18 List<String> databases = mongoClient.getDatabaseNames();
19
20 for (String dbName : databases) {
21 System.out.println("- Database: " + dbName);
22
23 DB db = mongoClient.getDB(dbName);
24
25 Set<String> collections = db.getCollectionNames();
26 for (String colName : collections) {
27 System.out.println("\t + Collection: " + colName);
28 }
29 }
30
31 mongoClient.close();
32
33 } catch (UnknownHostException ex) {
34 ex.printStackTrace();
35 }
36
37 }
}
This Java program connects to a MongoDB server running on localhost at default port, then lists all
database names available on the server. For each database, it lists all collection names (a collection is
equivalent to a table in relational database), and finally closes the connection. This program would
produce the following output:
- Database: local
+ Collection: startup_log
- Database: mydb
+ Collection: system.indexes
+ Collection: things
- Database: test
+ Collection: system.indexes
+ Collection: test
mongodb://localhost
mongodb://root:[email protected]:27027
mongodb://db2.server.com/users
mongodb://tom:[email protected]:27027/products
mongodb://db1.server.com,db2.server.com,db3.server.com
Or
package com.mongodb.quickstart;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.bson.Document;
import java.util.ArrayList;
import java.util.List;
As you can see, the MongoDB connection string is retrieved from the System Properties so
we need to set this up. Once you have retrieved your
MongoDB Atlas connection string
, you can add the mongodb.uri system property into your IDE. Here is my configuration
with IntelliJ for example.
IntelliJ Configuration
Or if you prefer to use Maven in command line, here is the equivalent command line you
can run in the root directory:
mvn compile exec:java -Dexec.mainClass="com.mongodb.quickstart.Connection" -
Dmongodb.uri="mongodb+srv://username:password@cluster0-
abcde.mongodb.net/test?w=majority"
Note: Don't forget the double quotes around the MongoDB URI to avoid surprises from your shell.
The standard output should look like this:
Getting Set Up
In the setup part, we created the classes HelloMongoDB and Connection. Now we will work on
the Create class.
If you didn't set up your free cluster on MongoDB Atlas, now is great time to do so. You have all the
instructions in this
blog post
.
Checking the Collection and Data Model
In the sample dataset, you can find the database sample_training, which contains a collection grades.
Each
document in this collection represents a student's grades for a particular class. MongoDB Enterprise
Cluster0-shard-0:PRIMARY> db.grades.findOne({student_id: 0, class_id: 339})
{
"_id" : ObjectId("56d5f7eb604eb380b0d8d8ce"),
"student_id" : 0,
"scores" : [
{
"type" : "exam",
"score" : 78.40446309504266
},
{
"type" : "quiz",
"score" : 73.36224783231339
},
{
"type" : "homework",
"score" : 46.980982486720535
},
{
"type" : "homework",
"score" : 76.67556138656222
}
],
"class_id" : 339
}
{
"_id": {
"$oid": "56d5f7eb604eb380b0d8d8ce"
},
"student_id": {
"$numberDouble": "0"
},
"scores": [{
"type": "exam",
"score": {
"$numberDouble": "78.40446309504266"
}
}, {
"type": "quiz",
"score": {
"$numberDouble": "73.36224783231339"
}
}, {
"type": "homework",
"score": {
"$numberDouble": "46.980982486720535"
}
}, {
"type": "homework",
"score": {
"$numberDouble": "76.67556138656222"
}
}],
"class_id": {
"$numberDouble": "339"
}
}
Here is the JSON representation of a document in the
package com.mongodb.quickstart;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.bson.types.ObjectId;
import java.util.Random;
import static java.util.Arrays.asList;
rand.nextDouble() * 100),
new Document("type", "homework").append("score", rand.nextDouble()
* 100)));
gradesCollection.insertOne(student);
}}}
GROUP C
Mini Project