Dbms Merged Notes
Dbms Merged Notes
Types of databases
1.SQL databases
In SQL database to manage data the query language is used, Structured Query Language
Types of statements
student
Keys in databases
1. Primary key: minimal set of columns which identifies the row uniquely , are called as
primary key.
student
corse
student-marks
Room
movie management
2. Candidate key:
All possible minimal combinations, that may become primary key, are called as candidate key,
3. unique key--- any single column, which has unique values, is called as unique key
it can contain more than one null values, but not null values will be unique.
4. foreign key--- if we want to enter valid data in a column, and for that we may need to
refer primary key of other table, or primary key of same table, then it is called as foreign
key
5. Alternate key
all candidate keys, which are not selected as primary key are called as alternate key
6. super key
any combination of the columns which identifies the uniquely is called as super key
to install mysql
https://dev.mysql.com/downloads/installer/
where hiredate='1982-12-09';
5. To list all employees with sal < 3000 and name =smith
select * from emp
where sal < 3000 and name=’smith’;
6. To list all employees with sal >= 1300 and <=3000
select * from emp where sal between 1300 and 3000
Arithmetic operators
+, -, *, / , %
Logical operators
Relational operators
[not] between whenever you want to check range of select * from emp where
…and values, the use between…and operator, sal between 1300 and
the values we use are inclusive 3000
[not] in when you want to check multiple values select * from emp where
in single column, then use in sal in(1300,2000,3000)
is [not] null this operator will check for the null select * from emp
values where comm is null;
[not] like like operators will allow you to design select *
patterns from emp
to design patterns we use % and _ where ename like ‘A%’
% matches with 0 or more characters select *
_ matches with 1 character from emp
where ename like ‘_A%’
7. To list all employees with sal not > 1300 and <3000
select * from emp where sal not between 1300 and 3000
10. to list all employees with sal is either 1300, 2500 or 3000
select * from emp where sal in (1300,2500,300)
11. to list all employees working as either clerk or manager or analyst
select * from emp where job in (‘CLERK’,’MANAGER’,’ANALYST’)
12. to list all employees not working as either clerk or manager or analyst
select * from emp where job not in ('CLERK','MANAGER','ANALYST');
13. To list all employee with comm is null
select * from emp
where comm is null;
14. To list all employees with name starts with either m or starts with J
select * from emp where ename like ‘M%’ or ename like ‘J%’
15. list all employees with name starts with A and E at second last position.
select * from emp where ename like ‘A%E_’
16. list all employees with name starts with either A or M and ends with either N or R
select * from emp where ename like ‘A%N’ or ename like ‘M%R’ or ename like 'A%R’ or
ename like 'M%N
17. list all employees with either N at second position or N at third position.
select * from emp where ename like ‘_N%’ or ename like ‘__N%’
REGEXP
. to match any one character
[a-zA-Z] it matches with alphabets
[0-9] it matches with any one digit
* matches the preceding pattern for 0 or more times
+ matches the preceding pattern for 1 or more times
? matches the preceding pattern for 0 or one times
{m} exactly m occurrences
{m,n} it matches with minimum m and maximum n occurrences
{m,} it matches with minimum m and maximum any number of
occurrences
^ it matches the pattern at the beginning of the string
$ it matches the pattern at the end of the string
[^a-z] it matches with any character except a-z
(abc|pqr|mnx) it matches with any one pattern abc or pqr or mnx
4. To list all employees with name starts with either m or starts with J
select * from emp where ename like ‘M%’ or ename like ‘J%’
select * from emp where ename REGEXP ‘^[MJ]’
5. list all employees with name starts with A and E at second last position.
select * from emp where ename like ‘A%E_’
select * from emp where ename regexp '^A.*E.$’
6. list all employees with name starts with either A or M and ends with either N or R
select * from emp where ename like ‘A%N’ or ename like ‘M%R’ or ename like 'A%R’ or
ename like 'M%N
select * from emp where ename regexp ‘^[AM].*[NR]$’;
10.
to display unique values of a column
select distinct job from emp; It will display unique values
from job column
select distinct job,mgr from It will display unique
emp; combination of job and mgr
3. to arrange data in descending order of salary, if salary is same then arrange on ename
select * from emp order by sal desc, ename
4. to arrange data in descending order of salary, if salary is same then arrange on ename in
descending order
select * from emp order by sal desc, ename desc
examples
1. display sum of sal and min sal for all employees
select sum(sal), max(sal) from emp
5. find sum of sal, sum of netsal, net sal= sal+comm for each department
select deptno,sum(sal),sum(sal+ifnull(comm,0))
from emp
group by deptno
select deptno,mgr,sum(sal),avg(sal),count(*)
from emp
group by deptno,mgr
partition by clause allows you to display columns which are not involved in group by.
From emp
select ename
select ename
select empno,ename,concat(substr(ename,1,3),’.’,substr(job,length(job)-
3,3),”@mycompany.com”)
3. display ename, every ename length should be 12, add extra required number of * on
the right side
select empno,ename,rpad(ename,12,’*’)
from emp;
select medid,mname,mfgdate
from medicine
where datediff(curdate(),mfgdate)>=90
or
select medid,mname,mfgdate
from medicine
where date_sub(curdate(),interval 3 month)>=mfgdate -------better aproach
2. display expiry date of medicines if it is after 6 months 7 days from mfg date
select medid,mname,mfgdate,date_add(date_add(mfgdate,interval 6 month)
,interval 7 day)
from medicine
3. find all employees joined in dec 1981
7. Write a query to get the distinct Thursday from hiredate in emp table.
select distinct hiredate,dayname(hiredate)
-> from emp
-> where dayname(hiredate)='Thursday';
8. find a particular string occurs how many times in the given string
“saaavaaadaaa” find aaa appears how many times in the given string
saaavaaadaaa 12
svd-----------------3
select floor((length("saaataaayaaa")-
length(replace("saaataaayaaa","aaa","")))/length("aaa"));
case statement
When you want to display some data, based on condition, then we use case
statement
in case statement all the values that you are displaying should be of same type
case when condition then o/p
when condition then o/p
else o/p end alias_name
Table: Boxoffice
Movie_id Rating Domestic_sales International_sales
5 8.2 380843261 555900000
14 7.4 268492764 475066843
8 8 206445654 417277164
12 6.4 191452396 368400000
3 7.9 245852179 239163000
6 8 261441092 370001000
• String Types.
MySQL uses all the standard ANSI SQL numeric data types, so if you're coming to MySQL from a
different database system, these definitions will look familiar to you. The following list shows
the common numeric data types and their descriptions −
• INT − A normal-sized integer that can be signed or unsigned. If signed, the allowable
range is from -2147483648 to 2147483647. If unsigned, the allowable range is from 0 to
4294967295. You can specify a width of up to 11 digits.
• TINYINT − A very small integer that can be signed or unsigned. If signed, the allowable
range is from -128 to 127. If unsigned, the allowable range is from 0 to 255. You can
specify a width of up to 4 digits.
• SMALLINT − A small integer that can be signed or unsigned. If signed, the allowable
range is from -32768 to 32767. If unsigned, the allowable range is from 0 to 65535. You
can specify a width of up to 5 digits.
• BIGINT − A large integer that can be signed or unsigned. If signed, the allowable range is
from -9223372036854775808 to 9223372036854775807. If unsigned, the allowable
range is from 0 to 18446744073709551615. You can specify a width of up to 20 digits.
• FLOAT(M,D) − A floating-point number that cannot be unsigned. You can define the
display length (M) and the number of decimals (D). This is not required and will default
to 10,2, where 2 is the number of decimals and 10 is the total number of digits (including
decimals). Decimal precision can go to 24 places for a FLOAT.
• TIMESTAMP − A timestamp between midnight, January 1st, 1970 and sometime in 2037.
This looks like the previous DATETIME format, only without the hyphens between
numbers; 3:30 in the afternoon on December 30th, 1973 would be stored as
19731230153000 ( YYYYMMDDHHMMSS ).
• YEAR(M) − Stores a year in a 2-digit or a 4-digit format. If the length is specified as 2 (for
example YEAR(2)), YEAR can be between 1970 to 2069 (70 to 69). If the length is
specified as 4, then YEAR can be 1901 to 2155. The default length is 4.
String Types
Although the numeric and date types are fun, most data you'll store will be in a string format.
This list describes the common string datatypes in MySQL.
• CHAR(M) − A fixed-length string between 1 and 255 characters in length (for example
CHAR(5)), right-padded with spaces to the specified length when stored. Defining a
length is not required, but the default is 1.
• BLOB or TEXT − A field with a maximum length of 65535 characters. BLOBs are "Binary
Large Objects" and are used to store large amounts of binary data, such as images or
other types of files. Fields defined as TEXT also hold large amounts of data. The
difference between the two is that the sorts and comparisons on the stored data are
case sensitive on BLOBs and are not case sensitive in TEXT fields. You do not specify a
length with BLOB or TEXT.
constraints
Not null field level It does not allow to add null
values in the table
) primary key(studid,cname),
on delete cascade
on update cascade
)
cname varchar(20),
description varchar(30))
pname varchar(20),
qty int,
catid int,
on update cascade)
on delete (action)
on update (action)
action values.
cascade if delete from parent table, then delete matching rows from child table,
if update from parent table, then change the value is child table also
set null if delete from parent table, then set value to null in matching rows from child
table,
if update from parent table, then set value to null in matching rows in child
table
no action if on delete and on update clause is not used, then values from the parent
table can be deleted only if, the corresponding value does not exists in the
child table
DML statements
insert insert into <table> values(<values for all insert into mytable
columns>) values(12,’xxx’,’pune’)
insert into<table>(list of columns) values( insert into mytable(id,name)
<values for specified columns>) values(13,’yyy’)
update update <table> update mytable
set fiedl1=val1,field2=val2, ……. set name=’ccc’,addr=’yyy’
where <condition> where id=12
if where cluse is not used then it will update all
the rows
delete delete from <table> delete from mytable
where <condition> where id=12
if where cluse is not used then it will delete all
the rows
to insert INSERT INTO tbl_name insert into
multiple (a,b,c) salesman(sid,sname,address)
rows in a VALUES values(11,'xxx','Pune'),
(1,2,3),
table (12,'yyy','pune'),
(4,5,6),
(7,8,9); (13,'zzzz','mumbai');
to delete the table ----drop table will delete all the rows and will also delete table from the
databse
truncate table <table name>---it will delete all the rows from the table, but keep empty table as
it is.
set autocommit=0;
To set autocommit on
set autocommit=1;
Trucate table
Tucate delete
it is a DDL, so it is autocommit it is dml statement, changes need to
commited
rollback is not possible rollback is possible
we can not use where cluse where clause can be used
alter table
rename the column alter table <table name> alter table mytable
CHANGE COLUMN old_name change location mylocation
new_name varchar(50)
column_definition
FOREIGN KEY(properties)
REFERENCES Properties(ID)
create owner table to store (ownerid, oname,address)
select *
from emp
where deptno=( select deptno
from emp
where ename=’smith’
);
nested queries
1. simple nested query
when output of one query is dependent on output of another query, then we use nested
query,
outer query is called as parent query, and inner query is called s child query
if the child query is not dependent on parent query data, then it is called as simple
query.
2. co related query
when output of one query is dependent on output of another query, then we use nested
query,
outer query is called as parent query, and inner query is called s child query
if the child query is dependent on parent query data, then it is called as co-related query.
examples
1. to list all employees with sal < avg(sal) of departmrnt 10?
select * from emp
where sal < (select avg(sal)
from emp
where deptno=10)
2. display all employees who are working in ward’s department
select * from emp
where deptno=(select deptno
from emp
where ename=’ward’)
3. to list all employees with sal < avg sal of wards department
select *
from emp
where sal <(select avg(sal)
from emp
where deptno=(select deptno
from emp
where ename=’ward’))
4. to display all employees with sal > smith’s sal and jones sal
select *
from emp
where sal > all(select sal
from emp
where ename in(‘smith’,’jones’))
5. to display all employees with sal > either smith’s sal or jones sal
select *
from emp
where sal > any(select sal
from emp
where ename in(‘smith’,’jones’))
6. to display all employees who are working either smith’s dept or jones dept
select *
from emp
where deptno in (select deptno
from emp
7. to find all employees with sal < avg sal of its own department
select *
from emp e
from emp m
where m.deptno=e.deptno)
8. to find all employees whose sal < its own mgr sal
select *
from emp e
where sal <(select sal
from emp m
where m.empno=e.mgr)
select *
from emp e
from dept
where dname=’Accounting’)
11. display all employees who are not mgr of any employee
select *
from emp e
where not exists (select *
from emp m
where m.mgr=e.empno)
12. list all faculties who are not assigned to any course
select * from faculty f
where not exists (select * from course c where f.fid=c.fid)
13. list all faculties who are assigned to some course
select * from faculty f
where exists (select * from course c where f.fid=c.fid)
14. list all rooms which are not assigned to any course.
select * from room r
where not exists (select * from course c where r.rid=c.rid)
select *
from course
where rid is null
16. update sal of smith to jones sal+2000
update emp
set sal=(select sal from emp where ename=’jones’)+2000
where ename=’smith’
17. delete all records who are working in either smiths dept or jones dept
delete from emp
where deptno in (select deptno
from (select * from emp ) e
where e.ename in (‘smith’,’jones’))
18. create table emp_10
as
(select * from emp
where deptno=10)
21 . list all employees who are working in jones dept and sal >2000
1. When you want to display values from more than one table then use joins
2. if we are joining n tables then minimum n-1 join conditions are needed
Types of joins
cross join when every row in the table emp is joined with every row from
other table, then it is called as crossjoin
inner join If we add join condition in the join query, then it is called as
1. equi join inner join
2. non equi join 1.if the condition is based on = sign then it is called as equi
3. self join join
2. if the condition is based on operator other than = then, it is
called as non equijoin
3. If in inner join we combine a table with itself, then it is
called as self join
outer join when you want to retrieve matching as well as non matching
1. left outer join rows from multiple tables then use outer join
2. right outer 1. if we want nonmatching rows from the table which is
join on the left side in from clause, then use left outer join
3. full outer join 2. if we want nonmatching rows from the table which is
on the right side in from clause, then use right outer
join
3. if we want nonmatching rows from both side tables
then use full outer join, to use full outer join we need
to write union query in mysql.
select select
e.empno,e.deptno,d.dname e.empno,e.deptno,d.dname
from emp e inner join dept d
from emp e, dept d
on e.deptno=d.deptno;
where e.deptno=d.deptno;
select select
e.empno,e.deptno,d.dname e.empno,e.deptno,d.dname
from emp e inner join dept d on
from emp e, dept d
e.deptno=d.deptno
where sal>2000;
where e.deptno=d.deptno
and sal>2000;
where e.deptno=d.deptno
and e.deptno in (10,20)
select cid,cname,fname,rname
9. to list all employee name and department name , along with departments which do
not have any employee
select select
empno,ename,e.deptno,d.dept empno,ename,e.deptno,d.dept
no,dname no,dname
from dept d left join emp e on from emp e right join dept d on
e.deptno=d.deptno; e.deptno=d.deptno;
10. find all the employees name and department name, also display employees for
whom no dept is assigned, and also display departments in which no employee is
there?
select empno,ename,e.deptno,d.deptno,d.dname
from emp e left join dept d on e.deptno=d.deptno
union
select empno,ename,e.deptno,d.deptno,d.dname
from emp e right join dept d on e.deptno=d.deptno;
11. to display course name and faculty name, for all courses, and also display faculty
names which are not assigned to any course
select cid,cname,fname
from course c right join faculty f on c.fid=f.fid;
12. to display course name and room name, for all courses, and also display room
names which are not assigned to any course
select cid,cname,rname
from course c right join room r on c.rid=r.rid;
13. to display course name and faculty name, for all courses, and also display faculty
names which are not assigned to any course, and also display courses for which no
faculty is assigned.
select cid,cname,fname
from course c right join faculty f on c.fid=f.fid
union
select cid,cname,fname
from course c left join faculty f on c.fid=f.fid;
14. to display all employees, who are not assigned to any department, and all
departments in which no employees are assigned
select e.empno,e.ename,e.deptno,d.deptno,dname
from emp e left join dept d on e.deptno=d.deptno
where d.dname is null
union
select e.empno,e.ename,e.deptno,d.deptno,dname
from emp e right join dept d on e.deptno=d.deptno
where e.ename is null;
15. to display course name for which no faculty is assigned and display all faculty
names which are not assigned to any course,
select cid,cname,fname
union
select cid,cname,fname
16. find all employees for which no dept is assigned and all department for which no
employee is assigned
select empno,ename,e.deptno,d.deptno,d.dname
from emp e right join dept d on e.deptno=d.deptno
where e.ename is null
union
select empno,ename,e.deptno,d.deptno,d.dname
from emp e left join dept d on e.deptno=d.deptno
where d.dname is null;
17. find all faculties which are not assigned to any course and find all rooms which are
not assigned to any course
union
select c.cid,c.cname,null,null,r.rid,r.rname
Table: Movies
Id Title Director Year Length_minutes Release date
1 Toy Story John Lasseter 1995 81
2 A Bug's Life John Lasseter 1998 95
3 Toy Story 2 John Lasseter 1999 93
4 Monsters, Inc. Pete Docter 2001 92
5 Finding Nemo Andrew Stanton 2003 107
6 The Incredibles Brad Bird 2004 116
year >1970
title varchar(20),
director varchar(20),
Table: Boxoffice
Movie_id Rating Domestic_sales International_sales
5 8.2 380843261 555900000
14 7.4 268492764 475066843
8 8 206445654 417277164
12 6.4 191452396 368400000
3 7.9 245852179 239163000
6 8 261441092 370001000
9 8.5 223808164 297503696
Views in myasql
to restrict the dml operation via view use with check option
-> as
as
where deptno=10
When you want to provide limited access to the existing data, then we create views
1. views
a. for view no separate memory is allocated for storing data, it only stores the base
query.
b. only base query will be stored, and any statement on the view will use base query
to get the data, because of that we always get UpToDate data in view
c. if view contains all not null columns of the single base table and if it is not read
only view, then we can use all DML operation(insert, delete, update) on the view
d. if the view is based on joins, aggregate functions, group by statement or union of
multiple queries, then by default the views are readonly
uses of views:
1. Hide complexity of the queries ( joins, aggregate functions nested queries)
2. To give restricted access to few columns or rows from tables
3. Hide table names, to increase the security of data.
2. Materialized view
a. Views for which the first time the base query will get executed and then the
output will be stored in a temporary table in RAM, within the session, the data will
be retrieved from the RAM
b. you may not get uptodate data in materialized view.
c. When your data is history data/ non changeable data, then use materialized view
as
to drop view
select *
select *
select *
1. clutsered index-→
a. there is only one clustered index,
b. it is stored along with table data,
c. it does not require extra space to store index file
d. the data is stored in the sorted order based on clustered index
2. non clusterd index→
• it is stored outside the table,
• there can be any number of non clustered index files,
• every index file stores, key and the position in the table
1. primary key index- when we add primary key constraint in the table, this index is
automatically created, data in the table is sorted based on this index
2. unique index- When you add unique constraint in the table, unique index is
automatically gets creates, it does not allow to add duplicate not null values in the
column.
if unique constraint is not assigned in the table, but if you create unique index then also
duplicate values will not be allowed in the column
3. full text index---usually it is used on tex/tinytex/mediumtext/longtext columns, in which
we need to search jargons, then use full text indexes, usually these are used in search
engines.
4. regular index---if you create a index on a table, then it is regular index
5. spatial index---- if the geolocationof data is stored in the table, then we use spatial
indexes.
6. descending index---while creating indexes if you use desc keyword then those indexes
are called as descending indexes.
to create index
on emp(sal)
to drop index
to find which indexes are used by the query or to suggest using of which indexes in query
EXPLAIN SELECT *
FROM
customers
WHERE
write a command to create descending index on job, if job is same then arrange the data on sal
on emp(job desc,sal)
begin transaction
end transaction
intermediate changes are visible only to the user who is performing the transaction,
these changes will visible to other users, when the transaction is commited
emp
10 records
commit
insert 2
update 1
commit
delete 1
rollback
10 records
commit
insert-3
update 2
savepoint A
delete 1
insert-3
update 2
savepoint B
insert-2
delete 1
rollback to B
----------------------
12 rows
insert -3
delete 1
create table
insert- 4
delete 1
rollback
window functions
select *
where e.drn=1;
lead function will give you the next value within frame, lag function give you previous value with
frame.
select empno,ename,sal,lead(sal,1) over (order by sal) leaddata, lag(sal,2) over (order by sal)
lagdata,first_value(sal) over (order by sal)
procedure any block of code , which has business logic is called as procedure
function any block of code , which has business logic, and returns one values, is
called as functions.
these can be used in select clause and where clause in SQL
triggers any block of code , which has business logic, and gets called on some
users action automatically, then it is called as trigger
exception While executing procedures if any error occurs, we use exceptions
cursors When you want to traverse through all rows one by one, and perform
some action on each row, on by one, then use cursors
1. we can hide table names from the developer of the middleware application, which
increases the security of the database.
2. For a particular task, if we need to execute many queries, then we may wrap these
queries in a procedure, and call the procedure from middleware application, once,
execute all the queries, complete the task and go back, this will reduce the network
traffic, also improves performance efficiency of the middleware application. so it
reduces the interaction between middleware program and database.
3. If any of the query is complex, then we may hide the query inside the procedure
4. Procedures will also reduce the network traffic.
delimiter //
begin
declaration of variable;
statement1;
statement2;
end//
delimiter ;
call <procedurename>();
call insertdept(10,’admin’,’pune’)
2. write a procedure to accept eid, sal and job from user as i/p and update sal and job of
the employee in emp table
delimiter //
create procedure updateemp(eid int,esal float(9,2),ejob varchar(20))
begin
update emp
set sal=esal,job=ejob
where empno=eid;
end//
delimiter ;
call updateemp(7902,6666,’QA’);
delimiter ;
call findjob(7902,@s,@c)
select @s,@c
in above example, select … into statement can be used only inside pl sql blocks, the
select query should return single row as output. number of column names before into
and number of variables after into should be same.
@s and @c are session variables. these variables will remain available till the time you
logout.
4. write a procedure to find number of employees and maximum netsalary for the given
department.
net sal =sal+comm
delimiter //
create procedure findemp(in edid int, out cnt int,out maxsal float(9,2))
begin
select count(*),max(sal+ifnull(comm,0)) into cnt,maxsal
from emp
where deptno=edid;
end//
delimiter ;
call findemp(10,@c,@ms)
set @c=5
call incrementnum(@c)
select @c;
6. write a procedure to display all employees in given department and sal >1500.
delimiter //
create procedure getempdata(in edid int,in esal float(9,2))
begin
select *
from emp
where deptno=edid and sal>esal;
end//
delimiter ;
call getempdata(10,1500);
7. write a procedure to find all employees along with dname with sal>2000
delimiter //
create procedure findempdetails(esal float(9,2))
begin
select empno,ename,sal,e.deptno,dname
from emp e,dept d
where e.deptno=d.deptno and sal >esal;
end//
delimiter ;
call findempdetails(2000);
delimiter //
create procedure getRemark(eid int,out remark varchar(50))
begin
declare vcomm float(9,2) default 0;
select comm into vcomm
from emp
where empno=eid;
if vcomm is null or vcomm=0 then
set remark=’poor performance’;
elseif vcomm<= 300 then
set remark=’ok performance’;
elseif vcomm<= 500 then
set remark=’good performance’;
else
set remark=’excellent performance’;
end if;
end//
end//
delimiter ;
9. write a procedure to find netsal of the given employee and find the remark, if
netsal <1000 “less”
if >=1000 and <2000 then ‘ok’
if netsal >=2000 and < 3000 then ‘good’
otherwise better
display remark inside the procedure
netsal= sal+comm
delimiter //
create procedure findNetsal(eid int,out remark varchar(50))
begin
declare vsal,vcomm,vnetsal float(9,2);
select sal,comm into vsal,vcomm
from emp
where empno=eid;
set vnetsal=vsal+ifnull(vcomm,0);
if vnetsal<1000 then
set remark ='less';
else
set remark='better';
end if;
select eid,vsal,vcomm,vnetsal,remark;
end//
delimiter ;
10. write a procedure getdiscount to find discount % and discounted amount from product
table for the given product
if price < 50 then 3%
if price >=50 and <80 7%
if price >=80 and < 100 8%
otherwise 12%
display pid,pname,price,discount percentage and discount amount
delimiter //
create procedure getdiscount(dpid int, out discount float(4,2))
begin
if vprice<50 then
set discount=0.03;
elseif vprice<80 then
set discount=0.07;
elseif vprice <100 then
set discount=0.08;
else
set discount=0.12;
end if;
select dpid , vpname,vprice,vprice-(vprice*discount),discount;
end//
delimiter ;
In PLSQL there are 3 loops
While expression do This is top tested loop, will repeat statements till the
Statements condition is true
End while;
REPEAT This is bottom tested loop, will repeat statements until the
statements; given condition is false
UNTIL expression
END REPEAT
1. Write a procedure which accepts start and stop values and display all numbers between
start and stop
2. Example displaydata(10,20) o/p 10,11,12,13,14,15……20
Delimiter //
Delimiter //
Begin
Set cnt=start;
While cnt<=stop do
set str=concat(str,cnt,',');
Set cnt=cnt+1;
End while;
set str=substr(str,1,length(str)-1);
Select str;
End//
Delimiter ;Delimiter ;
3. Write a procedure to accept a number from user and display its factorial
Delimiter //
Create procedure displayfactorial(in num int,out fact int)
Begin
Declare start int default 1;
Set fact=1;
While start<=num do
Set fact=fact*start;
Set start=start+1;
End while;
End//
Delimiter //
Begin
Repeat
Set str=concat(str,cnt,',');
Set cnt=cnt+1;
End repeat;
Set str=substr(str,1,length(str)-1);
Select str;
End//
Delimiter ;
Delimiter ;
Loop …endloop
3. Write a procedure which accepts start and stop values and display all numbers between
start and stop(use loop …end loop)
Delimiter //
Create procedure displaydataloop(in start int,in stop int)
Begin
Declare str varchar(100) default '';
Declare cnt int default start;
L1:Loop
Set str=concat (str,cnt,',');
Set cnt=cnt+1;
If cnt>stop then
Leave l1;
End if;
End loop;
Set str=substr(str,1,length(str)-1);
Select str;
End//
Delimiter ;
4. Write a procedure to find factorial of a number using loop …end loop;
Delimiter //
Create procedure displayfactorialloop(in num int,out fact int)
Begin
Declare start int default 1;
Set fact=1;
L1:loop
Set fact=fact*start;
Set start=start+1;
If start >num then
Leave l1;
End if;
End loop
Select fact;
End//
Cursors
Cursors are used to read the data from the table row by row, and process it
1. Declare cursor.
2. declare continue handler to stop the loop
3. open the cursor.
4. fetch the row from the cursor.
5. check whether reached to last row leave the loop
6. process the row.
7. goto step 4
8. once come out of the loop then close the cursor.
elimiter //
create procedure displayallemp()
begin
open empcur;
lable1: loop
if vset=1 then
leave lable1;
end if;
select vempno,vname;
end loop;
close empcur;
end//
delimiter ;
Cursors
Cursors are used to read the data from the table row by row, and process it
1. Declare cursor.
2. declare continue handler to stop the loop
3. open the cursor.
4. fetch the row from the cursor.
5. check whether reached to last row leave the loop
6. process the row.
7. goto step 4
8. once come out of the loop then close the cursor.
delimiter //
begin
open empcur;
lable1: loop
if vset=1 then
leave lable1;
end if;
select vempno,vname;
end loop;
close empcur;
end//
delimiter ;
2. write a procedure to display all the employees whose sal < avg sal of its own
department
delimiter //
create procedure displayempbyavg()
begin
declare vset,vempno,vdeptno int default 0;
declare vename,vjob varchar(20);
declare vsal,vavgsal float(9,2);
declare empcur cursor for select empno,ename,job,sal,deptno from emp;
declare continue handler for NOT FOUND set vset=1;
open empcur;
label1:loop
fetch empcur into vempno,vename,vjob,vsal,vdeptno;
if vset=1 then
leave label1;
end if;
select avg(sal) into vavgsal
from emp
where deptno=vdeptno;
if vsal<vavgsal then
select vempno,vename,vjob,vsal,vdeptno,vavgsal;
end if;
end loop;
close empcur;
end//
delimiter ;
-> begin
-> end//
select empno,ename,hiredate,calculateexp(hiredate)
delimiter //
begin
declare vemail varchar(50);
set vemail=concat(substr(enm,3,4),'.',left(ejob,3),'@mycompany.com');
return vemail;
end//
delimiter ;
To write trigger
Triggers are used for data analysis purpose or for security purpose.
action varchar(20));
delimiter //
create trigger updatedepttr before update
on dept
for each row
insert into dept_audit values(old.deptno,new.dname,
old.dname,new.loc,old.loc,user(),curdate(),’update’);
end//
delimiter ;
Exception handling
declare <exception-action> handler <exception> <statements>
• SQLEXCEPTION
• error code
• NOT FOUND
delimiter //
begin
end//
delimieter ;
Normalization
Revati came to bank for enquiry, but she did not open the account, so no acid is there , hence
we will not be able to add her entry in the table to retain customer information, this is called
insertion anamoly
If kishori changes her phone number for a/c 1000, it will not get reflected in other accounts, this
is called as updation anamoly
if rajan closes the account, then bank will loose customer information along with account
information, it is called as deleteion anamoly.’
1NF
According to the E.F. Codd, a relation will be in 1NF, if each cell of a relation contains
only an atomic value. This normal form states that an attribute of a relation cannot
hold multiple values. It should hold only single-valued attributes. Values stored in
an attribute should be of the same domain.
Stud Sna cid Cname Fid Fname Email mar
id me ks
1 Djh 100 Database 1 Kishori abc@gmail.com,wert@rediff.c 99
om
1 Djh 101 Java 2 Madhura abc@gmail.com,wert@rediff.c 99
om
2 ettty 100 Database 1 Kishori eee@gmail.com,wwww@yah 98
oo.com,rrr@rediff.com
2 ettty 102 Data 2 Ganesh Eee11@gmail.com,wwww123 98
structure @yahoo.com
2NF
According to the E.F. Codd, a relation is in 2NF, if it satisfies the following conditions:
• A relation must be in 1NF.
• And the candidate key in a relation should determine all non-prime attributes
or no partial dependency should exist in the relation.
Prime attributes: The attributes which are used to form a candidate key are called
prime attributes.
Non-Prime attributes: The attributes which do not form a candidate key are called
non-prime attributes.
Partial Dependency: If a non-prime attribute can be determined by the part of the
candidate key in a relation, it is known as a partial dependency. Or we can say that,
if L.H.S is the proper subset of a candidate key and R.H.S is the non-prime attribute,
then it shows a partial dependency.
Example of partial Dependency: Suppose there is a relation R with attributes A,
B, and C.
prime attributes
sid, cid
sid--→ sname,email,
cid -→ cname
student
Course
cid Cname
100 Database
101 Java
102 Data
structure
3NF
student_course
Stud cid Fid mar
id ks
1 100 1 99
1 101 2 99
2 100 1 98
2 102 3 98
Fid Fname
1 Kishori
2 Madhura
3 Ganesh
Stud Sna
id me
1 Djh
2 ettty
Stud Email
id
1 abc@gmail.com
1 wert@rediff.com
2 eee@gmail.com, ,
2 wwww@yahoo.com
2 rrr@rediff.com
Id Subject Professor
103 C# Lakshay
• Using Id and Subject together, we can find all unique records and also the other
columns of the table. Hence, the Id and Subject together form the primary key.
• The table is in 1NF because all the values inside a column are atomic and of the same
domain.
• We can't uniquely identify a record solely with the help of either the Id or the Subject
name. As there is no partial dependency, the table is also in 2NF.
• There is no transitive dependency because the non-prime attribute i.e., Professor, is not
deriving any other non-prime attribute column in the table. Hence, the table is also
in 3NF.
• There is a point to be noted that the table is not in BCNF (Boyce-Codd Normal Form).
As we know that each professor teaches only one subject, but one subject may be taught by
multiple professors. This shows that there is a dependency between the subject & the
professor, and the subject is always dependent on the professor (professor -> subject). As
we know that the professor column is a non-prime attribute, while the subject is a prime
attribute. This is not allowed in BCNF in DBMS. For BCNF, the deriving attribute
(professor here) must be a prime attribute.
1 101 Mayank
2 101 Kartik
3 102 Sarthak
4 103 Lakshay
5 104 Mayank
Professor Table
Professor Subject
Mayank Java
Kartik C++
Sarthak Java
Lakshay C#
Mayank Java
Professor is now the primary key and the prime attribute column, deriving the subject
column. Hence, it is in BCNF.
It is in 1NF
is it in 2NF
empno-→ename, grade,sal
project
employee
scale
46 JONES A1 5
92 SMITH A2 4
96 BLACK B1 9
72 JACK A2 4
92 SMITH A2 4
proj emp
001 46 12/1/1998 24
001 92 2/1/1999 24
001 96 2/1/1999 18
004 72 2/4/1999 6
004 92 5/5/1999 6
scale
46 JONES A1 5
92 SMITH A2 4
96 BLACK B1 9
72 JACK A2 4
92 SMITH A2 4
46 JONES A1
92 SMITH A2
96 BLACK B1
72 JACK A2
92 SMITH A2
grade
Grade Sal
scale
A1 5
A2 4
B1 9
A2 4
A2 4
one-one any one side key can be added into another side
one- many, many- add key of one side into many side table as a foreign key
one
many-many create new table and add primary key of both sides
Is it in 1NF------yes
Is it in 2NF
1. It should be in 1 NF ----yes
2. Check for partial dependency
Prime attribute ----- orderno, item no
Orderno---→order date,cname,cno,email,orderamt,salespersonid,salespersonname,
Itemno
orderno, item no---→qty,price,locationid, location name
order
(Orderno,order date,cname,cno,email,orderamt,salespersonid,salespersonname
Cno--→cname,email
Salesperson id-→sname
Order_item
(orderno, item no,qty,price,locationid, location name
Customer
(cno,cname,email)
Salesman
(Salesperson id,sname)
order
(Orderno,order date, cno, ,orderamt,salespersonid)
Location(location id,lname)
Order_item
(orderno, item no,qty,price,locationid)
Types of models
Conceptual model
If you draw ER diagram with entity name and relation
Logical model
In conceptual model if you add list of attribute then it is logical model
Physical model
In logical model if you define data types of each attribute, primary key,foreign key
customer(cno,cname,mobile)
1. list
a. duplicate values are allowed
b. it is represented as []
c. it is ordered collection, hence indexing is possible.
d. It is mutable
add in the list at the update student set hobbies=hobbies+['trekking']
end where sid=1;
add in the list at the update student set hobbies=['trekking']+hobbies
begining where sid=1;
delete from the list update student set hobbies-['trekking']
where sid=1;
overwrite the list 1st update student set hobbies[1]='trekking'
index position with where sid=1;
some value
2. set
a. it is a collection of unique values
b. it is represented using {}
c. It is unordered, and hence no indexing is possible
d. It is mutable
add value in the set update customer
set brands=brands+{'a','b'}
where cno=1;
where cno=1;
delete all values update customer
from the set
set brands={}
where cno=1;
where cno=1;
3. map
a. it allows to store key-value pair
b. keys should be unique
c. data is stored in {}
d. values can be retrieved by using keys.
add value in the map update student set
marks=marks +{'java':98}
where sid=1;
delete all values from the map update student set marks={}
where sid=1;
delete some key-value pair update student set
marks=marks -{'java','python'}
where sid=1;
assign or overwrite value in the update student set
map marks[‘perl’]=100
where sid=1;
4. tuple
a. duplicates are allowed
b. it is ordered collection, so indexing is possible
c. tuples are immutable
d. it uses ()
e. these are fixed length data
alter table student add degree tuple<text,text,int>;
begin batch
apply batch
{"cno":12,"cname":"dfsd","brands":["a","b"],"mobile":"34567",
"billamt":4567}';
In mongodb data can be stored as document, stored in BSON format
{empno:123,
ename:'Rajan',
desg:'manager',
dept:{depetno:1,dname:'xxx'},
project:[{name:'x',duration:4},
{name:'y',duration:2},
{name:'x',duration:60}],
hobbies:['reading','dancing'],
married:True
project.1.duration
hobbies.1
to install mongodb
to download mongo db
https://www.mongodb.com/try/download/community
https://www.mongodb.com/try/download/database-tools
step 1
c:\system32>mongosh
to import data
open third command prompt----to load data