You are on page 1of 28

*DATABASE-> is a collection of interrelated data.

*sql->refer as "structured query language" use to fetch information from databas


e.
(1)DDL->Data Definition Language (DDL) statements are used to define the databas
e structure or schema.
-------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 t
he records are removed
RENAME - rename an object
(2)DML->Data Manipulation Language (DML) statements are used for managing data w
ithin schema objects.
-------SELECT - retrieve data from the a database
INSERT - insert data into a table
UPDATE - updates existing data within a table
DELETE - deletes all records from a table, the space for the records remain
CALL - call a PL/SQL or Java subprogram
LOCK TABLE - control concurrency
(3)DCL->Data Control Language (DCL) statements.
-------GRANT - gives user's access privileges to database
REVOKE - withdraw access privileges given with the GRANT command
(4)TCL->Transaction Control (TCL) statements are used to manage the changes made
by DML statements.
------It allows statements to be grouped together into logical transactions.
COMMIT - save work done
SAVEPOINT - identify a point in a transaction to which you can later roll back
ROLLBACK - restore database to original since the last COMMIT
SET TRANSACTION - Change transaction options like isolation level and what rollb
ack segment to use
ex-> student table
-----------------------------------------------------------------------------

| sid |

sname |

email

dob

per | course |

fee

|
----------------------------------------------------------------------------| 12 |

subhag | subhag@gmail | 1986-04-15

72

| MCA

| 40000

|
----------------------------------------------------------------------------| 13 |

gaurav | gaurav@gmail | 1990-06-17

70

| BE(EC) | 60000

|
----------------------------------------------------------------------------| 14 |

sachin | sachin@gmail | 1987-11-15

| 61.13 | BE(CS) | 75000

|
----------------------------------------------------------------------------| 15 |

nidhi

| nidhi@yahoo | 1986-02-02

| 67.43 | BE(CS) | 75000

|
----------------------------------------------------------------------------| 16 |

radha

| radha@hotmail | 1993-04-23

| 74

| BE(IT) | 50000

|
----------------------------------------------------------------------------database terminology->
(1)Database->A database is a collection of data that is organized in a specific
way.
The data is stored in a way that makes it easy to access using quer
ies.
(2)Field->Each table has a set of fields.(no. of columns)
in the student table it has 7 field.it is also known as attributes.
{ sid , sname , email , dob , per , course , fee }
(3)schema->the overall structure of the dabase is called schema.
the student schema is ->{ sid , sname , email , dob , per , course ,
fee }
(4)tuple ->it is known as rows . in the above table 5 tuple is present.
Working with MySQL Server->
-------------------------*in MySQL you need to select DATABASE where the information will be stored.
*DATABSE is name of directory in MySQL.
some useful queries->
-------------------(1)to verify all the databases available ->show databases;
(2)to select required databse -> use <DBNAME>
(3)to create a new database -> create database <DBNAME>
(4)to drop database* -> drop database <DBNAME> (this command execute from root)
(5)to see the list of table under a DB-> show tables;

(6)to see the user information -> select user();


datatypes->*this datatype will be applicable only in MySQL not in ORACLE
--------------------------------------------Integer values | INT
| BIGINT
| LONG
----------------------------------Float values | FLOAT
| DOUBLE
|
----------------------------------Alphanumeric | CHAR(N)
| VARCHAR(N)
| TEXT
----------------------------------Date
| DATE
| (YYYY-MM--DD)mysql
DATE('DD-Mon-YYYY')oracle
|
----------------------------------Large Documents | CLOB
|
-----------------------------------queries in MySQL->
-------------------------------------------------------------------------------------------------------(1) create table->
syntax-> create table <table_name>(
<col 1><datatype>[size],
<col 2><datatype>[size],
........................
........................
<col n><datatype>[size]);
ex->create table students(sid int,sname varchar(15),email varchar(15),phone long
,fee long,dob date);
(2)to see the attributes of tables->
syntax-> desc <table_name>;
ex-> desc subhag
note->to remove table
syntex: drop table <table name>
ex-> drop table students;
--------------------------------------------------------------------------------------------------------(3)insert data into table->there are two options into inserting data into table
(A)syntax-> insert into<table_name>values(val1,val2,......... )

ex->
insert into students
00,'1986-07-07');
insert into students
23,'1992-07-13');
insert into students
29,'1988-11-28');
insert into students
22,'1991-02-17');
insert into students
13,'1985-08-03');
insert into students
11,'1982-10-15');

values(123 , 'subham gupta',

's@gmail ', 9616754075,12455

values(124 , 'ram gupta',

'r@gmail ', 9991234522,15475

values(125 , 'lakshman gupta', 'l@gmail ', 9837498672,54732


values(126 , 'bharat gupta',

'b@gmail ', 9543271243,52132

values(127 , 'ramesh kumar',

'r@gmail ', 9423976534,34231

values(129 , 'govind gupta',

'g@gmail ', 9321546375,19821

note->to see the all content the data of table->


select * from <table_name>;
select * from students;
(B)syntax-> insert into<table_name>(col1 ,col2 ......)values<val1,val2,........
>
ex->
insert into students (sid ,sname ,fee) values(140 , 'radhe modi', 2245500);
insert into students (sid ,sname ,fee) values(141 , 'nidhi singh', 3745500);
insert into students (sid ,sname ,fee,dob) values(144 , 'ram chandra', 4245500,
'1978-01-21');
* select * from students;
------------------------------------------------------------------------------------------------------------(4)inserting multiple record->
create table stud(sid int , sname varchar(10));
insert into stud values(1,'A'),(2,'B'),(3,'C'),(4,'D'),(5,'E');
select * from stud;
------------------------------------------------------------------------------------------------------------(5)updating record of tables->
syntax-> update<table_name>set col1 = val1,col2 = val2 ........where<conditio
n>;
ex->
update students set email= 'ram@gmail' where sid=123;
update students set sname='jyoti',fee = 3465254 where sid = 129;
-------------------------------------------------------------------------------------------------------------(6)deleting records of table->
syntax-> delete from<table_name>where<cond>;
ex->
delete from students where email = 'r@gmail ';
delete from students where phone= 9991234522 and dob= '1992-07-13';
Q:delete the record of students who has not dob.
delete from students where dob is null;
select * from students;
Q:delete the record that has email.
delete from students where email is not null;
select * from students;

note->if you want to delete all row from a table than


delete from students;
---------------------------------------------------------------------------------------------------------------reading record from table->
syntax-> select * (or)col1 ,col2 ,col3.....
from <table_name>
where<con>
order by<col_name>[asc/desc]
group by<col_name>
having<cond>;
select * from students where sid = 126;
select sname,phone from students where sid =126;
*SQl Operator->
(1) Arithmetic operators->+,-,*,/,mod
(2) Relational operators
(A)<,<=,>,>=
(B)=(Equality)
(C):=(Assignment)
(D)!=(not equal to)
(3)Logical Operators
and ,or,not
(4)"in" operator
(5)"like" operator
(6)"between" operator
(7)"is null" operator
(8)"not" operator
-------------------------------------------------------------------------------------------------------IN Operator->in operator is used to match one value from collection of values
syntax-> <col_name>in(val1,val2......);
ex->

city in('blore','hyd','pune');
or
city='blore' or city = 'hyd' or city='pune';
-------------------------------------------------------------------------------------------------------BETWEEN Operator->it is used to match the value in specified range
syntax-> <col_name>between<val1>and<val2>;
ex-> cost between 250 and 450;
or
cost>=250 and cost<=450;
--------------------------------------------------------------------------------------------------------LIKE Operator->(1)to match the value with specified pattern
(2)to define the pattern you can use following character
% - occurance of zero or more character
_ - occurance of only one character
ex->

starting with 's'


: name like 's%'
end with 's'
: name like '%s'
's' character should be present : name like '%s%'
second last char shuld be 'a' : name like '%a_'
name ends with i
: name like '_i'
----------------------------------------------------------------------------------------------------------IS NULL Operator->used to verify whether column contains null or not
suntax-> <col_name>is null;
ex-> city is null;
phone is null;
---------------------------------------------------------------------------------------------------------NOT Operator->it can be used with 'between','is null','in','like' operator to in
verse the result
(1) age not in(20,23);
(2) city is not null;
(3) phone is not null;
(4) cost not between 250 and 350;
(5) name not like 'sri%';
-----------------------------------------------------------------------------------------------------------------create table books(bid varchar(10),bname varchar(15),author varchar(15),cost big
int,edi char(3),pub varchar(10),yop int,isbn varchar(10));
insert into books values('b-001','learn java','srinivas',950,'2nd','pearson',201
3,'ab45dv41');
insert into books values('b-002','java in depth','dande',400,'1st','ps',2010,'ac
49xv73');
insert into books values('b-003','learn ejb','srini',800,'3rd','tata',2013,'e444
5rt26');
insert into books values('b-004','learn java','vas',900,'4th','pearson',2003,'w
385iv41');
insert into books values('b-005','learn c++','srinivas',975,'2nd','tata',2007,'q
2r5dv21');
Q:(1)display the complete information of books.
(2)display the bookid,bookname,cost of all books.
(3)display the book published by 'pearson'.
(4)display the books written by author whose name start with 'sri'.
(5)display the books published in 2010 and written by author whose name ends w
ith 'vas'.
(6)display the books published between 2000 to 2011.
(7)display the books in ascending order of cost.
(8)display the books published after 2009 in descending order of cost.
(9)display the books published by 'tata','pearson'.
(10)display the books whose author name 2nd character is 'r'.
(11)display the books which are not published by 'pearson'.
A:
1->select
2->select
3->select
4->select

* from books;
bid,bname,cost from books;
* from books where pub='pearson';
* from books where author like 'sri%';

5->select * from books where yop=2010 and author like '%vas';


6->select * from books where yop between 2000 and 2011;
or
select * from books where yop>=2000 and yop<=2011;
7->select * from books where order by cost;
8->select * from books where yop>=2009 order by cost desc;
9->select * from books where pub in ('pearson','tata');
or
select * from books where pub='jlc'or pub = 'tata';
10->select * from books where author like '_r%';
11->select * from books where pub<>'pearson';
or
select * from books where pub!='pearson';
or
select * from books where pub not in('pearson');
----------------------------------------------------------------------------------------------------Arithmetic Function->(1)sqrt (2)ceil (3)floor (4)round (5)power
--------------------select ceil(12.5) from dual;
select floor(12.3) from dual;
select round(12.85) from dual;
select power(3,2) from dual;
select sqrt(16) from dual;
----------------------------------------------------------------------------------------------------String Function->
----------------(1)length (2)substr (3)concat (4)upper (5)lower (6)replace
ex->
select sname , length(sname) from students;
select length('subhag')from dual;
select length(' java welcome center ') from dual;
select substr('kclinktechnologies',4)from dual;
select substr('kclinktechnologies',4,2)from dual;
select replace('java welcome center','wel','best') from dual;
select concat('kclink' 'india');
select lower('INDIA IS GREAT');
select upper('dilwale dulahaniya le jayege');
*date->select sysdate from dual;
-----------------------------------------------------------------------------------------------------Aggregate function->(1)sum (2)min (3)max (4)avg (5)count
-------------------ex->
create table emp(eid int,ename varchar(10),salary float);
insert into emp values(1,'sri',7000);
insert into emp values(2,'vas',9000);
insert into emp (eid , ename)values(3,'srini');
insert into emp values(4,'sri',5000);
select
select
select
select
select
select

sum(salary) from emp;


max(salary) from emp;
min(salary) from emp;
avg(salary) from emp;
count(eid) from emp;
count(*) from emp;

select count(distinct ename) from emp;


--------------------------------------------------------------------------------------------------------group by and having clause->
---------------------------(1)gruop by clause is used to divide the table into multiple groups based on spe
cified column
(2)having clause is used to specify the condition on groups
create table student(sid int,sname varchar(12),city varchar(10),branch varchar(1
0),course varchar(10),totfee float,feepaid float,feebal float);
insert
00);
insert
insert
);
insert
0);
insert
);
insert
000);
insert
000);
insert
;

into student values(1,'srinivas','blore','mkr','fc',

18000,10000,80

into student values(2,'dande' ,'pune', 'btm','core java',5000,5000,0);


into student values(3,'manish', 'blore','mha','android', 8000,4000,4000
into student values(4,'dk',

'blore','mkr','fc',

18000,9000,900

into student values(5,'rajbeer' ,'pune', 'btm','android', 8000,5000,3000


into student values(6,'ramesh' ,'delhi', 'c.p.','dot net', 22000,15000,7
into student values(7,'subhag' ,'jhanshi', 'sadar','j2ee', 17000,12000,5
into student values(8,'radhe' ,'jhanshi', 'cant','c++', 10000,5000,5000)

Q:
(1)display total fee collection.
(2)display the fee paid by 'mkr' branch.
(3)display the total fee balance of 'btm' branch.
(4)display the branch wise fee collection in the following format.
branch name - total collection
btm
13000
mha
8000
mkr
36000
c.p.
22000
sadar
17000
cant
10000
(5)diplay the city wise fee paid in the following format
city name - total fee paid
blore
23000
pune
10000
jhanshi
17000
delhi
15000
(6)display the city wise(blore and pune)only fee balance in the following format
city name - total balance
blore
- 21000
pune
- 3000
A:select * from student
(1)select sum(totfee) from student;
(2)select sum(feepaid)from student where branch='mkr';
select branch,sum(totfee) from student where branch='mkr';
(3)select sum(feebal) from student where branch='btm';

(4)select sum(totfee) from student group by branch;


or
select branch,sum(totfee) from student group by branch;
(5)select sum(feepaid) from student group by city;
or
select city"city name" ,sum(feepaid)"total feepaid" from student group by city;
(6)select city"city name" ,sum(feebal)"total balance" from student group by city
having city in('blore','pune');
note-> if you want to apply condition on "group by" clause then "having clause"
is used not "where clause"
------------------------------------------------------------------------------------------------------------------Constraints->
-----------(1)constraints are the rule that will be applied on the column of the table
(2)these rules should be followed while updating the data table
Type of Constraints->
-------------------(1)not null constraint
(2)unique key constraint
(3)primary key constraint
(4)foreign key constraint
(5)default constraint
(6)check constraint
---------------------------------------------------------------------------------------------------------------not null constraint->
-------------------(1)if you are not supplying any value for the column then by default "NULL" valu
e wil be inserted by the dbms
(2)NULL means simply value is not available and it is not eqivalent to null or s
pace or 0 or '\0' or any other character
(3)if you do not want NULL value for any column you can use "not null"constraint
on that column
without not null constraint->
ex->create table emp(eid int,ename varchar(15) ,email varchar(20));
insert into emp(eid , email) values(3,'gupta@gmail.com') ;
insert into emp(eid , email) values(4,'kumar@gmail.com') ;
insert into emp(eid , ename) values(5,'subhag');
select * from emp;
with not null constraints->
create table emp1(eid int,ename varchar(15) not null,email varchar(20));
insert into emp1 values(2,'subhag','gupta@gmail.com');
insert into emp1(eid , ename) values(5,'radha');
insert into emp1(eid , email) values(3,'gupta@gmail.com') // it give the error
note-> we can insert "not null constraint" into multiple columns
create table emp2(eid int not null,ename varchar(15) not null,email varchar(20)
not null);
--------------------------------------------------------------------------------

-----------------------------------unique key constraints->


(1)by default you can insert duplicate value in any column
create table emp3(eid int , ename varchar(15),phone long,salary float)
insert into emp3 values(1,'a',9616754075,90000.0);
insert into emp3 values(1,'a',9616754075,90000.0); // this can insert the same r
esult and introduce duplicacy
(2)if you want different value for any column than you can use "unique constrain
t".
create table emp4(eid int unique, ename varchar(15),phone long,salary float);
insert into emp4 values(1,'a',9616754075,90000.0);
insert into emp4 values(1,'a',9616754075,90000.0); // not ok
insert into emp4 values(2,'a',9616754075,90000.0); // ok
note-> in unique constrains you can not insert dulicate values but you can inser
t any no of"null" values
insert into emp4(ename , phone , salary) values('a',9616754075,90000.0);
insert into emp4(ename , phone , salary) values('a',9616754075,90000.0);
select * from emp4
note-> unique constraints can be used for multiple column of the same table
unique constraints can be used in combination with not null also
create table emp5(eid int unique not null , ename varchar(10) unique , phone int
unique , email varchar(15) unique)
-----------------------------------------------------------------------------------------------------------------------primary key constraint->
----------------------(1)combination of "unique+not null" constraint is called as primary key.
(2)table should contain only one primary key.
(3)primary key is mainly used to identify the records uniquely in a table.
(4)when you apply primary key then both unique and not null constraint will
be applied on the column.
type of primary key->
(1)simple primary key
(2)composite primary key
--------------------------------------------------------------------------------------------------------------------(1)simple primary key->
---------------------when you specify one column of a table as primary key then it is called
simple primary key.
create table order1(oid int primary key , itemname varchar(10), qty int,price in
t);
insert into order1 values(1,'mouse',100,450);
insert into order1(1,'mouse',200,325); // not ok
insert into order1(itemname,qty) values('keyboard',,500);

// not ok

(2)**composite primary key->


-----------------------when you specify more than one column of a table as primary key then it is calle
d as composite primary key
create table account(bcode int , atype int , acno int ,bal float , primary key(b
code,atype,acno));
---------------------------------------------------------------------------------------------------------------------foreign key constraint->
-----------------------(1)foreign key constraint is mainly used to establish the relationship
between two or more tables
(2)the table which contains main information is called "parent table".
(3)the table which contains related information is called "child table".
(4)The table containing the foreign key is called the referencing or child table
,
and the table containing the primary key is called the referenced or parent t
able
(5)some condition in foreign key
A - is a parent table
B - is a child table
A------->B
in A table
(i)you can not delete the data in A table because B pointing the A data.
(ii)you can not update the data in A table because B pointing the A data
in this insertion is not create voilation
in B table
(i)you can not insert the data in B table
(ii)you can not update the data in B table
in this deletion is not create voilation
ex->
create table models(modelid int primary key,name VARCHAR(10) NOT NULL);
insert
insert
insert
insert

into
into
into
into

models
models
models
models

values(11,'subhag');
values(12,'radhe');
values(13,'krishna');
values(14,'nidhi');

create table orders (id int PRIMARY KEY,modelid int NOT NULL,
description VARCHAR(20),FOREIGN KEY (modelid) REFERENCES models (modelid
));
insert into Orders values(22 ,11 ,'mouse');
insert into Orders values(23 ,12 ,'monitor');
note->error will come
in parent table->
delete from models where modelid = 12; // error
update models set modelid=19 where name='subhag'; // error
update models set modelid=19 where name='nidhi'; // no error
update models set name ='jyoti' where modelid =13;
in child table->

insert into Orders values(24 ,15 ,'keyboard');


update orders set modelid = 17 where id=23;

->to solve this problem we use on delete cascade on update cascade


note->we can use either one or both
ON DELETE CASCADE ON UPDATE CASCADE:
when you delete or update the record from parent table automatically delete and
update the record from child table
create table orders (id int PRIMARY KEY,modelid int NOT NULL,
description VARCHAR(20),FOREIGN KEY (modelid) REFERENCES models (modelid
)
ON DELETE CASCADE ON UPDATE CASCADE );
insert into Orders values(22 ,11 ,'mouse');
insert into Orders values(23 ,12 ,'monitor');
so parent table error will be removed->
in parent table->
delete from models where modelid = 12;
update models set modelid=18 where name='subhag';
insert into Orders values(24 ,15 ,'keyboard'); // error
|-> beacause we can not insert the data into child table(first we insert the da
ta into parent table)
note->if we want to drop the table then first drop the child table
-------------------------------------------------------------------------------------------------------------default constraint->
------------------(1)by default "null" will be default value value for all the columns.
(2)default constraint can be used to supply other than null value as default val
ue.
create table emp7(eid int,ename varchar(10),salary float,city varchar(15) defaul
t 'banglore',country varchar(15) default 'india',age int default 65);
insert into emp7(eid,ename,salary)values(1,'ram',25000);
insert into emp7(eid,ename,salary)values(2,'lakshman',20000);
select * from emp7;
insert into emp7 values(3,'luv',30000,'ayodhya','gandhar',12);
insert into emp7 values(4,'kush',10000,'janakpuri','nepal',10);
select * from emp7;
note->if you supply value for all the columns then your value will be inserted o
therwise default value will be inserted.
-----------------------------------------------------------------------------------------------------------------check constraint->
-----------------note->only oracle support check constraint.

(1)check constraint is used to design user define rules.


(2)when you are developing any web application then you will get the requirement
your own constraints like:(a)student id must start with KC.
(b)age of student must be greater than 18.
(c)email id of student must be from yahoo domain only.
(d)for saving a/c customer bal should not be less than 500.
syntax-><col_name>check(<condition>);
create table student2(sid varchar(10) check(sid like 'kc-%'),sname varchar(15) n
ot null ,email varchar(15) check(email like '%@yahoo.com'),age int check(age>18)
,fee float check(fee>=20000));
insert into student2 values('kc-123','dharmendra','dh@yahoo.com', 25,25000);
insert into student2 values('kc-124','surendra','sr@yahoo.com', 29,20000);
insert into student2 values('125','bhupendra','br@yahoo.com', 29,20000)
// er
ror check consraints voilated
insert into student2 values('klc-125','bhupendra','br@gmail.com', 10,20000)// e
rror
------------------------------------------------------------------------------------------------------------------join->
-----(1)you want to access the data from more than table at a time then you can use j
oin.
(2)while you are joining tables there should be some common columns available to
specify join.
Type of join->
------------(1)inner join
(2)outer join
(A)left outer join
(B)right outer join
(c)full outer join
(3)self join
(4)cross join(practically not possible)
inner join->
-----------(1)inner join is also called as equi join
(2)inner join will give you the matching records from joined table.
create table customer5(cid int,cname varchar(10),email varchar(15),phone int,sta
tus varchar(15));
insert into customer5 values(101,'srinivs','sri@jlc.com',65799988,'active');
insert into customer5 values(102,'dande','dan@jlc.com',88359988,'active');
insert into customer5 values(103,'vassu','vasu@jlc.com',93799988,'inactive');
insert into customer5 values(104,'manish','mani@jlc.com',82799988,'inactive');
create
insert
insert
insert
insert

table account5(cid int,acno int,atype varchar(12),bal float);


into account5 values(101 ,123 ,'saving',9000);
into account5 values(102 ,124 ,'current',9700);
into account5 values(103 ,125 ,'current',5000);
into account5 values(104 ,126 ,'fixed',8500);

create table address5(cid int, street varchar(15) , city varchar(15),country var


char(12));

Q:
(1)display cname,email,accno,bal of all customers.
(2)display cname,email,status,city,country of all the customers.
(3)display cname,email,accno,bal of the customers who have saving a/c.
(4)dispaly cname,status,city,country of customers who is staying in delhi and ar
e active.
(5)display accno,atype,bal,city of the customers who have current a/c and bal be
tween
5000 to 10000 and staying in banglore,delhi and pune.
(6)display cname,status,accno,bal,city and country of all customers.
(7)display cname,status,accno,bal,city and country of all customers who are inac
tive
and bal<10000 and not staying in india.
execute queries 1-> select cname,email,acno,bal from customer5 cs,account5 ad where cs.cid=ad.ci
d;
2->select cname,email,status,city,country from customer5 cs, address5 ad where c
s.cid=ad.cid;
3->select cname,email,acno,bal from customer5 cs,account5 ad where cs.cid=ad.cid
and ad.atype='saving';
4->select cname,status,city,country from customer5 cs , address5 ad where cs.cid
=ad.cid and cs.status='active' and ad.city='delhi';
5->select acno,atype,bal,city from account5 a1,address5 a2 where a1.cid=a2.cid a
nd a1.atype='current'and a1.bal between 5000 and 10000 and a2.city in('banglore'
,'delhi','pune');
6->select cname,email,status,acno,bal,city from customer5 c1,account5 a1,address
5 a2 where c1.cid=a1.cid and c1.cid=a2.cid;
7->select cname,status,acno,bal,city,country from customer5 c1,account5 a1,addre
ss5 a2 where c1.cid = a1.cid and c1.cid = a2.cid and c1.status='inactive'and a1.
bal<10000 and city<>'india';
------------------------------------------------------------------------------------------------------------------------table for all join operations-->
create table jlcstud(sid int primary key ,name varchar(12),email varchar(15));
create table jlcfee(fid int primary key, fee float , sid int);
create table jlcadd(aid int primary key , location varchar(15),sid int);
insert
insert
insert
insert
insert
insert
insert

into
into
into
into
into
into
into

jlcstud->
jlcstud values(1,'ram','ram@gmail');
jlcstud values(2,'lakshman','lakshman@gmail');
jlcstud values(3,'bharat','bharat@gmail');
jlcstud values(4,'satrughan','satu@gmail');
jlcstud values(5,'sita','sita@gmail');
jlcstud values(6,'urmila','urmila@gmail');

insert into jlcfee->

insert
insert
insert
insert

into
into
into
into

jlcfee
jlcfee
jlcfee
jlcfee

values(123
values(124
values(125
values(126

,12455.11,1);
,15475.13,2);
,54732.29,3);
,52132.22,4);

insert
insert
insert
insert
insert

into
into
into
into
into

jlcadd->
jlcadd values(501,'delhi',3);
jlcadd values(502,'pune',4);
jlcadd values(503,'banglore',5);
jlcadd values(504,'chennai',6);

inner join/equi join->


1->select * from jlcstud,jlcfee where jlcstud.sid=jlcfee.sid
results->
SID NAME

EMAIL

FID FEE

1
2
3
4

ram@gmail
lakshman@gmail
bharat@gmail
satu@gmail

123
124
125
126

ram
lakshman
bharat
satrughan

SID

12455.11
15475.13
54732.29
52132.22

1
2
3
4

2-> select st.sid,st.name,st.email,fe.fee from jlcstud st , jlcfee fe where st.s


id=fe.sid
results->
SID NAME

EMAIL

1
2
3
4

ram@gmail
lakshman@gmail
bharat@gmail
satu@gmail

ram
lakshman
bharat
satrughan

FEE
12455.11
15475.13
54732.29
52132.22

3->select * from jlcstud,jlcfee,jlcadd where jlcstud.sid=jlcfee.sid and jlcstud.


sid=jlcadd.sid
results->
SID NAME
3
4

EMAIL

FID FEE

SID AID LOCATION SID

bharat
bharat@gmail 125 54732.29 3
satrughan satu@gmail
126 52132.22 4

501
502

delhi
pune

3
4

4->select st.sid,st.name,st.email,fe.fee,ad.location from jlcstud st,jlcfee fe,j


lcadd ad where st.sid=fe.sid and st.sid=ad.sid
results->
SID NAME
3
4

EMAIL

bharat
bharat@gmail
satrughan satu@gmail

FEE

LOCATION

54732.29
52132.22

delhi
pune

5->select * from jlcstud inner join jlcfee on jlcstud.sid=jlcfee.sid


results->
SID NAME

EMAIL

FID

FEE

SID

1
2
3
4

ram
lakshman
bharat
satrughan

ram@gmail
lakshman@gmail
bharat@gmail
satu@gmail

123
124
125
126

12455.11
15475.13
54732.29
52132.22

1
2
3
4

6->select * from jlcstud inner join jlcfee using(sid)


results->
SID NAME

EMAIL

FID

1
2
3
4

ram@gmail
lakshman@gmail
bharat@gmail
satu@gmail

123
124
125
126

ram
lakshman
bharat
satrughan

FEE
12455.11
15475.13
54732.29
52132.22

7->select * from jlcstud natural join jlcfee


results->
SID NAME

EMAIL

FID

FEE

1 ram
ram@gmail
123 12455.11
2 lakshman lakshman@gmail 124 15475.13
3 bharat
bharat@gmail 125 54732.29
4 satrughan satu@gmail
126 52132.22
------------------------------------------------------------------------------------------------------------------------left outer join->
---------------it will give "matching record from joined table + record remains in the left sid
e table"
ex->
select * from jlcstud left join jlcfee on jlcstud.sid = jlcfee.sid;
select * from jlcstud left outer join jlcfee on jlcstud.sid = jlcfee.sid;
select * from jlcstud left outer join jlcfee using(sid);
right outer join->
----------------it will give "matching record from joined table + record remains in the right si
de table"
insert into jlcfee values(127 ,53132.22,7);
insert into jlcfee values(128 ,52132.22,8);
ex->
select * from jlcstud right join jlcfee on jlcstud.sid = jlcfee.sid;
select * from jlcstud right outer join jlcfee on jlcstud.sid = jlcfee.sid;
select * from jlcstud right outer join jlcfee using(sid);
full outer join->
----------------it will give "matching records from joined table + record remaing in the left si
d + record remaing in right sid table "
ex->select * from jlcstud left join jlcfee on jlcstud.sid = jlcfee.sid union
select * from jlcstud right join jlcfee on jlcstud.sid = jlcfee.sid;
-------------------------------------------------------------------------------------------------------------------------

(imp)self join->
---------------(1)joining the table to itself is called as self join.
(2)self join is same as any other join but in this join multiple instance of
same table will participate the join query.
create
insert
insert
insert
insert

table employee(eid int,ename varchar(5),mgrid int);


into employee values(101,'A',103);
into employee values(102,'B',103);
into employee values(103,'c',104);
into employee values(104,'D',101);

select * from employee;


eid
101
102
103
104

ename mgrid
A
103
B
103
C
104
D
101

|
|
|
|
|
|
|
|

but we want this o/p


eid
101
102
103
104

ename mgrname
A
C
B
C
C
D
D
A

so for the required o/p we will use self join


select emp.ename "emp name",mgr.ename as "manager name" from employee emp,employ
ee mgr
where emp.mgrid=mgr.eid;
------------------------------------------------------------------------------------------------------------------------sub query->
-----------when you include one query as a part of another query then it is called subquery
.
use the table of previouse customer5,account5 and address5.
using sub queries solve the following queries->
(1)what is the customer having a/c no.123;
(2)display the accno and balances of customers who are enable;
(3)display the accno and balance of the customers who is staying in banglore.
(4)display name and status of the customers who is staying in banglore,mysore,pu
ne.
(5)display the name and email of the customers who has saving acc and balance
between 5000-10000.
A:
1-> select cname,email from customer5 c,account5 a where c.cid=a.cid and a.acno
=123;
or
A)-select cid from account5 where acno=123;
B)-select cname,email from customer5 where cid=101;
note->we can find the above two query solution using sub query
1->select cname,email from customer5 where cid=(select cid from account5 where a
cno=123);
|-> this execute first
note-> in sub query inner query always execute first
note-> when outer query contain multiple date then we use 'in' keyword instead o
f '=' operator

2->select acno,bal from account5 where cid in(select cid from customer5 where st
atus='active');
3-> select bal from account5 where cid in(select cid from address5 where city='b
anglore');
4->select cname,status from customer5 where cid in(select cid from address5 wher
e city in('banglore','pune','delhi'));
5->select cname,email from customer5 where cid in(select cid from account5 where
atype='saving' and bal between 5000 and 10000);
-----------------------------------------------------------------------------------------------------------------------creation of table using sub query->
we can create table using sub query by using 'as' keyword
1-> create table cust1 as select * from customer5;
select * from cust1;
2-> create table cust2 as select cname,email from customer5;
select * from cust2;
3-> create table cust3 as select c.cid ,cname,email,acno,bal from customer5 c,ac
count5 a where c.cid=a.cid;
select * from cust3;
------------------------------------------------------------------------------------------------------------------------auto_increment->
--------------it can be used to generate numeric value in mysql.
ex->
create
insert
insert
insert

table emp5(eid int primary key auto_increment,ename varchar(10));


into emp5(ename)values('A');
into emp5(ename)values('B');
into emp5(ename)values('C');

select * from emp5;


------------------------------------------------------------------------------------------------------------------------alter command-> this is very importent command .
-------------- this is used to add ,drop ,modify ,rename of the column .
create table stu(sid int,sname char(10),fee float);
insert into stu values(11,'subhag',10200);
insert into stu values(12,'radhe',15000);
insert into stu values(13,'krishna',22000);
*add the new column->
alter table stu add(email varchar(15));
select * from stu;
*drop the column->
alter table stu drop column fee;
*modifying the size of the column->
alter table stu modify sid varchar(15);
alter table stu modify sname char(20);

*adding the primary key constraints->


alter table stu add primary key(sid);
*dropping the primary key constraints->
alter table stu drop primary key;
*rename the column name->
alter table stu rename column sname to sname1;
*rename the table name->
alter table stu rename to stu1;
*removing the structure of table->
drop table stu;
-----------------------------------------------------------------------------------------------------------------------Q->what is the diff b/w drop,delete and truncate.
truncating table->
(a)delete from student;
(b)truncate table student;
(1)above two queries both is used to remove the row and give the same result.
(2)in delete ,row is deleted as well as space are removed also.
in truncate,row is deleted but space
(3)delete operation can be rolled back;
truncate operation can not be rolled back.
------------------------------------------------------------------------------------------------------------------------transaction mangement->
---------------------(1)transaction is a process of performing set of DB operation as a single unit.
(2)if all the database operation of the transaction is successfull than you
have to save the transaction by using "commit" command.
(3)if any single database operation of the transaction is unsuccessfull then
you have to cancel the entire transaction by issuing "rollback" command.
(4)to manage the transaction you need to use the following keywords
(A)autocommit
(B)commit
(c)rollback
(D)savepoint
commit-> the query will be committed or save can not be rolled back.
rollback->uncommitted or unsaved query will be rolled back
savepoint->marking from where the uncommitted or unsaved query will be rolled ba
ck.
autocommit->(1)if enabled then after executing the query commit will be issued.
(2)if disabled then after executing the query commit will not be iss
ued
if we want the rollback then we off the "autocommit" option
note-> delete operation can be roll back but truncate operation can not be roll
back
only dml operation can be roll back

select @@autocommit;
set autocommit=0; // off the autocommit
if we want the rollback then we off the "autocommit" option
select * from employee;
1->delete from employee;
rollback // it restore the original result
2->truncate from employee;
rollback // statement will execute but will not store the original result
------------------------------------------------------------------------------------------------------------------------*PL/SQL BLOCK->
--------------with pl/sql you can define the block where multiple sql statements can be submit
ted to database engine at once.
note->mysql doen not support pl/sql.only stored procedure can executed on mysql
syntax:
declare
// varaible or constant declaration
begin
// statements
end;
/
statements:
*declare variables
*declare constants
*conditional statements
*looping control statements
*sql statements
Q:write a pl/sql block to print welcome message
A:
begin
dbms_output.put_line('welcome to stored procedure');
end;
/
o/p->pl/sql procedute successfully completed but it will not show any
note->so if we want the output then we write first
set serveroutput on;
*variable declaration->
---------------------syntax: <var_name><datatype>
ex-> eid int;
ename varchar(10);
*constant declaration->

----------------------syntax: <const_name>constant<datatype>:=<val>;
ex-> max constant int:=225;
*variable initialization->
-------------------------syntax: <var_name>:=<value>;
ex-> eid:=100;
ename:='subhag';
*declaration and initialization->
-------------------------------syntax: <var_name><datatype>:=<value>;
ex-> eid int:=100;
ename varchar(10):='subhag';
->write a pl/sql block to display the sum of two number
(1) declare
a int;
b int;
c int;
begin
a:=10;
b:=20;
c:=a+b;
dbms_output.put_line(c);
end;
/
(2)declare
a int:=&a;
b int:=&b;
c int;
begin
c:=a+b;
dbms_output.put_line('total is '||c);
end;
/
& : is used to take the value from user at run time
|| : is used for concatenation
/ : is used to execute last query
condition statement->
syntax:1
-------if(<cond>)then
s1;
end if

syntax:2
-------if(<cond>)then
s1;
else
s2;
end if;

syntax:3
---------if(<cond>)then
s1;
elseif(<cond>)then
s2;
:
:
else

sN;
end if;
->write a pl/sql block to take two no from the user and display max
declare
a int:=&a;
b int:=&b;
max1 int;
begin
if(a>b)then
max1:=a;
else
max1:=b;
end if;
dbms_output.put_line('maximum is '||max1);
end;
/
*Looping Statements->
-------------------1->simple loop
2->for loop
3->while loop
simple loop->
-----------syntax:
loop
// statement
<incr/decr>;
exit when(a>10);
end loop;
end;
/
forward order
------------declare
a int;
begin
a:=1;
loop
dbms_output.put_line(a);
a:=a+1;
exit when(a>10);
end loop;
end;
/
reverse order
------------declare
a int;
begin
a:=10;
loop
dbms_output.put_line(a);
a:=a-1;

exit when(a<1);
end loop;
end;
/
*for Loop->
---------syntax:
for <var>in[reverse]<start_val>..<end_val>
loop
//statement
end loop;
forward order
------------begin
for a in 1..10
loop
dbms_output.put_line(a);
end loop;
end;
/
reverse order
------------begin
for a in reverse 1..10
loop
dbms_output.put_line(a);
end loop;
end;
/
*while loop->
-----------syntax:
while(<cond>)
loop
// statements
<ince/decr>;
end loop;
forward order
------------declare
a int;
begin
a:=1;
while(a<=10)
loop
dbms_output.put_line(a);
a:=a+1;
end loop;
end;
/
reverse order
------------declare
a int;

begin
a:=10;
while(a>=1)
loop
dbms_output.put_line(a);
a:=a-1;
end loop;
end;
/
->write a pl/sql to take a no. from user and print its table
declare
a int:=&a;
begin
for i in 1..10
loop
dbms_output.put_line(a*i);
end loop;
end;
/
*stored procedure->
-----------------1->stored procedure is a named pl/sql block.
2->it is created and stored in the database.
3->when you submit pl/sql block to the database engine
then it will be compiled every time.
4->when you submit stored procedure to the database engine
then it will be compiled and saved into the databse.
5->when you want to execute the stored procedure then you can call
with its name it will be executed directly without re-compilation.
...............
Request time
...............
:
:------------------------->:
:->compilation
:
:
5ms/query
:
: 5ms/query
:
java
:
: Database :
: Program
:
:
:
:
:
Response time
:
:
:
:<-------------------------:
:<-execution
:.............:
5ms/query
:.............: 5ms/query
*using pl/sql
------------for 1st time execution=5ms+5ms+5ms+5ms = 20ms
for next 100 time executin=100*20 = 2000ms
*using stored procedure
----------------------for 1st time execution=5ms+0ms+5ms+5ms = 15ms
for next 100 time executin=100*15 = 1500ms
note->in this compilation time is saved.
note->syntax is different of stored procedure in oracle as compared to mysql

*Stored Procedure in MySql->


--------------------------syntax:
delimiter $
create [or replace] procedure <proc_name>( <param_type> <param_name> <datatype>
)
is or as
declaration section
begin
// sql statements
end ;
/
*displaying welcome message
create procedure showMessage1 as
begin
dbms_output.put_line('welcome to procedure');
end;
/
*to see the output->
set serveroutput on;
call showMessage();
type of parameter->
-----------------1->input parameter
2->output parameter
3->input output parameter
*syntax to specify parameter->
----------------------------<param_name><param_type><data_types>;
ex->
id in int;
sname out varchar;
fee in out float;
input parameter->
---------------(1)it is the default type.
(2)the value which you are passing can not be changed inside the procedure
and you can not access that value outside the procedure.
(3)to specify any parameter as input you have to use "in" keyword.
ex->
create or replace procedure p1(ch in char)
as
n int;
begin
n:=ascii(ch);
dbms_output.put_line('ascii value ='||n);
end;
/

call p1('A');
output parameter->
----------------(1)it is used to bind the variable to the procedure at runtime.
(2)the value of variable which you are passing can be changed inside
the procedure and you can access that modified value outside the procedure.
(3)to specify output parameter you have to use "out" keyword
ex->
create procedure p2(ch in char , n out int)
as
begin
n:=ascii(ch);
end;
/
to execute->
sql> var n number;
sql> call p2('D',n);
call completed.
sql> print n;
input output parameter->
----------------------(1)it is used to bind the variable with some inetialized value to the
procedure at run time.
(2)the va alue of variable which you are passing can be changed inside the proce
dure and
you can access that modified value outsde the procedure.
(3)to specify input output parameter you have to use "in out" keyword.
ex->
create or replace procedure p3(x in out int)
as
begin
x:=x+10;
end;
/
to execute->
sql> var x number;
sql> exec:x=10;
sql> call p3(:x);
sql> print x;
*using sql in stored procedure->
-------------------------------create table proctable(id int primary key , name varchar(12) , fee float);
inserting data into table->
-------------------------create or replace procedure insertInfo(sid int,snm varchar , sfee float)
as
begin
insert into proctable values(sid , snm, sfee);
end;

/
to invoke->
call insertInfo(11,'subhag',20000);
call insertInfo(12,'radha',25000);
call insertInfo(12,'ram'); // error
deleting data from table->
------------------------create or replace procedure deleteInfo(sid int)
as
begin
delete from proctable where id = sid;
end;
/
to invoke->
call deleteInfo(11);
udating data of table->
---------------------create or replace procedure updateInfo(sid int,snm out varchar,sfee in out float
)
as
begin
update proctable set fee = fee+sfee where id = sid;
select name,fee into snm,sfee from proctable where id=sid;
end;
/
to invoke->
var nm varchar2(10);
var fe number;
exec:fe:=1200;
call updateInfo(11,:nm,:fe);
dropping the procedure->
----------------------drop procedure <proc_name>;
ex-> drop procedure p1;
Trigger->A Trigger is a PL/SQL block that is invoked automatically by DBMS
-------- when insert,delete or update operation is executed on a databse table.
cursor->
------(1)it is a database object that holds the records returned by select satement.
(2)from cursor object you can access the record one by one;
(3)when we want to fetch multiple result from the table then we use "sys_refcurs
or"
at output parameter
ex->
create or replace procedure p6(emp out sys_refcursor)
as
begin
open emp for select * from employee;

end;
/
to execute->
sql>var empdata refcursor
sql>call p6(:empdata);
sql>print empdata;
special query(for mySql)->
------------------------create table account(aid int primary key,name varchar(20),email varchar(20),bal
float);
display record

You might also like