DBMS Lab Manual1
DBMS Lab Manual1
Lab Manual
Prepared by
Mrs.S.A.Belhe
Mr.G.H.Wani
TE AI&DS
Semester I
Academic Year 2022-23
Vision
To create globally recognized AI&DS Engineers for sustainable
development.
Mission
1. To meet the current & future demands of the nation in the area of
AI&DS.
2. To produce high-quality students technically superior, professionally &
ethically strong.
3. To inculcate the interdisciplinary skillset required to fulfil a societal
need.
Program Education Objectives(PEOs)
1 Conceptual design using ER Model, Online Tool, Smart CO302.2 1,2,3,9 1,2
Reducing ER into tables, normalization Draw
2 Conceptual design using ER Model, Open source operating CO302.2 1,2,3,9 1,2,
Reducing ER into tables, normalization system- Fedora
21. MySQL
3 SQL queries using concepts like all types of Open source operating CO302.2 1,2,3,9 1,2
Join, Sub-Query and View. system- Fedora
To write the SQL queries using concepts like 21. MySQL
all types of Join, Sub-Query and View
4 A PL/SQL block of code (Use of Control Open source operating CO302.2 1,2,3,9 1,2
structure and Exception handling) sys tem- Fedora
To write a PL/SQL block of code using 21. MySQL
Control structure and Exception handling
5 To Write a Named PL/SQL Block for given Oracle 11g CO302.2 1,2,3,9 1,2
requirements using PL/SQLStored
Procedure and Stored Function
6 To write a PL/SQL code block using Cursors Oracle 11g CO302.2 1,2,3,9 1,2
(All types: Implicit, Explicit,Cursor FOR
Loop, Parameterized Cursor)
7 To write a PL/SQL code using Database Oracle 11g CO302.2 1,2,3,9 1,2
Trigger (All Types: Rowlevel and
Statement level triggers, Before and After
Triggers)
8 To Write the MongoDB Queries using CRUD operations. (Use Oracle CO302.2 1,2,3,9 1,2
CRUDoperations, SAVE 11g
method, logical operators etc)
PROBLEM STATEMENT:
All ER Notations
Brief rules to reduce ER diagram into tables
Brief about 1NF, 2NF, 3NF and BCNF
CONCLUSION
Assignment No. 2
TITLE :
SQL queries using Insert, Select, Update, delete with operators, functions, and set operator etc
OBJECTIVE To Write SQL queries using Insert, Select, Update, delete with operators, functions, and set operator etc.
Use of SQL objects such as Table, View, Index, Sequence, Synonym, different constraints etc.
PROBLEM STATEMENT:
Create above tables with appropriate constraints like primary key, foreign key, check constrains, not null etc.
Q2. Find all loan numbers for loans made at Akurdi Branch with loan amount > 12000.
Q3. Find all customers who have a loan from bank. Find their names, loan_no and loan amount. Q4. List all customers in
alphabetical order who have loan from Akurdi branch.
Q5. Find all customers who have an account or loan or both at bank. Q6. Find all customers who have both account and
loan at bank.
Q7. Find all customer who have account but no loan at the bank. Q8. Find average account balance at Akurdi branch.
Q9. Find the average account balance at each branch Q10. Find no. of depositors at each branch.
Q11. Find the branches where average account balance > 12000. Q12. Find number of tuples in customer relation.
Q14. Delete all loans with loan amount between 1300 and 1500. Q15. Delete all tuples at every branch located in Nigdi.
Q.17. Create sequence roll_seq and use in student table for roll_no column.
THEORY:
Data manipulation language (DML) statements access and manipulate data in existing schema objects. These statements
do not implicitly commit the current transaction. The SELECT statement is a limited form of DML statement in that it can
only access data in the database. It cannot manipulate data in the database, although it can operate on the accessed data
before returning the results of the query.
The data manipulation language statements are: INSERT, UPDATE, DELETE, SELECT
SQL INSERT : Statement is used to add new rows of data to a table in the database.
Syntax: There are two basic syntax of INSERT INTO statement as follows:
Here, column1, column2,…columnN are the names of the columns in the table into which want to insert data.
It‘s not required to specify the column(s) name in the SQL query if values for all the columns of the table are provided.
But make sure the order of the values is in the same order as the columns in the table. The SQL INSERT INTO syntax
would be as follows:
Insert Into TABLE_NAME Values (Value 1, Value 2, Value 3…… Value N);
syntax:
INSERT INTO first_table_name [(column1, column2, … columnN)] SELECT column1, column2,
…columnN FROM second_table_name [WHERE condition];
Here, column1, column2…are the fields of a table whose values you want to fetch. If you want to fetch all the fields
available in the field, then you can use the following syntax:
The SQL WHERE clause is used to specify a condition while fetching the data from single table or joining with multiple
tables. If the given condition is satisfied then only it returns specific value from the table. You would use WHERE clause
to filter the records and fetching only necessary records. The WHERE is also used in UPDATE, DELETE statement
Syntax: The basic syntax of SELECT statement with WHERE clause is as follows: SELECT column1, column2,
columnN FROM table_name WHERE [condition]
You can specify a condition using comparison or logical operators like >, <, =, LIKE, NOT, etc. SQL> SELECT ID,
NAME, SALARY FROM CUSTOMERS WHERE SALARY > 2000; SQL> SELECT ID, NAME, SALARY FROM
CUSTOMERS WHERE NAME = ‗Hardik‘;
The SQL AND and OR operators are used to combine multiple conditions to narrow data in an SQL statement. These two
operators are called conjunctive operators. These operators provide a means to make multiple
The AND Operator: The AND operator allows the existence of multiple conditions in an SQL statement‘s WHERE
clause.
Syntax: The basic syntax of AND operator with WHERE clause is as follows:
SELECT column1, column2, columnN FROM table_name WHERE [condition1] AND [condition2]…AND [conditionN];
You can combine N number of conditions using AND operator. For an action to be taken by the SQL statement, whether
it be a transaction or query, all conditions separated by the AND must be TRUE.
SQL> SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE SALARY > 2000 AND age < 25;
The OR Operator: The OR operator is used to combine multiple conditions in an SQL statement‘s WHERE clause.
SELECT column1, column2, columnN FROM table_name WHERE [condition1] OR [condition2]…OR [conditionN]
You can combine N number of conditions using OR operator. For an action to be taken by the SQL statement, whether it
be a transaction or query, only any ONE of the conditions separated by the OR must be TRUE.
SQL> SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE SALARY > 2000 OR age < 25;
SQL UPDATE Query is used to modify the existing records in a table. You can use WHERE clause with UPDATE query
to update selected rows otherwise all the rows would be affected.
Syntax: The basic syntax of UPDATE query with WHERE clause is as follows:
UPDATE table_name SET column1 = value1, column2 = value2…., columnN = valueN WHERE [condition]; You can
combine N number of conditions using AND or OR operators.
The SQL DELETE Query is used to delete the existing records from a table. You can use WHERE clause with DELETE
query to delete selected rows, otherwise all the records would be deleted.
Syntax: The basic syntax of DELETE query with WHERE clause is as follows: DELETE FROM table_name WHERE
[condition];
You can combine N number of conditions using AND or OR operators. SQL> DELETE FROM CUSTOMERS WHERE
ID = 6;
If you want to DELETE all the records from CUSTOMERS table, you do not need to use WHERE clause and DELETE
query would be as follows:
Syntax: The basic syntax of DISTINCT keyword to eliminate duplicate records is as follows: SELECT DISTINCT
column1, column2,…..columnN FROM table_name WHERE [condition] SELECT DISTINCT SALARY FROM
CUSTOMERS ORDER BY SALARY;
The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups.
The GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause.
Syntax: The basic syntax of GROUP BY clause is given below. The GROUP BY clause must follow the conditions in the
WHERE clause and must precede the ORDER BY clause if one is used.
SELECT column1, column2 FROM table_name WHERE [ conditions ] GROUP BY column1, column2 SQL> SELECT
NAME, SUM(SALARY) FROM CUSTOMERS GROUP BY NAME;
Following is an example, which would sort the result in descending order by NAME:
DDL- Data Definition Language (DDL) statements are used to define the database structure or schema. Data Definition
Language understanding with database schemas and describes how the data should consist in the database, therefore
language statements like CREATE TABLE or ALTER TABLE belongs to the DDL. DDL is about ―metadata‖.
TRUNCATE – remove all records from a table, including all spaces allocated for the records are removed
Create Database: From the MySQL command line, enter the command CREATE
DATABASE
<DATABASENAME>;. Replace <DATABASENAMEs> with the name of your database. It cannot include spaces.
SHOW DATABASES;
list all of the databases you have stored. Besides the database you just created, you will also see a mysql database and a
test database.
Create table:
We define an SQL relation by using the create table command. The following command creates a relation department in
the database.
create table department(dept name varchar (20),building varchar (15),budget numeric (12,2),
primary key (dept name));
Insert values in table: A newly created relation is empty initially. We can use the insert command to load data into the
relation. For example, if we wish to insert the fact that there is an instructor named Smith in the Biology department with
instructor id 10211 and a salary of $66,000, we write:
Drop table: To remove a relation from an SQL database, we use the drop table command. The drop table
command deletes all information about the dropped relation from the database. The command
drop table r
Alter Table :We use the alter table command to add attributes to an existing relation. All tuples in the relation are assigned
null as the value for the new attribute. The form of the alter table command is
where r is the name of an existing relation, A is the name of the attribute to be added, and D is the type of the added
attribute. We can drop attributes from a relation by the command
where r is the name of an existing relation, and A is the name of an attribute of the relation.
View:
SQL allows a ―virtual relation‖ to be defined by a query, and the relation conceptually contains the result of the query.
The virtual relation is not precomputed and stored, but instead is computed by executing the query whenever the virtual
relation is used. Any such relation that is not part of the logical model, but is made visible to a user as a virtual relation, is
called a view.
Create View: We define a view in SQL by using the create view command.
where <query expression> is any legal query expression. The view name is represented by v.
Alter View: The CREATE VIEW statement creates a new view, or replaces an existing view if the OR REPLACE clause
is given. If the view does not exist, CREATE OR REPLACE VIEW is the same as CREATE VIEW.
Drop view: Use the DROP VIEW statement to remove a view or an object view from the database. You can change the
definition of a view by dropping and re-creating it.
Syntax:
INDEX:
Create Index: A database index is a data structure that improves the speed of operations in a table. Indexes can be created
using one or more columns, providing the basis for both rapid random lookups and efficient ordering of access to records.
The users cannot see the indexes; they are just used to speed up queries and will be used by the Database Search Engine to
locate records very fast. The INSERT and UPDATE statements take more time on tables having indexes, whereas the
SELECT statements become fast on those tables.
Simple and Unique Index: You can create a unique index on a table. A unique index means that two rows cannot have
the same index value. Here is the syntax to create an Index on a table.
You can use one or more columns to create an index. For example, we can create an index on table student using column
rno
Alter Index: There are four types of statements for adding indexes to a table −
ALTER TABLE tbl_name ADD PRIMARY KEY (column_list)− This statement adds a PRIMARY KEY, which means
that the indexed values must be unique and cannot be NULL.
ALTER TABLE tbl_name ADD UNIQUE index_name (column_list)− This statement creates an index for which the
values must be unique (except for the NULL values, which may appear multiple times).
ALTER TABLE tbl_name ADD INDEX index_name (column_list)− This adds an ordinary index in which any value may
appear more than once.
ALTER TABLE tbl_name ADD FULLTEXT index_name (column_list)− This creates a special FULLTEXT index that
is used for text-searching purposes.
Drop Index: You can drop any INDEX by using the DROP clause along with the ALTER command. Try out the
following example to drop the above-created index.
You can drop any INDEX by using the DROP clause along with the ALTER command.
Sequence:
To create a sequence value in SQL query, we can use AUTO_INCREMENT with optional starting value.
CONCLUSION
Assignment No. 3
TITLE:
SQL queries using concepts like all types of Join, Sub-Query and View
OBJECTIVE To write the SQL queries using concepts like all types of Join, Sub-Query and View
PROBLEM STATEMENT:
cust_mstr(cust_no,fname,lname)
add_dets(code_no,add1,add2,state,city,pincode)
cust_mstr(custno,fname,lname)
acc_fd_cust_dets(codeno,acc_fd_no)
fd_dets(fd_sr_no,amt)
List the customer holding fixed deposit of amount more than 5000
emp_mstr(e_mpno,f_name,l_name,m_name,dept,desg,branch_no)
branch_mstr(name,b_no)
List the employee details along with branch names to which they belong
emp_mstr(emp_no,f_name,l_name,m_name,dept)
cntc_dets(code_no,cntc_type,cntc_data)
List the employee details along with contact details using left outer join & right join
cust_mstr(cust_no,fname,lname)
add_dets(code_no,pincode)
List the customer who do not have bank branches in their vicinity.
6. a) Create View on borrower table by selecting any two columns and perform insert update delete
operations
b) Create view on borrower and depositor table by selecting any one column from each table
perform insert update delete operations
c) create updateable view on borrower table by selecting any two columns and perform insert
THEORY:
The most frequently used clause is INNER JOIN. This produces a set of records which match in both the user and
course tables, i.e. all users who are enrolled on a course:
Result:
user.name course.name
Alice HTML5
Bob HTML5
Carline CSS3
David MySQL
LEFT JOIN
What if we require a list of all students and their courses even if they‘re not en rolled on one? A LEFT JOIN
produces a set of records which matches every entry in the left table (user) regard less of any matching entry in the
right table (course):
user.name course.name
Alice HTML5
Bob HTML5
Carline CSS3
David MySQL
Emma (NULL)
RIGHT JOIN
Perhaps we require a list all courses and students even if no one has been enrolled? A RIGHT JOIN produces a set
of records which matches every entry in the right table (course) regardless of any matching entry in the left table
(user):
Result:
user.name course.name
Alice HTML5
Bob HTML5
Carline CSS3
(NULL) JavaScript
(NULL) PHP
David MySQL
RIGHT JOINs are rarely used since you can express the same result using a LEFT JOIN. This can be more effi
cient and quicker for the database to parse:
We could, for example, count the number of students enrolled on each course:
course.name count()
HTML5 2
CSS3 1
JavaScript 0
PHP 0
MySQL 1
Our last option is the OUTER JOIN which returns all records in both tables regard less of any match. Where no
match exists, the missing side will contain NULL.
OUTER JOIN is less useful than INNER, LEFT or RIGHT and it‘s not implemented in MySQL. However, you can
work around this restriction using the UNION of a LEFT and RIGHT JOIN, e.g.
UNION
Result:
user.name course.name
Alice HTML5
Bob HTML5
Carline CSS3
David MySQL
Emma (NULL)
(NULL) JavaScript
(NULL) PHP
**********************PROGRAM************************
Student table-sid-PK
Rno,name,deptid,shift,class,Year,Marks,DOB,address
Dept table
deptid-FK
did,name,location,establishmentdate,intake.
Joins:
Suppliertb:
Q1. Select all students with names starting with A.
Q2. Select all students with department name as ―Computer‖
Q3. Find count of students in ―Computer‖ department.
Q4. List students yearwise.
Q5. Create View to display rno, name, deptid, department name.
Q6. Apply inner join, right join, left join and full outer join queries to display data from both tables.
Q7. Find dept with intake within the range of greater than 50 and less
Database changed
MariaDB [tej]> select *from siddd;
+------+--------+--------+--------+-------+-------+------+-----------+
| Rno | name | deptid | shift | class | marks | DOB | Address |
+------+--------+--------+--------+-------+-------+------+-----------+
| 8 | Sakshi | Comp | second | TE | 89 | 1997 | Pune |
| 45 | Shifa | IT | first | TE | 45 | 1997 | Chinchwad |
| 49 | Anuj | Comp | second | TE | 45 | 1997 | Pimpri |
| 43 | Tejas | Comp | second | TE | 78 | 1997 | Pune |
+------+--------+--------+--------+-------+-------+------+-----------+
4 rows in set (0.02 sec)
MariaDB [tej]> select name from siddd where name like '%A';
+-------+
| name |
+-------+
| Shifa |
+-------+
1 row in set (0.02 sec)
MariaDB [tej]> select name from siddd where name like 'A%';
+------+
| name |
+------+
| Anuj |
+------+
1 row in set (0.00 sec)
OBJECTIVE: To write a PL/SQL block of code using Control structure and Exception handling.
PROBLEM STATEMENT:
Write a PL/SQL block for following requirement and handle the exceptions.
Roll no. of student will be entered by user. Attendance of roll no. entered by user will be checked in
Stud table. If attendance is less than 75% then display the message “Term not granted” and set the
status in stud table as “D”. Otherwise display message “Term granted” and set the status in stud
table as “ND”
2. Write a PL/SQL block for following requirement using user defined exception handling.
The account_master table records the current balance for an account, which is updated whenever,
any deposits or withdrawals takes place. If the withdrawal attempted is more than the current
balance held in the account. The user defined exception is raised, displaying an appropriate
message. Write a PL/SQL block for above requirement using user defined exception handling.
Check the number of days (from date of issue), if days are between 15 to 30 then fine
If no. of days>30, fine will be Rs 50 per day & for days less than 30, Rs. 5 per day.
If condition of fine is true, then details will be stored into fine table.
Also handles the exception by named exception handler or user define exception handler.
THEORY: PL/SQL
Introduction to PL/SQL,
A procedure (often called a stored procedure) is a subroutine like a subprogram in a regular computing
language, stored in database. A procedure has a name, a parameter list, and SQL statement(s). All most all
relational database system supports stored procedure, MySQL 5 introduce stored procedure. In the following
sections we have discussed MySQL procedure in details and used MySQL 5.6 under Windows 7. MySQL 5.6
supports "routines" and there are two kinds of routines : stored procedures which you call, or functions whose
return values you use in other SQL statements the same way that you use pre-installed MySQL functions like pi().
The major difference is that UDFs can be used like any other expression within SQL statements, whereas
stored procedures must be invoked using the CALL statement.
• Stored procedures are fast. MySQL server takes some advantage of caching, just as prepared statements do.
The main speed gain comes from reduction of network traffic. If you have a repetitive task that re quires
checking, looping, multiple statements, and no user interaction, do it with a single call to a proce dure that's
stored on the server.
• Stored procedures are portable. When you write your stored procedure in SQL, you know that it will run on
every platform that MySQL runs on, without obliging you to install an additional runtime environment
package, or set permissions for program execution in the operating system, or deploy dif ferent packages if you
have different computer types. That's the advantage of writing in SQL rather than in an external language like
Java or C or PHP.
Limitations of SQL
Poor Interface
SQL has a poor interface as it makes look everything very complex even when it's not! Due to its difficult interfacing,
users find it difficult to deal with the databases.
2. Cost Inefficient
SQL Server Standard costs around $1,418/year. The high cost makes it difficult for some programmers to use it.
3. Partial Control
SQL doesn't grant the complete control over databases to its users. This is due to some hidden business rules.
4. Security
Regardless of the SQL version, databases in SQL are constantly under threat as it holds huge amounts of sensitive data.
Advantages of PL/SQL
• It is a standard database language and PL/SQL is strongly integrated with SQL. PL/SQL supports both static
and also dynamic SQL. Static SQL is said to support DML operations and also the transaction control from
PL/SQL block. In dynamic SQL, SQL allows embedding the DDL statements in the PL/SQL blocks.
• Also, It then allows sending an entire block of statements to the database at one time. It reduces network traffic
and also provides high performance for the applications.
• It gives high productivity to programmers as it can query, transform and also update the data in the database.
• This is said to save time on the design and also the debugging by strong features, like the exception handling,
encapsulation, data hiding and also object-oriented data types.
Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be nested within other PL/SQL blocks
using BEGIN and END. Following is the basic structure of a PL/SQL block −
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
exception1-handling-statements
exception2-handling-statements
........
exception3-handling-statements
END;
CONCLUSION :
Assignment No. 5
TITLE: Named PL/SQL Block for given requirements using PL/SQLStored Procedure and Stored
Function.
OBJECTIVE: To Write a Named PL/SQL Block for given requirements using PL/SQLStored
PROBLEM STATEMENT:
1. Write a PL/SQL stored Procedure for following requirements and call the procedure in
2. Fine(Roll_no,Date,Amt)
Check the number of days (from date of issue), if days are between 15 to 30 then fine
If no. of days>30, per day fine will be Rs 50 per day & for days less than 30, Rs. 5 per
day.
If condition of fine is true, then details will be stored into fine table.
2. Write a stored function in PL/SQL for given requirement and use the same in PL/SQL block.
Account no. and branch name will be accepted from user. The same will be searched in table
acct_details. If status of account is active then display appropriate message and also store the
inactive”.
3. Write a Stored Procedure namely proc_Grade for the categorization of student. If marks scored
distinction category if marks scored are between 989 and900 category is first class, if marks
Write a PL/SQL block for using procedure created with above requirement.
Stud_Marks(name, total_marks)
Result(Roll,Name, Class)
THEORY:
Create Procedure
Following statements create a stored procedure. By default, a procedure is associated with the default
database (currently used database). To associate the procedure with a given database, specify the name as data
base_name.stored_procedure_name when you create it. Here is the complete syntax :
Syntax:
mysql>SELECT VERSION();
+-----------+
| VERSION() |
+-----------+
| 5.6.12 |
+-----------+
1 row in set (0.00 sec)
CREATE PROCEDURE and CREATE FUNCTION require the CREATE ROUTINE privilege. They might also
require the SUPER privilege, depending on the DEFINER value, as described later in this section. If binary logging
is enabled, CREATE FUNCTION might require the SUPER privilege. By default, MySQL automatical ly grants the
ALTER ROUTINE and EXECUTE privileges to the routine creator. This behavior can be changed by disabling the
automatic_sp_privileges system variable.
Select a database:
Before creates a procedure we must select a database. Let see the list of databases and choose one of them.
Pick a Delimiter
The delimiter is the character or string of characters which is used to complete an SQL statement. By default
we use semicolon (;) as a delimiter. But this causes problem in stored procedure because a procedure can have
many statements, and everyone must end with a semicolon. So for your delimiter, pick a string which is rarely
occur within statement or within procedure. Here we have used double dollar sign i.e. $$.You can use whatever
you want. To resume using ";" as a delimiter later, say "DELIMITER ; $$". See here how to change the delimiter :
mysql> DELIMITER $$ ;
Now the default DELIMITER is "$$". Let execute a simple SQL command :
mysql> DELIMITER ; $$
Here we have created a simple procedure called job_data, when we will execute the procedure it will display all the
data from "jobs" tables.
Call a procedure
The CALL statement is used to invoke a procedure that is stored in a DATABASE. Here is the syntax CALL
sp_name([parameter[,...]])
CALL sp_name[()]
Stored procedures which do not accept arguments can be invoked without parentheses. Therefore CALL job_data()
and CALL job_data are equivalent. Let execute the procedure.
This statement is a MySQL extension. It returns the exact string that can be used to re-create the named
stored procedure. Both statement require that you be the owner of the routine. syntax :
CONCLUSION
Assignment No. 6
TITLE PL/SQL code block using Cursors (All types: Implicit, Explicit,Cursor FOR Loop,
Parameterized Cursor)
OBJECTIVE: To write a PL/SQL code block using Cursors (All types: Implicit, Explicit,Cursor
PROBLEM STATEMENT:
Implicit Cursor
1. The bank manager has decided to activate all those accounts which were previously marked as
inactive for performing no transaction in last 365 days. Write a PL/SQ block (using implicit cursor)
to update the status of account, display an approximate message based on the no. of rows affected
by the update.
EXPLICIT CURSOR:
2. Organization has decided to increase the salary of employees by 10% of existing salary, who are
having salary less than average salary of organization, Whenever such salary updates takes place, a
increment_salary(E_no , Salary)
College has decided to mark all those students detained (D) who are having attendance less than
75%. Whenever such update takes place, a record for the same is maintained in the D_Stud table.
parameterized Cursor
4. Write a PL/SQL block of code using parameterized Cursor, that will merge the data available in
the newly created table N_RollCall with the data available in the table O_RollCall. If the data in the
first table already exist in the second table then that data should be skipped.
parameterized Cursor
5. Write the PL/SQL block for following requirements using parameterized Cursor:
Consider table EMP(e_no, d_no, Salary), department wise average salary should be inserted into
6. Write PL/SQL block using explicit cursor: Cursor FOR Loop for following requirements:
College has decided to mark all those students detained (D) who are having attendance less than
75%. Whenever such update takes place, a record for the same is maintained in the D_Stud table.
THEORY:
A cursor in SQL Server is a database object that allows us to retrieve each row at a time and manipulate its data. A cursor
is nothing more than a pointer to a row. It's always used in conjunction with a SELECT statement. It is usually a
collection of SQL logic that loops through a predetermined number of rows one by one. A simple illustration of the cursor
is when we have an extensive database of worker's records and want to calculate each worker's salary after deducting
taxes and leaves.
%FOUND
%NOTFOUND
%ISOPEN
3 Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor
automatically after executing its associated SQL statement.
%ROWCOUNT
4
Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement,
or returned by a SELECT INTO statement.
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
6 customers selected
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |
| 6 | Komal | 22 | MP | 5000.00 |
+----+----------+-----+-----------+----------+
Explicit Cursors
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.
The syntax for creating an explicit cursor is −
CURSOR cursor_name IS select_statement;
Working with an explicit cursor includes the following steps −
Declaring the cursor defines the cursor with a name and the associated SELECT statement. For example −
CURSOR c_customers IS
SELECT id, name, address FROM customers;
Opening the cursor allocates the memory for the cursor and makes it ready for fetching the rows returned by the
SQL statement into it. For example, we will open the above defined cursor as follows −
OPEN c_customers;
Fetching the cursor involves accessing one row at a time. For example, we will fetch rows from the above-
opened cursor as follows −
FETCH c_customers INTO c_id, c_name, c_addr;
Closing the cursor means releasing the allocated memory. For example, we will close the above-opened cursor
as follows −
CLOSE c_customers;
Example
Following is a complete example to illustrate the concepts of explicit cursors &minua;
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;
/
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
1 : Declare Cursor
The first step is to declare the cursor using the below SQL statement:
2: Open Cursor
It's a second step in which we open the cursor to store data retrieved from the result set. We can do this by using the below
SQL statement:
OPEN cursor_name;
3: Fetch Cursor
It's a third step in which rows can be fetched one by one or in a block to do data manipulation like insert, update, and
delete operations on the currently active row in the cursor. We can do this by using the below SQL statement:
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM cursor_name;
END;
4: Close Cursor
It's a fourth step in which the cursor should be closed after we finished work with a cursor. We can do this by using the
below SQL statement:
CLOSE cursor_name;
5: Deallocate Cursor
It is the fifth and final step in which we will erase the cursor definition and release all the system resources associated
with the cursor. We can do this by using the below SQL statement:
DEALLOCATE cursor_name;
CONCLUSION
Assignment No. 7
TITLE: PL/SQL code block using Trigger Trigger (All Types: Rowlevel and Statement level
OBJECTIVE: To write a PL/SQL code using Database Trigger (All Types: Rowlevel and
PROBLEM STATEMENT:
1. Write a update, delete trigger on clientmstr 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 audit_trade table. (separate implementation using both row and statement triggers)
2. Write a before trigger for Insert, update event considering following requirement:
I) Trigger action should be initiated when salary is tried to be inserted is less than Rs. 50,000/-
II) Trigger action should be initiated when salary is tried to be updated for value less than Rs.
50,000/-
Action should be rejection of update or Insert operation by displaying appropriate error message.
Also the new values expected to be inserted will be stored in new table Tracking(e_no, salary).
emp_sal(emp_no, sal1,sal2,sal3)
before inserting salary into emp_sal table, if salary of employee in any of the last three month is
greater than Rs. 50,000/- then entry of average salary along with emp_no needs to be inserted into
Theory:
A trigger is a set of SQL statements that reside in system memory with unique names. It is a specialized category of stored
procedure that is called automatically when a database server event occurs. Each trigger is always associated with a table.
A trigger is called a special procedure because it cannot be called directly like a stored procedure. The key distinction
between the trigger and procedure is that a trigger is called automatically when a data modification event occurs against a
table. A stored procedure, on the other hand, must be invoked directly.
The following are the main characteristics that distinguish triggers from stored procedures:
Syntax of Trigger
We can create a trigger in SQL Server by using the CREATE TRIGGER statement as follows:
schema: It is an optional parameter that defines which schema the new trigger belongs to.
trigger_name: It is a required parameter that defines the name for the new trigger.
table_name: It is a required parameter that defines the table name to which the trigger applies. Next to the table name, we
need to write the AFTER clause where any events like INSERT, UPDATE, or DELETE could be listed.
NOT FOR REPLICATION: This option tells that SQL Server does not execute the trigger when data is modified as part
of a replication process.
SQL_Statements: It contains one or more SQL statements that are used to perform actions in response to an event that
occurs.
Triggers will be helpful when we need to execute some events automatically on certain desirable scenarios. For example,
we have a constantly changing table and need to know the occurrences of changes and when these changes happen. If the
primary table made any changes in such scenarios, we could create a trigger to insert the desired data into a separate table.
Let us understand how we can work with triggers in the SQL Server. We can do this by first creating a table named
'Employee' using the below statements:
We can verify the insert operation by using the SELECT statement. We will get the below output:
Conclusion:
Assignment No. 8
TITLE: MongoDB Queries using CRUD operations. (Use CRUDoperations, SAVE method, logical
operators etc)
OBJECTIVE: To Write the MongoDB Queries using CRUD operations. (Use CRUDoperations, SAVE
PROBLEM STATEMENT:
Teachers(Tname,dno,dname,experience,salary,date_of_joining )
Students(Sname,roll_no,class)
6. Find the information about all teachers of computer,IT,and E&TC department having salary greater than
or equal to 10000/-
8. Update the experience of teacher-praveen to 10years, if the entry is not available in database consider
10. find the teachers name and their experience from teachers collection
13. Delete all the documents from teachers collection having IT dept.
14. display with pretty() method, the first 3 documents in teachers collection in ascending order
Theory:
NoSQL originally referring to non SQL or non relational is a database that provides a mechanism for storage and
retrieval of data.
This data is modeled in means other than the tabular relations used in relational databases. Such databases came into
existence in the late 1960s, but did not obtain the NoSQL moniker until a surge of popularity in the early twenty-first
century.
NoSQL databases are used in real-time web applications and big data and their use are increasing over time. NoSQL
systems are also sometimes called Not only SQL to emphasize the fact that they may support SQL-like query
languages.
A NoSQL database includes simplicity of design, simpler horizontal scaling to clusters of machines and finer control
over availability. The data structures used by NoSQL databases are different from those used by default in relational
databases which makes some operations faster in NoSQL.
MongoDB – Explanation
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’
means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides
an altogether different mechanism for storage and retrieval of data. This format of storage is called BSON ( similar to
JSON format).
A simple MongoDB document Structure:
{
title: 'Geeksforgeeks',
by: 'Harshit Gupta',
url: 'https://www.geeksforgeeks.org',
type: 'NoSQL'
}
SQL databases store data in tabular format. This data is stored in a predefined data model which is not very much
flexible for today’s real-world highly growing applications. Modern applications are more networked, social and
interactive than ever. Applications are storing more and more data and are accessing it at higher rates.
Relational Database Management System(RDBMS) is not the correct choice when it comes to handling big data by the
virtue of their design since they are not horizontally scalable. If the database runs on a single server, then it will reach a
scaling limit. NoSQL databases are more scalable and provide superior performance. MongoDB is such a NoSQL
database that scales by adding more and more servers and increases productivity with its flexible document model.
TAKE AWAY
MongoDB is the leading NoSQL database on the market and utilizes a document-oriented database.
MongoDB supports the rich querying of datasets large or small with fast response times.
Using dynamic schemas, MongoDB enables agile development and flexibility for application or business
requirement changes.
MongoDB emphasizes performance, scalability, and high availability and in many cases exceeds traditional
MongoDB is a proven solution for a wide range of business requirements to companies across numerous
industries.
As we know that we can use MySQL to use Structure Query Language to store the data in the form of RDBMS.
SQL is the most popular language for adding, accessing, and managing content in a database. It is most noted for its
quick processing, proven reliability, ease, and flexibility of use. The application is used for a wide range of purposes,
including data warehousing, e-commerce, and logging applications. The most common use for MySQL, however, is for
the purpose of a web database.
1. column_name –
Name of the particular column with any space.
2. column_type –
Datatype of the column. Datatype depends upon the data of the reference column. Datatype can be – char(),
varchar(), int(), float(), etc.
3. constraints –
In order to give restrictions to particular column constraints are used. Constraints can be – not null, primary key,
foreign key, etc. These are the keywords which give set of restriction to the particular column.
Database – GFG
Table – Student
Student –
use gfg;
Create table student(name Varchar(30) NOT NULL, marks Integer);
Output :
use gfg;
select * from student;
name marks
ravi 23
swati 33
kranti12
3. Update Operation :
Altering the content of the table or the structure of the table is done with the help of Update Operations. Two
Commands are mostly used for Update Operation –
Alter Table Command that change the size of name column from varchar(40) to varchar(50) for the Student table :
desc student;
Field Type Null Default
name varchar(40) YES Null
marks int(11) YES Null
desc student;
Update Command that update the marks of the student from 23 to 100 whose name is ravi using the update command :
1. Delete Command –
(DML command) works on the records of the table.
2. Drop Command –
(DDL command) works on the structure of the table.
Delete Command that delete the records of students having marks equal to 100 :
delete from student
where marks = 100;
Original Table –
name marks
swati 33
kranti12
Drop Command that drop the table student :
drop table student;
Original Structure –
use gfg;
show tables;
Tables_in_gfg
student
After dropping the student table –
use gfg;
show tables;
Tables_in_gfg
Conclusion:
Group C [DBMS] Mini Project
2. Follow the Software Development Life cycle and other concepts learnt in Software Engineering
5. Student should develop application in group of 2-3 students and submit the Project Report which will
Testing document
Conclusion.
ASSIGNMENT (Beyond Syllabus)
Today, data can be analyzed to make real-time decisions, spot emerging trends and uncover insights that
would not be evident using legacy data processes.
R and Python
Microsoft Excel
Tableau
RapidMiner
KNIME
Power BI
Apache Spark
QlikView
Talend
Splunk
Splunk
Splunk is a platform used to search, analyze, and visualize the machine-generated data gathered from
applications, websites, etc. Being named by Gartner as a Visionary in the 2020 Magic Quadrant for
APM, Splunk has evolved products in various fields such as IT, Security, DevOps, Analytics.
Talend
Talend is one of the most powerful data integration ETL tools available in the market and is developed in the
Eclipse graphical development environment. Being named as a Leader in Gartner’s Magic Quadrant for
Data Integration Tools and Data Quality tools 2019, this tool lets you easily manage all the steps involved
in the ETL process and aims to deliver compliant, accessible and clean data for everyone.
QlikView
QlikView is a Self-Service Business Intelligence, Data Visualization, and Data Analytics tool. Being named
a leader in Gartner Magic Quadrant 2020 for Analytics and BI platforms, it aims to accelerate business
value through data by providing features such as Data Integration, Data Literacy, and Data Analytics.
Apache Spark
Apache Spark is one of the most successful projects in the Apache Software Foundation and is a cluster
computing framework that is open-source and is used for real-time processing. Being the most active Apache
project currently, it comes with a fantastic open-source community and an interface for programming. This
interface makes sure of fault tolerance and implicit data parallelism.
Power BI
is a Microsoft product used for business analytics. Named as a leader for the 13th consecutive year in the
Gartner 2020 Magic Quadrant, it provides interactive visualizations with self-service business intelligence
capabilities, where end users can create dashboards and reports by themselves, without having to depend on
anybody.
KNIME
Konstanz Information Miner or most commonly known as KNIME is free and an open-source data analytics,
reporting, and integration platform built for analytics on a GUI based workflow.
RapidMiner
RapidMiner is the next tool on our list. Being named a Visionary in 2020 Gartner Magic Quadrant for Data
Science and Machine Learning Platforms, RapidMiner is a platform for data processing, building Machine
Learning models, and deployment.