0% found this document useful (0 votes)
14 views

DBMS Lab Manual1

The document is a lab manual for the Database Management Systems course prepared for the TE AI&DS program for the academic year 2022-23. It outlines the vision, mission, program education objectives, specific outcomes, and outcomes for graduates, along with a list of experiments and assignments related to database programming and SQL. The manual aims to equip students with practical skills in AI&DS and prepare them for professional challenges in the field.

Uploaded by

Mandar Patil
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

DBMS Lab Manual1

The document is a lab manual for the Database Management Systems course prepared for the TE AI&DS program for the academic year 2022-23. It outlines the vision, mission, program education objectives, specific outcomes, and outcomes for graduates, along with a list of experiments and assignments related to database programming and SQL. The manual aims to equip students with practical skills in AI&DS and prepare them for professional challenges in the field.

Uploaded by

Mandar Patil
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Department of Artificial Intelligence & Data Science

Lab Manual

Data Base Management Systems laboratory


(317523)

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)

PEO1:Graduates will have the capabilities to apply AI&DS knowledge to


develop feasible systems.

PEO2:Graduates will be able to handle the challenges of rapidly


changing technology.

PEO3:Equip the graduates with strong technical knowledge,


competency in soft skills, lifelong learning skills that allow them to
contribute ethically to the need of society.

Program Specific Outcomes (PSOs)

PSO1 Problem Solving and Programming Skills:Graduates will be able


to practically apply the knowledge of various programming languages and
data analytics tools and techniques.

PSO2 Professional Skills:Graduates will be able to apply the knowledge of


software engineering principles and practices to the multidisciplinary
areas of AI&DS to meet the needs of the industry and society.

PSO3 Successful Career:Graduates will be able to become entrepreneur


and to pursue higher studies / career in software industries.
Program Outcomes (POs)
Graduates will be able to

1. Apply the knowledge of mathematics, science, engineering fundamentals, and an engineering


specialization to the solution of complex engineering problems. [Engineering knowledge]
2. Identify, formulate, research literature, and analyse complex engineering problems reaching substantiated
conclusions using first principles of mathematics, natural sciences, and engineering sciences. [Problem
analysis]
3. Design solutions for complex engineering problems and design system components or processes that
meet the specified needs with appropriate consideration for the public health and safety, and the
cultural, societal, and environmental considerations. [Design/development of solutions]
4. Use research-based knowledge and research methods including design of experiments, analysis and
interpretation of data, and synthesis of the information to provide valid conclusions. [Conduct
investigations of complex problems]
5. Create, select, and apply appropriate techniques, resources, and modern engineering and IT tools
including prediction and modelling to complex engineering activities with an understanding of the
limitations. [Modern tool usage]
6. Apply reasoning informed by the contextual knowledge to assess societal, health, safety, legal and
cultural issues and the consequent responsibilities relevant to the professional engineering practice. [The
engineer and society]
7. Understand the impact of the professional engineering solutions in societal and environmental contexts,
and demonstrate the knowledge of, and need for sustainable development. [Environment and
sustainability]
8. Apply ethical principles and commit to professional ethics and responsibilities and norms of the
engineering practice. [Ethics]
9. Function effectively as an individual, and as a member or leader in diverse teams, and in
multidisciplinary settings. [Individual and team work]
10. Communicate effectively on complex engineering activities with the engineering community and with
society at large, such as, being able to comprehend and write effective reports and design documentation,
make effective presentations, and give and receive clear instructions. [Communication]
11. Demonstrate knowledge and understanding of the engineering and management principles and apply
these to one’s own work, as a member and leader in a team, to manage projects and in multidisciplinary
environments. [Project management and finance]
12. Recognize the need for, and have the preparation and ability to engage in independent and life-long
learning in the broadest context of technological change. [Life-long learning]
List of Experiments
Lab No. Name of Subject : DBMS Lab Class: T.E.AI&DS

Sr. Experiment Name Equipment/ CO PO PSO


No. Software
required

Group A: Database Programming SQL,PL/SQL

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)

Group C :- Mini Project : Database Project

1 Develop an application with Front End: CO302.6 1,2,3,4,5,9,10,12 1,2,3


following details: Python/Java/PHP/Perl/Ruby
1. Follow the same problem /.NET/ or any other
statement decided in Assignment-1 language
of Group A. Backend : MongoDB/
2. Follow the Software MySQL/ Oracle / or any
Development Life cycle and other standard SQL / NoSQL
concepts learnt in Software database
Engineering
Assignment - 1 (to be prepared as soft copy)
TITLE :

Conceptual design using ER Model, Reducing ER into tables, normalization


OBJECTIVE Propose a Conceptual Design using ER features using tools like ERDplus, ER Win etc.
Convert the ER diagram into tables on paper and propose a normalize Relational data model.

PROBLEM STATEMENT:

<< Write your mini Project Problem Statement here>>


THEORY:

 All ER Notations
 Brief rules to reduce ER diagram into tables
 Brief about 1NF, 2NF, 3NF and BCNF

E-R Diagram (for your Problem Statement):

Reduced Table Structure from above E-R Diagram:

Normalized Tables at least in 3NF:

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:

Account(Acc_no, branch_name,balance) branch(branch_name,branch_city,assets)


customer(cust_name,cust_street,cust_city) Depositor(cust_name,acc_no) Loan(loan_no,branch_name,amount)
Borrower(cust_name,loan_no)

Solve following query:

Create above tables with appropriate constraints like primary key, foreign key, check constrains, not null etc.

Q1. Find the names of all branches in loan relation.

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.

Q13. Calculate total loan amount given by bank.

Q14. Delete all loans with loan amount between 1300 and 1500. Q15. Delete all tuples at every branch located in Nigdi.

Q.16. Create synonym for customer table as cust.

Q.17. Create sequence roll_seq and use in student table for roll_no column.
THEORY:

Data Manipulation Language (DML) Statements :

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:

INSERT INTO TABLE_NAME (column1, column2, column3,…columnN)] VALUES (value1, value2,


value3,…valueN);

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);

Populate one table using another table:

syntax:
INSERT INTO first_table_name [(column1, column2, … columnN)] SELECT column1, column2,
…columnN FROM second_table_name [WHERE condition];

The basic syntax of SELECT statement is as follows:

SELECT column1, column2, columnN FROM table_name;

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:

SELECT * FROM table_name;

SQL> SELECT ID, NAME, SALARY FROM CUSTOMERS;

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

comparisons with different operators in the same SQL statement.

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.

Syntax: The basic syntax of OR operator with WHERE clause is as follows:

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.

SQL> UPDATE CUSTOMERS SET ADDRESS = ‗Pune‘ WHERE ID = 6;

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:

SQL> DELETE FROM CUSTOMERS;


The SQL DISTINCT keyword is used in conjunction with SELECT statement to eliminate all the duplicate records and
fetching only unique records.

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:

DATA DEFINITION LANGUAGE (DDL) QUERIES

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‖.

Data Definition Language (DDL) are used different statements :

CREATE – to create objects in the database

ALTER – alters the structure of the database

DROP – delete objects from the database

TRUNCATE – remove all records from a table, including all spaces allocated for the records are removed

COMMENT – add comments to the data dictionary

RENAME – rename an object

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.

Display a list of your available databases: Enter the command

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:

insert into instructor values (10211, ‘Smith‘, ‘Biology‘, 66000);

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

alter table r add AD;

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

alter table r drop A;

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.

create view v as <query expression>;

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:

Drop view viewname;

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.

CREATE UNIQUE INDEX index_name ON table_name ( column1, column2,…);

You can use one or more columns to create an index. For example, we can create an index on table student using column
rno

CREATE UNIQUE INDEX RNO_INDEX ON student (rno);

CREATE UNIQUE INDEX RNO_INDEX ON student (rno DESC);

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.

ALTER TABLE student DROP INDEX (id);

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.

 create table sonali(id int primary key auto_increment, name varchar(20));


 create table sonali(id int primary key auto_increment = 10, name varchar(20));
Summary of commands :

Creating View, replacing or updating view and dropping view

 Create view view1 as select * from emp;


 Create or replace view1 as select * from emp1;
 Drop view view1;

Crating sequence and inserting values

• create table sonali(id int primary key auto_increment, name varchar(20));


• create table sonali(id int primary key auto_increment = 10, name varchar(20));
• insert into sonali(name) values(‗a‘),(‗b‘),(‗c‘);
• insert into sonali values(NULL,‘sonali‘);
• insert into sonali(name) values(‗sonali‘);
Creating index create index id1 on sonali(id)

create index id1 on sonali(id desc)

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:

1. Create following Tables

cust_mstr(cust_no,fname,lname)

add_dets(code_no,add1,add2,state,city,pincode)

Retrieve the address of customer Fname as 'xyz' and Lname as 'pqr'

2.Create following Tables

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

3. Create following Tables

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

4. Create following Tables

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

5. Create following Tables

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

update delete operations

THEORY:

JOINs : allow us to query this data in a number of ways.


INNER JOIN (or just JOIN)

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:

SELECT user.name, course.name


FROM `user`
INNER JOIN `course` on user.course = course.id;

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):

SELECT user.name, course.name


FROM `user`
LEFT JOIN `course` on user.course = course.id;
Result:

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):

SELECT user.name, course.name


FROM `user`
RIGHT JOIN `course` on user.course = course.id;

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:

SELECT user.name, course.name


FROM `course`
LEFT JOIN `user` on user.course = course.id;

We could, for example, count the number of students enrolled on each course:

SELECT course.name, COUNT(user.name)


FROM `course`
LEFT JOIN `user` ON user.course = course.id
GROUP BY course.id;
Result:

course.name count()
HTML5 2
CSS3 1
JavaScript 0
PHP 0
MySQL 1

OUTER JOIN (or FULL OUTER JOIN)

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.

SELECT user.name, course.name


FROM `user`
LEFT JOIN `course` on user.course = course.id

UNION

SELECT user.name, course.name


FROM `user`
RIGHT JOIN `course` on user.course = course.id;

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

MariaDB [(none)]> use tej;


Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

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 *from deptid;


+--------+----------+---------------------+--------+
| name | location | eastablishment_date | intake |
+--------+----------+---------------------+--------+
| Tejas | 5 | 20 | 80 |
| Anuj | 5 | 20 | 80 |
| Shifa | 6 | 26 | 70 |
| Sakshi | 5 | 20 | 80 |
+--------+----------+---------------------+--------+
4 rows in set (0.00 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)

MariaDB [tej]> select *from siddd where deptid='Comp';


+------+--------+--------+--------+-------+-------+------+---------+ |
Rno | name | deptid | shift | class | marks | DOB | Address | +-----
-+--------+--------+--------+-------+-------+------+---------+
| 8 | Sakshi | Comp | second | TE | 89 | 1997 | Pune | | 49 | Anuj
| Comp | second | TE | 45 | 1997 | Pimpri | | 43 | Tejas | Comp |
second | TE | 78 | 1997 | Pune |
+------+--------+--------+--------+-------+-------+------+---------+ 3
rows in set (0.00 sec)

MariaDB [tej]> select count(*) as totalcount from siddd where deptid='Comp';


+------------+
| totalcount |
+------------+
|3|
+------------+
1 row in set (0.01 sec)

MariaDB [tej]> create view stud_view as select Rno,name,deptid from siddd;


ERROR 1050 (42S01): Table 'stud_view' already exists
MariaDB [tej]> select *from stud_view;
+------+--------+--------+
| Rno | name | deptid |
+------+--------+--------+
| 8 | Sakshi | Comp |
| 45 | Shifa | IT |
| 49 | Anuj | Comp |
| 43 | Tejas | Comp |
+------+--------+--------+
4 rows in set (0.00 sec)
MariaDB [tej]>

Conclusion:-Thus we have successfully implemented JOINS, VIEWS in mysql


Assignment No. 4
TITLE: A PL/SQL block of code (Use of Control structure and Exception handling)

OBJECTIVE: To write a PL/SQL block of code using Control structure and Exception handling.

PROBLEM STATEMENT:

1. Consider table Stud(Roll, Att,Status)

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.

3. 1. Borrower(Roll_no, Name, Date_of_Issue, Name_of_Book, 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, 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.

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.

Why Stored Procedures?

• 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.

• Applications that are written in PL/SQL languages are portable.

• this provides high security level.

• It also provides access to the predefined SQL packages.

• It also supports for Object-oriented programming.


• It provides support for developing web applications and server pages.
Syntax and types of PL/SQL blocks

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;

The 'Hello World' Example


DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN
dbms_output.put_line(message);
END;
/
The end; line signals the end of the PL/SQL block. To run the code from the SQL command line, you may need to type /
at the beginning of the first blank line after the last line of the code. When the above code is executed at the SQL prompt,
it produces the following result −
Hello World

PL/SQL procedure successfully completed.

Syntax and types of Exception handling:

Following is a general syntax for exception handling:

DECLARE

<declarations section>

BEGIN

<executable command(s)>

EXCEPTION

<exception handling goes here >

WHEN exception1 THEN

exception1-handling-statements

WHEN exception2 THEN

exception2-handling-statements

WHEN exception3 THEN


exception3-handling-statements

........

WHEN others THEN

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

Procedure and Stored Function.

PROBLEM STATEMENT:

1. Write a PL/SQL stored Procedure for following requirements and call the procedure in

appropriate PL/SQL block.

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.

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

account details in active_acc_details table, otherwise display message on screen “account is

inactive”.

3. 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)
THEORY:

Syntax of Stored procedure and function

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:

CREATE [DEFINER = { user | CURRENT_USER }]


PROCEDURE sp_name ([proc_parameter[,...]])
[characteristic ...] routine_body
proc_parameter: [ IN | OUT | INOUT ] param_name type
type:
Any valid MySQL data type
characteristic:
COMMENT 'string'
| LANGUAGE SQL
| [NOT] DETERMINISTIC
| { CONTAINS SQL | NO SQL | READS SQL DATA
| MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }
routine_body:
Valid SQL routine statement

Check the MySQL version:

Following command displays the version of MySQL :

mysql>SELECT VERSION();
+-----------+
| VERSION() |
+-----------+
| 5.6.12 |
+-----------+
1 row in set (0.00 sec)

Check the privileges of the current user:

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.

mysql> SHOW PRIVILEGES;

Select a database:

Before creates a procedure we must select a database. Let see the list of databases and choose one of them.

mysql> SHOW DATABASES;


+--------------------+
| Database |
+--------------------+
| information_schema |
| hr |
| mysql |
| performance_schema |
| sakila |
| test |
| world |
+--------------------+
7 rows in set (0.06 sec))

Now select the database 'hr' and list the tables :

mysql> USE hr;


Database changed
mysql> SHOW TABLES;

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> SELECT * FROM user $$


+----------+-----------+--------+
| userid | password | name |
+----------+-----------+--------+
| scott123 | 123@sco | Scott |
| ferp6734 | dloeiu@&3 | Palash |
| diana094 | ku$j@23 | Diana |
+----------+-----------+--------+
3 rows in set (0.00 sec) Now execute the following command to resume ";" as a delimiter :

mysql> DELIMITER ; $$

Example : MySQL Procedure

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.

mysql> DELIMITER $$ ;mysql> CREATE PROCEDURE job_data()


> SELECT * FROM JOBS; $$
Query OK, 0 rows affected (0.00 sec)

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.

mysql> CALL job_data$$


+------------+---------------------------------+------------+------------+
| JOB_ID | JOB_TITLE | MIN_SALARY | MAX_SALARY |
+------------+---------------------------------+------------+------------+
| AD_PRES | President | 20000 | 40000 |
| AD_VP | Administration Vice President | 15000 | 30000 |
| AD_ASST | Administration Assistant | 3000 | 6000 |
| FI_MGR | Finance Manager | 8200 | 16000 |
| FI_ACCOUNT | Accountant | 4200 | 9000 |
| AC_MGR | Accounting Manager | 8200 | 16000 |
| AC_ACCOUNT | Public Accountant | 4200 | 9000 |
| SA_MAN | Sales Manager | 10000 | 20000 |
| SA_REP | Sales Representative | 6000 | 12000 |
| PU_MAN | Purchasing Manager | 8000 | 15000 |
| PU_CLERK | Purchasing Clerk | 2500 | 5500 |
| ST_MAN | Stock Manager | 5500 | 8500 |
| ST_CLERK | Stock Clerk | 2000 | 5000 |
| SH_CLERK | Shipping Clerk | 2500 | 5500 |
| IT_PROG | Programmer | 4000 | 10000 |
| MK_MAN | Marketing Manager | 9000 | 15000 |
| MK_REP | Marketing Representative | 4000 | 9000 |
| HR_REP | Human Resources Representative | 4000 | 9000 |
| PR_REP | Public Relations Representative | 4500 | 10500 |
+------------+---------------------------------+------------+------------+
19 rows in set (0.00 sec)Query OK, 0 rows affected (0.15 sec)

SHOW CREATE 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 :

SHOW CREATE PROCEDURE proc_name

Let execute the above and see the output :

mysql> SHOW CREATE PROCEDURE job_data$$

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

FOR Loop, Parameterized 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.

(Use of %FOUND, %NOTFOUND, %ROWCOUNT)

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

record for the same is maintained in the increment_salary table.

EMP (E_no , Salary)

increment_salary(E_no , Salary)

3. Write PL/SQL block using explicit cursor 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.

create table stud21(roll number(4), att number(4), status varchar(1));

create table d_stud(roll number(4), att number(4));

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

new table dept_salary(d_no, Avg_salary)

EXPLICIT CURSOR: Cursor for loop

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.

create table stud21(roll number(4), att number(4), status varchar(1));

create table d_stud(roll number(4), att number(4));

THEORY:

What is cursor? Cursor types

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.

Cursor Status variables and its use

S.No Attribute & Description

%FOUND

1 Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more


rows or a SELECT INTO statement returned one or more rows. Otherwise, it returns
FALSE.

%NOTFOUND

2 The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or


DELETE statement affected no rows, or a SELECT INTO statement returned no rows.
Otherwise, it returns FALSE.

%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.

Syntax - use of Implicit cursor status variables

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

PL/SQL procedure successfully completed.


If you check the records in customers table, you will find that the rows have been updated −
Select * from customers;

+----+----------+-----+-----------+----------+
| 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 for initializing the memory


 Opening the cursor for allocating the memory
 Fetching the cursor for retrieving the data
 Closing the cursor to release the allocated memory

Declaring the Cursor

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

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

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

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

PL/SQL procedure successfully completed.

Explicit cursor management

1 : Declare Cursor
The first step is to declare the cursor using the below SQL statement:

DECLARE cursor_name CURSOR


FOR select_statement;
We can declare a cursor by specifying its name with the data type CURSOR after the DECLARE keyword. Then, we will
write the SELECT statement that defines the output for the cursor.

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:

FETCH NEXT FROM cursor INTO variable_list;


We can also use the @@FETCHSTATUS function in SQL Server to get the status of the most recent FETCH statement
cursor that was executed against the cursor. The FETCH statement was successful when the @@FETCHSTATUS gives
zero output. The WHILE statement can be used to retrieve all records from the cursor. The following code explains it
more clearly:

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

triggers, Before and After Triggers).

OBJECTIVE: To write a PL/SQL code using Database Trigger (All Types: Rowlevel and

Statement level triggers, Before and After Triggers).

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:

Emp(e_no, e_name, salary)

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).

3. Write a Database trigger for following requirements:

Employee salary of last three month is stored in the emp_sal table.

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

new table emp_new(emp_no, avg_sal).

Theory:

Database Trigger – explanation

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:

o We cannot manually execute/invoked triggers.


o Triggers have no chance of receiving parameters.
o A transaction cannot be committed or rolled back inside a trigger.

Syntax of Trigger

We can create a trigger in SQL Server by using the CREATE TRIGGER statement as follows:

1. REATE TRIGGER schema.trigger_name


2. ON table_name
3. AFTER {INSERT, UPDATE, DELETE}
4. [NOT FOR REPLICATION]
5. AS
6. {SQL_Statements}

The parameter descriptions of this syntax illustrate below:

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.

When we use triggers?

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.

Example of Trigger in SQL Server

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:

Example - all types

1. CREATE TABLE Employee


2. (
3. Id INT PRIMARY KEY,
4. Name VARCHAR(45),
5. Salary INT,
6. Gender VARCHAR(12),
7. DepartmentId INT
8. )

Next, we will insert some record into this table as follows:

1. INSERT INTO Employee VALUES (1,'Steffan', 82000, 'Male', 3),


2. (2,'Amelie', 52000, 'Female', 2),
3. (3,'Antonio', 25000, 'male', 1),
4. (4,'Marco', 47000, 'Male', 2),
5. (5,'Eliana', 46000, 'Female', 3)

We can verify the insert operation by using the SELECT statement. We will get the below output:

1. SELECT * FROM Employee;

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

method, logical operators etc)

PROBLEM STATEMENT:

1.Create Database PCCOE

2. Create following Collections

Teachers(Tname,dno,dname,experience,salary,date_of_joining )

Students(Sname,roll_no,class)

3. Find the information about all teachers

4. Find the information about all teachers of computer department

5. Find the information about all teachers of computer,IT,and e&TC department

6. Find the information about all teachers of computer,IT,and E&TC department having salary greater than

or equal to 10000/-

7. Find the student information having roll_no = 2 or Sname=xyz

8. Update the experience of teacher-praveen to 10years, if the entry is not available in database consider

the entry as new entry.

9. Update the deparment of all the teachers working in IT department to COMP

10. find the teachers name and their experience from teachers collection

11. Using Save() method insert one entry in department collection

12. Using Save() method change the dept of teacher praveen to IT

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 Databases - Explanation, example

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.

Difference between NOSQL and RDBMS

Relational Database NoSQL


It is used to handle data coming in low It is used to handle data coming in high
velocity. velocity.
It gives only read scalability. It gives both read and write scalability.
It manages structured data. It manages all type of data.
Data arrives from one or few locations. Data arrives from many locations.
It supports complex transactions. It supports simple transactions.
It has single point of failure. No single point of failure.
It handles data in less volume. It handles data in high volume.
Transactions written in one location. Transactions written in many locations.
Deployed in vertical fashion. Deployed in Horizontal fashion.

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

databases in these areas.

 MongoDB is a proven solution for a wide range of business requirements to companies across numerous

industries.

All CRUD Operations - use, syntax, example

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. Create Table Command :


Syntax :

CREATE TABLE table_name (column_name column_type constraints);


Parameters :

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 –

 name Varchar(30) NOT NULL


 marks Integer
Example :
use <database> command must be used before any operation on the table.

use gfg;
Create table student(name Varchar(30) NOT NULL, marks Integer);
Output :

Field Type Null Default


name varchar(30)No Null
marksint(11) YESNull
2. Read Operation :
The Read operations are used to retrieve the content of the table from a particular database. Read operation is done by
DDL commands.
Example :

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 –

1. Alter Table Command –


This is the DDL command (Data Definition Language) used to change the structure of the table.

2. Update Table Command –


This is the DML command(Data Manipulating Language) used to alter the records.

Alter Table Command that change the size of name column from varchar(40) to varchar(50) for the Student table :

Alter table student


modify name varchar(50) not null;
Original Table –

desc student;
Field Type Null Default
name varchar(40) YES Null
marks int(11) YES Null

After altering the table –

desc student;

Field Type Null Default


name varchar(50) YES Null
marks int(11) YES Null

Update Command that update the marks of the student from 23 to 100 whose name is ravi using the update command :

Update student set marks = 100


where name = "ravi";
Original Table –

select * from student;


namemarks
ravi 23
swati 33
kranti 12
After updating the table –

select * from student;


namemarks
ravi 100
swati 33
kranti 12
4. Delete Operation :
Two commands are mostly used for the Delete operations –

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 –

select * from student;


namemarks
ravi 100
swati 33
kranti 12
After deleting the student records –

select * from student;

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

Develop an application with following details:

1. Follow the same problem statement decided in Assignment-1 of Group A.

2. Follow the Software Development Life cycle and other concepts learnt in Software Engineering

Course throughout the implementation.

3. Develop application considering:

Front End: Python/Java/PHP/Perl/Ruby/.NET/ or any other language

Backend : MongoDB/ MySQL/ Oracle / or any standard SQL / NoSQL database

4. Test and validate application using Manual/Automation testing.

5. Student should develop application in group of 2-3 students and submit the Project Report which will

consist of documentation related to different phases of Software Development Life Cycle:

Title of the Project, Abstract, Introduction

Software Requirement Specification (SRS)

Conceptual Design using ER features, Relational Model in appropriate Normalize form

Graphical User Interface, Source Code

Testing document

Conclusion.
ASSIGNMENT (Beyond Syllabus)

DATA Analytical Tools


 Data analytics is the process of gleaning insights from data that is extracted, transformed, and centralized
to discover and analyze hidden patterns, relationships, trends, correlations, and anomalies, or to validate a
theory or hypothesis.

 In the past, data was analyzed to make future decisions.

 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.

BENEFITS OF DATA ANALYTICS

List Of Analytical Tools:

following Data Analytics Tools:

 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.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy