DBT 1-12 (1)
DBT 1-12 (1)
Database Concepts
MySQL v5.7 (RDBMS)
Intro to Oracle v11g (ORDBMS) (Object Relational DBMS) (RDBMS + OODBMS)
Intro to MongoDB v3.2 (NoSQL DBMS) (Not Only SQL) (type of DBMS)
MySQL
Origin of the word Computer -> Computaire (French word) -> to compute/calculate
Processing -> work done by the computer to convert the data into information
ANSI definition of DBMS -> collection of programs that allows you to insert, update, delete, and process
e.g. MS Excel, dBase, FoxBASE, FoxPro, Clipper, DataEase, Dataflex, Advanced Revelation, DB Vista, Quattro Pro, etc.
DBMS vs RDBMS
a. Field
b. Record
c. File
Oracle
- most popular (because it has best the best tools for s/w development)
- (makes programming very easy)
- product of Oracle Corporation (founded in 1977)
- #1 largest overall s/w company in the world
- #1 largest DB s/w company in the world
- 63% of world commercial DB market in Client-Server environment
- 86% of world commercial DB market in the Internet environment
- works on 113 OS
- 10/10 0f top 10 companies in the world use Oracle
Sybase
- going down
- recently acquired by SAP
MS SQL Server
- good RDBMS from Microsoft (17% of world commercial DB market)
- only works with Windows OS
MySQL
SQL
* Structured Query Language
* Commonly pronounced as "Sequel"
* Create, Drop, Alter
Insert, Update, Delete
Grant, Revoke, Select
* Conforms to ANSI standards (e.g. 1 character = 1 Byte)
* Conforms to ISO standards (for QA)
* Common for all RDBMS
* Initially founded by IBM (1975-77)
* Initially known as RQBE (Relational Query by Example)
* IBM gave RQBE free of cost to ANSI
* ANSI renamed RQBE to SQL
* Now controlled by ANSI
* In 2005, source code of SQL was rewritten in Java (100%)
MySQL Workbench
* MySQL client software
* Used for running SQL commands, MySQL commands, MySQL PL programs, etc.
* GUI based (Graphical User Interface) interface with database
MySQL PL
* MySQL Programming Language
* Programming language from MySQL
* Used for database programming
e.g. HRA_CALC, TAX_CALC, ATTENDANCE_CALC, etc.
MySQL Connectors
* for database connectivity (JDBC, ODBC, Python, C, C++, etc.)
MySQL Notifier
* Start-up and Shutdown the MySQL database
* Max 30 characters
* A - Z, a - z, 0-9 allowed
* Has to begin with an alphabet
* Special characters $, #, allowed
* In MySQL, to use reserved characters such as # in table name and
* Column name, enclose it in backquotes
* ` ` backquotes
e.g. `EMP#`
* 134 reserved words not allowed
Datatypes:-
Char (allows any character) (max upto 255 characters) (default width 1)
(wastage of HD space) (searching and retrieval is very fast)
e.g. ROLL NO, EMPNO, PANNO, etc.
Text
Mediumtext (allows any character) (max upto 16,777,215 characters) (16 MB)
Binary
(fixed length binary string) (max upto 255 Bytes of binary data) (e.g. small images)
(e.g. BARCODES, PICTURE_CODES, QR_CODES, FINGERPRINTS, SIGNATURES, etc.)
(width need not be specified)
VarBinary
(variable length binary string) (max upto 65,535 Bytes of binary data)
(e.g. STICKERS, EMOTICONS, EMOJIS, ICONS, etc.) (no default width) (width has to be specified)
* both of the above are stored as character strings of 1's and 0's
'1000-01-01' -> 1
'1000-01-02' -> 2
'1000-01-03' -> 3
'2021-06-22' -> 2456173 (number of days since '1000-01-01')
internally date is stored a fixed-length number
Date occupies 7 bytes of storage
Time ('hh:mm:ss') or ('HHH:MM:SS')
(Time values may range from 1-838:59:59' to '838:59:59')
datetime1-datetime2 -> returns number of days, remainder hours, remainder minutes, remainder seconds
between the two
My-SQL
* Max 4096 columns per table provided the row size <= 65,535 Bytes
* No limit on number of rows per table provided the table size <= 64 Terabytes
create table emp (empno char (4), ename varchar (25), sal float, city varchar (15), dob date );
";" is known as terminator (denotes the end of command)
insert into emp (empno, sal, ename, city, dob) values ('2', 6000, 'Mahesh', 'Mirzapur', '1991-06-08');
-> recommended
a. flexible
b. readable
c. in future if you alter the table, if you add a column, it will continue to work
insert into emp values ('1', 'A', 5000, 'Mumbai', '1990-04-05'), ('2', 'B', 5000, 'Delhi', '1991-06-15');
insert into emp (empno, sal) values ('1', 5000), ('2', 6000), ('3', 7000);
1)Read
2)Compile (convert into machine lang)
3)Plan (go to server HD search for table and return the output to my machine)
4)Execute
To restrict Columns: -
To restrict Rows: -
(Using WHERE clause)
Relational Operators: -
1. >
2. >=
3. <
4. <=
5. != or <>
6. =
select * from emp where sal > 2000 and sal < 3000;
Logical Operators: -
1. NOT
2. AND
3. OR
select * from emp where deptno = 10 or sal > 2000 and sal < 3000;
select * from emp where (deptno = 10 or sal > 2000) and sal < 3000;
select * from emp where job = 'MANAGER' and job = 'CLERK'; (no rows selected)
sal*12 -> computed column, derived column, virtual column, fake column, pseudo column
* Processing/calculation takes place in server RAM
Arithmetic Operators: -
1. () grouping
2. ** exponentials e.g. sal**3 means (sal^3)
** doesn't work in MySQL
** works in Oracle PL/SQL
In MySQL, if you want to use exponential then u have to use power function
3. / division
4. * multiplication
5. + addition
6. - subtraction
Installation: -
2. root
* Has Database Administrator DBA privileges
* Create users, assign privileges, configure database, perform planning, monitoring, tunning, take
backups, etc.
DAY3
select deptno, job, ename, sal, hiredate from emp order by ename ; (by name)
select deptno, job, ename, sal, hiredate from emp order by asc; (ascending)
select deptno, job, ename, sal, hiredate from emp order by desc; (descending)
select deptno, job, ename, sal, hiredate from emp order by deptno; (by deptno)
select deptno, job, ename, sal, hiredate from emp order by deptno, job;
(First it will sort on basis of deptno if deptno is same then it will sort on basis of job)
select deptno, job, ename, sal, hiredate from emp order by deptno desc,job desc;
* If you have large number of rows in the table, and large number of columns in ORDER BY clause, the SELECT
statement will be slow
select ename, sal*12 "Annual Salary" from emp order by "Annual Salary";
select ename, sal*12 "Annual Salary" from emp order by 2; (2 is column no in select statement)
select ename, sal*12 "Annual Salary" from emp order by "Annual Salary";
select * from emp where ename > 'A' and ename < 'B';
when you compare 2 strings of different lengths, the shorter of the 2 strings is temporarily padded on RHS with blank
spaces such that their lengths are equal; then it will start the comparison character by character based on ASCII value
select * from emp where ename >= 'A' and ename < 'B';
LIKE: -
select * from emp where ename like 'A%' or ename like 'a%';
select * from emp where ename like '%A'; (returns values ending with A)
select * from emp where ename like '%A%'; (returns values containing A)
select * from emp where ename like '__A%'; (returns values containing A as 3rd letter)
select * from emp where ename like '____'; (returns values containing 4 letters)
select * from emp where sal >= 2000 and sal <= 3000;
BETWEEN: -
select * from emp where sal between 2000 and 3000; -> recommended
* Easier to write
* Works faster
select * from emp where sal not between 2000 and 3000;
select * from emp where sal < 2000 or sal > 3000;
select * from emp where hiredate between '2020-01-01' and '20202-12-31';
select * from emp where hiredate >= '2020-01-01' and hiredate <= '20202-12-31';
select * from emp where ename >= 'A' and ename <= 'F';
UPDATE
update emp set sal = 10000 , city = 'Pune' where city = 'Mumbai';
* You can UPDATE multiple rows and multiple columns simultaneously, but you can UPDATE only 1 table at a
time
* If you want to UPDATE multiple tables simultaneously, it is not possible; you will require a separate UPDATE
command for each table
DROP
* UPDATE and DELETE commands without WHERE clause will not be allowed in MySQL Workbench
to issue UPDATE and DELETE commands without WHERE clause in MySQL Workbench: -
Click on Edit (menu at the top) -> Preference -> SQL Editor -> "Safe Updates" checkbox at the bottom -> uncheck it ->
click on Ok
COMMIT: -
* Commit will save all the DML changes since the last committed state
* When the user issues a Commit, it is known as End of Transaction
* Commit will make the Transaction permanent
commit work;
* Work is ANSI SQL
* Work in optional in Oracle and MySQL
ROLLBACK: -
rollback work;
* Rollback will undo all the DML changes since the last committed state
SAVEPOINT: -
ROLLBACK to SAVEPOINT: -
rollback to pqr;
* In a multi-user environment, when you SELECT from a table, you can view: -
* Only the committed data of all users
plus
changes made by you
ROW LOCKING: -
* When you UPDATE or DELETE a row, that row is automatically locked for other users
* ROW LOCKING IS AUTOMATIC IN MYSQL AND ORACLE
* When you UPDATE or DELETE a row, that row becomes READ ONLY for other users
* Other users can SELECT from that table; they will view the old data before your changes
* Other users can INSERT rows into that table
* Other users can UPDATE or DELETE "other" rows of that table
* No other user can UPDATE or DELETE your locked row, till you have issued a Rollback or Commit
* LOCKS ARE AUTOMATICALLY RELEASED WHEN YOU ROLLBACK OR COMMIT
Click on Query (menu at the top) -> New tab to current server -> click on it
* Now you will have 2 query windows to try out row locking
To abort the operation (to exit from the Request queue) -> Click on query (menu at the top) -> Click on Stop
* When you try to lock the row manually, if some other user has locked the same row before you, then by default
your request will wait in the Request Queue
select * from emp where deptno = 10 for update wait; -> (by default)
select * from emp where deptno = 10 for update wait 60; -> (time in SECONDS)
EMP
FNAME LNAME
----- -----
Arun Purun
Tarun Arun
Sirun Kirun
Nutan Purun
OUTPUT: - fname||lname
------------
ArunPurun
TarunArun
SirunKirun
NutanPurun
* || is supported by Oracle
* || is not supported by MySQL
CONCAT Strings: -
concat (str1, str2)
OUTPUT: - ArunPurun
TarunArun
SirunKirun
NutanPurun
UPPER case: -
OUTPUT: - ARUN
TARUN
SIRUN
NUTAN
select initcap (ename) from emp; -> supported by Oracle (not supported by MySQL)
OUTPUT: - Arun
Tarun
Sirun
Nutan
EMP Table
ENAME
----------
Arun Purun
Tarun Arun
Sirun Kirun
Nutan Purun
USES: -
a. Left justification of numeric data
b. to convert varchar to char
c. Centre-justification (use combo of lpad & rpad)
USES: -
a. Left justification
USES: -
a. Right justification of char data lpad(rtrim(ename),...)
b. to convert char to varchar
select substr(ename,3,2) from emp; -> (3 is starting position,2 is number of characters(gets 3rd & 4th letter))
select substr(ename,-3,2) from emp; -> (-3 is starting position, it will start from right side, we will get last 3
letters of the string)
USES: -
a. used to extract a part of string
select replace(ename,'un','xyz') from emp; -> will not work in MySQL 3rd parameter compulsory in MySQL
(Works in Oracle)
USES: -
a. Encoding and Decoding
b. Encryption and Decryption
c. Masking of ATM
d. Card Number
TRANSLATE: -
USES: -
a. used to check if one string exists in another string
* INSTR is available in MySQL but 3rd and 4th parameter not allowed in MySQL
LENGTH: - (returns the length of string)
In MySQL: -
-->> where utf8 is the given character set for US English else default binary character set
In Oracle: -
SOUNDEX: - (removes the vowels from both string and then compares) (a, e, i, o, u, y -> US))
In MySQL: -
sal float
In Oracle: -
sal number (7,3)
1234.567
In MySQL: -
select truncate(sal,0) from emp;
In Oracle: -
select trunc(sal) from emp;
select truncate (3.6,0), floor (3.6), truncate (-3.6,0), floor (-3.6) from dual;
3 3 -3 -4
Copyright® MH-19
SIGN: -
Returns -1, 0, 1
USES: -
1. check if num is +ve or -v
2. sign(SP-CP)
3. sign(temperature)
4. sign(blood_group)
5. sign(medical_report)
6. sign(bank_balance)
7. sign(sensex)
MOD: -
SQRT: -
POWER: -
x -> radians
sin(x)
cos(x)
tan(x)
sinh(x) -> not supported by MySQL (works in Oracle)
cosh(x) -> not supported by MySQL (works in Oracle)
tanh(x) -> not supported by MySQL (works in Oracle)
ln(y)
log(n,m)
Copyright® MH-19
Date and Time Functions: -
select sysdate() from dual; -> return date and time when the statement executed
select now() from dual; -> return date and time when the statement began to execute
select date_add(hiredate,interval 2 month) from dual; -> adds 2 months to the date
select date_add(hiredate,interval -2 month) from dual; -> subtracts 2 months to the date
select date_add(hiredate,interval 1 year) from dual; -> adds 1 year to the date
EMP
ename sal comm
----- ----- ------
A 5000 500
B 6000 null
C null 700
Copyright® MH-19
select * from emp where comm = null; -> returns null
OUTPUT: -
5500
null
null
select sal + ifnull(comm,0) from emp; -> if comm is null return 0, else return comm
OUTPUT: -
5500
6000
null
select ifnull(sal,0) + ifnull(comm,0) from emp; -> if sal is null return 0, else return sal, if comm is null
return 0, else return comm
OUTPUT: -
5500
6000
700
ifnull(comm,0)
ifnull(comm,100)
ifnull(city,'Goa')
ifnull(orderdate,'2021-04-01')
Copyright® MH-19
NVL: - (In Oracle)
nvl(comm,0)
nvl(comm,100)
nvl(city,'Goa')
nvl(orderdate,'01-APR-2021')
EMP
ename sal deptno
----- ----- -------
A 1000 10
B 2000 10
C 3000 20
D 4000 30
E 5000 40
OUTPUT: -
3000
3000
3000
4000
5000
greatest('str1','str2','str3','str4')
greatest('date1','date2','date3')
set x = greatest(a,b,c,d);
OUTPUT: -
1000
2000
3000
3000
3000
Copyright® MH-19
* Used to set an upper limit on some value
e.g., cashback = 10% of amt, max cashback = Rs. 10000
select least(amt*0.1,300) "CASHBACK" from ORDERS;
least('str1','str2','str3','str4')
least('date1','date2','date3')
set x = least(a,b,c,d);
CASE expression: -
select
case
when deptno = 10 then 'Training'
when deptno = 20 then 'Exports'
when deptno = 30 then 'Sales'
else 'Others'
end "DEPTNAME"
from emp;
OUTPUT: -
deptno DEPTNAME
------ ---------
10 Training
10 Training
20 Exports
30 Sales
40 Others
* If you don't supply ELSE and if some undefined value is present in the table, then it returns a null value
select
case
when deptno = 10 then 'Ten'
when deptno = 20 then 'Twenty'
when deptno = 30 then 'Thirty'
when deptno = 40 then 'Forty'
end "DEPTCODE"
from emp;
OUTPUT: -
deptno DEPTCODE
------ ---------
10 Ten
10 Ten
20 Twenty
30 Thirty
40 Forty
Copyright® MH-19
if sal < 3000 then REMARK = 'Low Income'
if sal = 3000 then REMARK = 'Middle Income'
if sal > 3000 then REMARK = 'High Income'
select
case
when sign(sal-3000) = 1 then 'High Income'
when sign(sal-3000) = -1 then 'Low Income'
else 'Middle Income'
end "REMARKS"
from emp order by 2;
EMP
empno ename sal deptno job mgr
------ ------ ----- ------ ------ -------
1 Arun 8000 1 M 4
2 Ali 7000 1 C 1
3 Kirun 3000 1 C 1
4 Jack 9000 2 M null
5 Thomas 8000 2 C 4
Single-Row Functions: -
* Will operate on 1 row at a time
* Character, Number, Date, List, Environment Functions e.g. upper (ename), round (sal), etc.
Multi-Row Functions: -
* Will operate on multiple rows at a time
* Group Functions
e.g. sum (sal), etc.
SUM: -
select sum(sal) from emp; -> 35000
EMP
empno ename sal deptno job mgr
------ ------ ----- ------ ------ -------
1 Arun 8000 1 M 4
2 Ali 7000 1 C 1
3 Kirun 3000 1 C 1
4 Jack 9000 2 M null
5 Thomas null 2 C 4
AVG: -
MIN: -
MAX: -
COUNT: -
select count(sal) from emp; -> 4 returns a COUNT of number of rows where sal is not
having a null value
select count(*) from emp; -> 5 returns a COUNT of total number of rows in the table
select count(*) from emp group by sal; -> counts no of rows with same salaries
Copyright® MH-19
sum(column)
avg(column)
min(column) min(ename),min(hiredata)
max(column) max(ename),max(hiredata)
count(column) count(ename),count(hiredata)
count(*)
stddev(column)
variance(column)
scott/tiger
* Regular user having connect, resource, create view privileges
* This user can be dropped
system/manager
* DBA privileges (similar to root user of MySQL)
* This user can be dropped
sys/change_on_install
* Owner of database
* Owner of system tables
* This user cannot be dropped
* Most important user
SQL> connect
SQL> create user <username> identified by <password>;
SQL> grant connect, resource, create view to <username>;
Copyright® MH-19
Day 6
Group Functions
SUMMARY REPORT: -
EMP
empno ename sal deptno job mgr
------ ------ ----- ------ ------ -------
1 Arun 8000 1 M 4
2 Ali 7000 1 C 1
3 Kirun 3000 1 C 1
4 Jack 9000 2 M null
5 Thomas 8000 2 C 4
sum(sal) deptwise: -
OUTPUT: -
deptno sum(sal)
--------- --------
1 18000
2 17000
Copyright® MH-19
1. Rows retrieved from DB server HD to server RAM (WHERE clause is used to retrieve the rows from DB server HD
to server RAM)
2. Sorting dept wise
3. Grouping dept wise
4. Summation dept wise
5. HAVING clause
6. ORDER BY clause
OUTPUT: - sum(sal)
--------
18000
17000
* Whichever column is present in GROUP BY clause, it may or may not be present in SELECT clause
select deptno, sum(sal) from emp where sal > 7000 group by deptno;
* WHERE clause is used to retrieve the rows from DB server HD to server RAM
* WHERE clause has to be specified before GROUP BY clause
* The position of columns in SELECT clause and the position of column in GROUP BY clause need not be same
* The position of columns in SELECT clause will determine the position of columns in the output
* The position of columns in GROUP BY clause will determine the sorting order, grouping order, summation
order and hence the speed of processing
* No upper limit on the number of columns in GROUP BY clause
HAVING clause: -
select deptno, sum(sal) from emp group by deptno having sum(sal) > 17000; -> its recommended that only
group functions should be
used in HAVING clause
Copyright® MH-19
* HAVING clause works after the summation takes place
select deptno, sum(sal) from emp group by deptno having sum(sal) > 7000; -> ERROR
select deptno, sum(sal) from emp group by deptno having deptno = 1; -> will work but it is inefficient
select deptno, sum(sal) from emp group by deptno having sum(sal) > 17000 and sum(sal) < 25000;
* In the HAVING clause you may use a group function that is not present in SELECT clause
select deptno, sum(sal) from emp where sal > 7000 group by deptno having sum(sal) > 10000 order by 1;
In Oracle: -
select max(sum(sal)) from emp group by deptno; -> nesting of GROUP Functions is allowed in
Oracle RDBMS (Not supported in any other RDBMS)
OUTPUT: - max(sum(sal))
------------
18000
Copyright® MH-19
In MySQL: -
select max(sum_sal) from (select sum(sal) as sum_sal from emp group by deptno) as tempp;
OUTPUT: - max(sum_sal)
------------
18000
MATRIX Report: -
select deptno, count(*), min(sal), max(sal), sum(sal) from emp gorup by deptno order by 1;
EMP
empno ename sal deptno job mgr
------ ------ ----- ------ ------ -------
1 Arun 8000 1 M 4
2 Ali 7000 1 C 1
3 Kirun 3000 1 C 1
4 Jack 9000 2 M null
5 Thomas 8000 2 C 4
DEPT
deptno dname location
------ ----- --------
1 TRN Bby
2 EXP Dlh
3 MKTG Cal
tablename.columnname
* In order for the join to work faster, preferably the driving table should be table with lesser number of rows
OUTPUT: -
ename dname
----- ------
Arun TRN
Ali TRN
Kirun TRN
Jack EXP
Thomas EXP
Copyright® MH-19
* The common column in both the tables, the column name need not to be same in both the tables,
because the same column may have a different meaning in the other table
* What matters is the datatype of the column has to match in both the tables, and there has to be some
sensible relation on whose basis you are writing the join
select deptno, dname, loc, ename, job, sal from emp, dept -> ERROR: column ambiguity defined
where dept.deptno = emp.deptno order by 1;
select dept.deptno, dname, loc, ename, job, sal from emp, dept
where dept.deptno = emp.deptno order by 1;
Types of Joins: -
Copyright® MH-19
OUTPUT: -
dname ename
----- ------
TRN Arun
TRN Ali
TRN Kirun
EXP Jack
EXP Thomas
OUTPUT: -
dname ename
----- ------
TRN Jack
TRN Thomas
EXP Arun
EXP Ali
EXP Kirun
MKTG Arun
MKTG Ali
MKTG Kirun
MKTG Jack
MKTG Thomas
3. OUTER JOIN
* Join with (+) sign (supported only in Oracle RDBMS & not supported by any other RDBMS)
* Shows matching rows of both the tables
plus
the non-matching rows of "OUTER" table
* Outer table -> table which is on Outer/Opposite side of = sign
* Used in Master-Detail Report (Parent-Child Report)
OUTPUT: -
dname ename
----- ------
TRN Arun
TRN Ali
TRN Kirun
EXP Jack
EXP Thomas
MKTG null
select dname, ename from emp, dept where dept.deptno (+) = emp.deptno; -> Left outer join
EMP
empno ename sal deptno job mgr
------ ------ ----- ------ ------ -------
1 Arun 8000 1 M 4
2 Ali 7000 1 C 1
3 Kirun 3000 1 C 1
4 Jack 9000 2 M null
5 Thomas 8000 2 C 4
6 Scott 6000 99
DEPT
deptno dname location
------ ----- --------
1 TRN Bby
2 EXP Dlh
3 MKTG Cal
OUTPUT: -
dname ename
----- ------
TRN Arun
TRN Ali
TRN Kirun
EXP Jack
EXP Thomas
null Scott
Copyright® MH-19
select dname, ename from emp, dept
where dept.deptno = emp.deptno (+)
union -> Full OuterJoin
select dname, ename from emp, dept
where dept.deptno (+) = emp.deptno;
OUTPUT: -
dname ename
----- ------
TRN Arun
TRN Ali
TRN Kirun
EXP Jack
EXP Thomas
MKTG null
null Scott
ANSI syntax for RIGHT Outer Join: - (supported by all RDBMS including MySQL & Oracle)
ANSI syntax for LEFT Outer Join: - (supported by all RDBMS including MySQL & Oracle)
ANSI syntax for FULL Outer Join: - (supported by all RDBMS except MySQL)
* You will have to take UNION of ANSI syntax for RIGHT outer join and ANSI syntax for LEFT outer join
INNER Join: - *****do not mention in interviews unless explicitly asked by interviewer
(jyada shanpatti nahi krneka)
* By default every join is INNER join, putting a (+) sign is what makes it an Outer Join
Copyright® MH-19
Select Day 7
OUTPUT: -
dname ename
----- -----
TRN Arun
TRN Ali
TRN Kirun
TRN Jack
TRN Thomas
EXP Arun
EXP Ali
EXP Kirun
EXP Jack
EXP Thomas
MKTG Arun
MKTG Ali
MKTG Kirun
MKTG Jack
MKTG Thomas
USES: -
* Used for printing purposes,
e.g. in the University, in STUDENTS table you have all the students names, in SUBJECTS table you have all the
subjects names; when you are printing the marksheet for the students, then every student name is combined
with each and every subject name, you will require a CARTESIAN JOIN
5. SELF JOIN
Copyright® MH-19
OUTPUT: -
a.ename b.ename
------- -------
Arun Jack
Ali Arun
Kirun Arun
Thomas Jack
EMP
empno ename sal deptno job mgr
------ ------ ----- ------ ------ -------
1 Arun 8000 1 M 4
2 Ali 7000 1 C 1
3 Kirun 3000 1 C 1
4 Jack 9000 2 M null
5 Thomas 8000 2 C 4
DEPT
deptno dname location
------ ----- --------
1 TRN Bby
2 EXP Dlh
3 MKTG Cal
DEPTHEAD
deptno dhead
------ -------
1 Arun
2 Jack
(5) (3) (2)
select dname, ename, dhead from emp, dept, depthead
where depthead.deptno = dept.deptno
and dept.deptno = emp.deptno;
OUTPUT: -
dname ename dhead
----- ----- ------
TRN Arun Arun
TRN Ali Arun
TRN Kirun Arun
EXP Jack Jack
EXP Thomas Jack
Types of Relationships: -
PROJECTS
pno pname clientname
---- ------ ----------
P1 CGS Deloitte
P2 AMS Morgan Stanley
P3 PPS ICICI Bank
P4 Macro Dev BNP Parivar
P5 Website Dev AMFI
EMP
empno ename sal deptno job mgr
------ ------ ----- ------ ------ -------
1 Arun 8000 1 M 4
2 Ali 7000 1 C 1
3 Kirun 3000 1 C 1
4 Jack 9000 2 M null
5 Thomas 8000 2 C 4
Copyright® MH-19
Display the ENAME who is receiving min(sal): -
OUTPUT: - Kirun
In Oracle: -
In MySQL: -
* You cannot UPDATE or DELETE from a table from which you are currently SELECTing
Solution: -
delete from emp where deptno = (select tempp.deptno from (select deptno from emp
where ename = 'Thomas') as tempp);
update emp set sal = 10000 where job = (select tempp.job from
(select job from emp where ename ='Kirun') as tempp);
Copyright® MH-19
Multi-row sub-queries: -
(sub-query returns multiple rows): -
Display all the rows who are receving the sal equal to any one of managers: -
1. Try to solve the problem using join instead of sub-query because using a join you solve the problem using
one SELECT statement whereas using sub queries you solve the problem using two or more SELECT statements;
the more the number of SELECT statements, the slower it will be
2. Try to reduce the number of levels of sub-queries
3. Try to reduce the number of rows returned by sub-query
EMP
empno ename sal deptno job mgr
------ ------ ----- ------ ------ -------
1 Arun 8000 1 M 4
2 Ali 7000 1 C 1
3 Kirun 13000 1 C 1
4 Jack 9000 2 M null
5 Thomas 8000 2 C 4
Display the rows who are receiving a sal greater than all of the Managers: -
Copyright® MH-19
Assumption, 3rd row sal is 3000: -
EMP
empno ename sal deptno job mgr
------ ------ ----- ------ ------ -------
1 Arun 8000 1 M 4
2 Ali 7000 1 C 1
3 Kirun 3000 1 C 1
4 Jack 9000 2 M null
5 Thomas 8000 2 C 4
In Oracle: -
OUTPUT: -
deptno sum(sal)
------ --------
1 18000
2 17000
OUTPUT: -
sum(sal)
--------
18000
17000
OUTPUT: -
max(sum(sal))
------------
18000
OUTPUT: -
deptno sum(sal)
------ --------
1 18000
Copyright® MH-19
select dname, sum(sal) from emp, dept
where dept.deptno = emp.deptno group by dname
having sum(sal) = (select max(sum(sal)) from emp group by deptno);
OUTPUT: -
dname sum(sal)
------ --------
TRN 18000
In MySQL: -
select deptno, sum(sal) from emp group by deptno;
OUTPUT: -
deptno sum(sal)
------ --------
1 18000
2 17000
OUTPUT: -
sum(sal)
--------
18000
17000
OUTPUT: -
max(sum_sal)
--------
18000
OUTPUT: -
deptno sum(sal)
------ --------
1 18000
OUTPUT: -
dname sum(sal)
TRN 18000
Copyright® MH-19
Day8
EMP
empno ename sal deptno job mgr
------ ------ ----- ------ ------ -------
1 Arun 8000 1 M 4
2 Ali 7000 1 C 1
3 Kirun 3000 1 C 1
4 Jack 9000 2 M null
5 Thomas 8000 2 C 4
DEPT
deptno dname location
------ ----- --------
1 TRN Bby
2 EXP Dlh
3 MKTG Cal
Solution 1: -
select deptno from emp;
OUTPUT: -
deptno
------
1
1
1
2
2
OUTPUT: -
deptno
------
1
2
OUTPUT: -
dname
------
TRN
EXP
Copyright® MH-19
select dname from dept where deptno in
(select distinct deptno from emp);
OUTPUT: -
dname
------
TRN
EXP
OUTPUT: -
dname
------
MKTG
Solution 2: -
select dname from emp, dept
where dept.deptno = emp.deptno;
OUTPUT: -
dname
------
TRN
TRN
TRN
EXP
EXP
OUTPUT: -
dname
------
TRN
EXP
Solution 3: -
* Whenever you have a join, along with DISTINCT, to make it work faster, use correlated sub-query
(Use the EXISTS operator)
* This is the exception when sub-query is faster than join
NOT EXISTS: -
OUTPUT: -
dname
------
MKTG
SET Operators: -
EMP1
empno ename
----- ------
1 A
2 B
3 C
EMP2
empno ename
----- ------
1 A
2 B
4 D
5 E
OUTPUT: -
empno ename
----- ------
1 A
2 B
3 C
4 D
5 E
Copyright® MH-19
union -> will combine the output of both the SELECTs and it will supress the duplicates
OUTPUT: -
empno1 ename
--------- ------
1 A
2 B
3 C
4 D
5 E
OUTPUT: -
empno1 ename
--------- ------
1 A
1 A
2 B
2 B
3 C
4 D
5 E
union all -> will combine the output of both the SELECTs and the duplicates are not supressed
INTERSECT: -
OUTPUT: -
empno1 ename
---------- ------
1 A
2 B
intersect -> will return what is common in both the SELECTs and it will supress the duplicates
Copyright® MH-19
MINUS: -
OUTPUT: -
empno1 ename
---------- ------
3 C
Minus -> will return what is present in first SELECT and what is present in second SELECT and
the duplicates are suppressed
select ...........................
union
select ...........................
minus
select ...........................
union
select ...........................
union all
select ...........................
intersect
select ...........................
order by x;
----------------------------------------
select ...........................
union
(select ...........................
minus
select ...........................)
union
(select ...........................
union all
select ...........................)
intersect
select ...........................
order by x;
Copyright® MH-19
PSEUDO Columns: -
INLINE VIEW -> if you use sub-query in the FROM clause, it is known as INLINE VIEW
ROWID: -
Copyright® MH-19
* ROWID is present in Oracle and you can view it
* ROWID is present in MySQL but you cannot view it
* ROWNUM is present in Oracle and you can view it
* ROWNUM is not present in MySQL
EMP
empno ename sal
------ ------ -----
101 Scott 5000
102 King 6000
* Rename a table
* Add, drop a column
* Increase width of column
INDIRECTLY: -
ADD a column: -
DROP a column: -
In MySQL: -
alter table emp modify ename varchar(30); -> data will get truncated
In Oracle: -
alter table emp modify ename varchar2(30);
Copyright® MH-19
* You can reduce the width provided the contents are null
alter table emp add x varchar2(25);
update emp set x = ename, ename = null;
alter table emp modify ename varchar2(20);
/* Data testing with x column */
update emp set ename = x;
alter table emp drop column x;
In Oracle: -
* You can change the datatype provided the contents are null
copy a table: -
Method 1: -
create table emp_struct as select * from emp;
delete from emp_struct;
commit;
Method 2: -
create table emp_struct as select * from emp;
truncate table emp_struct; -> will DELETE all the rows and COMMIT ALSO
DELETE TRUNCATE
DML command DDL command
Requires COMMIT Auto COMMIT
ROLLBACK possible ROLLBACK not possible
Can use WHERE clause with DELETE Cannot use WHERE clause with TRUNCATE
Free space is not deallocated Free space is deallocated
When you delete the rows delete triggers on table will When you truncate a table delete tables on triggers will
execute not execute
Copyright® MH-19
Method 3: -
RENAME a column: -
PRIVILEGES: -
GRANT / REVOKE (DCL commands)
GRANT: -
SCOTT_MYSQL> grant select on emp to public; -> public means all users
Copyright® MH-19
REVOKE: -
Copyright® MH-19
DAY9
INDEXES: -
Types of Indexes: -
1. Normal index
2. Unique index
3. Clustered index
4. Bitmap index
5. Index-Organized table
6. Index partitioning
NORMAL INDEX: -
* Present in all RDBMS, all DBMS, and some programming languages also
* To speed up the search operations (for faster access)
* To speed up SELECT statement with a WHERE clause
* Indexes are automatically invoked by MySQL as and when required
* Indexes are automatically updated by MySQL for all the DML operations
* Duplicate values are stored in index
* Null values are not stored in an index
* No upper limit on the number of indexes per table
* Larger the number of indexes, the slower would be the DML operations
* Cannot index TEXT and BLOB columns
* If you have multiple INDEPENDENT columns in the WHERE clause, then you should create separate indexes
for each column, MySQL will use the necessary indexes as and when required
EMP
rowid empno ename sal deptno
------- ------ ------ ----- ------
X001 5 A 5000 1
X002 4 A 6000 1
X003 1 C 7000 1
X004 2 D 9000 2
X005 3 E 8000 2
In Other RDBMS: -
IND_EMPNO
rowid empno
------- ------
X003 1
X004 2
X005 3
X002 4
X001 5
Copyright® MH-19
EMP
rowid empno ename sal deptno
------- ------ ------ ----- ------
X001 1 A 5000 1
X002 2 A 6000 1
X003 3 C 7000 1
X004 4 D 9000 2
X005 5 E 8000 2
IND_ENAME
rowid ename
------- ------
X001 A
X002 A
X003 C
X004 D
X005 E
IND_SAL
rowid sal
------- ------
X001 5000
X002 6000
X003 7000
X005 8000
X004 9000
EMP
rowid empno ename sal deptno
------- ------ ------ ----- ------
X001 1 A 5000 1
X002 2 A 6000 1
X003 3 C 7000 1
X004 1 D 9000 2
X005 2 E 8000 2
Copyright® MH-19
IND_DEPTNO_EMPNO
rowid deptno empno
------- ------ -----
X001 1 1 DEPTNO -> PRIMARY INDEX KEY
X002 1 2
X003 1 3 EMPNO -> SECONDARY INDEX KEY
X004 2 1
X005 2 2
COMPOSITE INDEX -> to combine two or more INTER-DEPENDENT columns in a single index,
also known as a COMPLEX INDEX
INDEX KEY -> column or set of columns on whose basis the index has been created
1. Read
2. Compile
3. Plan
4. Execute
EXECUTION PLAN -> plan created by MySQL as to how it is going to execute the SELECT statement
IND_EMPNO
rowid empno
------- ------
X001 1
X002 2
X003 3
X004 4
X005 5
DEPT
rowid deptno dname location
------ ------ ----- --------
Y011 1 TRN Bby
Y012 2 EXP Dlh
Y013 3 MKTG Cal
Copyright® MH-19
I2
rowid deptno
------- ------
X001 1
X002 1
X003 1
X004 2
X005 2
I1
rowid deptno
------- ------
Y011 1
Y012 2
Y013 3
i_emp_empno
rowid empno
------- ------
X001 1
X002 2
X003 3
X004 4
X005 5
select * from emp where empno = 1; -> Execute very fast (makkhan ke mafik)
IN MySQL: -
drop index i_emp_empno on emp;
IN Oracle: -
drop index i_emp_empno;
create index i_orders_onum on emp(onum desc); -> latest (new) orders will stored first at the
top,older orders would be below
to see which all indexes are created for specific table: -
use information_schema;
select * from statistics;
* If you create a table using sub-query, then indexes created on original table will not be copied into the new
table, if you want then you have to create them manually
UNIQUE INDEX: -
* Works like a normal index, but it performs one extra function, it will not allow you to INSERT duplicate
values for empno
* Oracle & MySQL doesn't allow more than one indexes on same column
EMP
empno ename sal deptno
------ ------ ----- ------
1 A 5000 1
2 A 6000 1
3 C 7000 1
4 D 9000 2
5 E 8000 2
Copyright® MH-19
CONSTRAINTS: - (V. IMP)
* Combine 2 or more INTER-DEPENDENT columns together to serve the purpose of Primary Key
* In MySQL, you can combine upto 32 columns in a composite Primary Key
* If you declare a composite Primary Key, then the index that is created automatically, happens to be
composite unique index
* If you cannot identify some key column, then you add an extra column to the table to serve the purpose
of Primary Key, such a key is known as SURROGATE KEY
* For SURROGATE KEY, CHAR datatype is recommended
* YOU CAN HAVE ONLY 1 PRIMARY KEY PER TABLE
* it's good to have couple of candidate keys in your table, because in future if you ALTER your table and DROP
the Primary Key column, then your table is left without a Primary Key, in that situation you can make 1 of
your candidate key columns as the new Primary Key
NOT NULL
* Null values are not allowed (it's a mandatory column)
* Duplicate values are allowed
* Can have any number of not null constraints per table
* Always a column level constraint
create table emp (empno char(4), ename varchar(25) not null, sal float not null, deptno int);
desc emp;
ALTERNATE KEY -> for a candidate key column, if you apply a not null constraint and you create a unique
index, then it works similar to Primary Key, it becomes an ALTERNATE to Primary Key,
such a candidate key column is known as ALTERNATE KEY
SUPER KEY -> if you have a Primary Key and Alternate key in the table, then the Primary Key is
also known as SUPER KEY
Copyright® MH-19
UNIQUE
mob_no
deptno
* Column level constraint can be specified at table level, but a table level composite constraint can never
be specified at column level
* Column level constraint can be specified at table level, except for the not null constraint which is always
a column level and therefore the syntax will not support specifying it at the end of the structure
Copyright® MH-19
Day10
CONTRAINTS: -
FOREIGN KEY: -
* Column or set of columns that references a column or set of columns of some table
* Foreign key constraint is specified on the child column (not the parent column)
* Parent column has to be PRIMARY Key or UNIQUE
* Foreign Key will allow duplicate values (unless specified otherwise)
* Foreign Key will allow null values (unless specified otherwise)
* Foreign Key may reference a column of the same table also (known as self-referencing)
EMP
empno ename sal deptno mgr
------ ------ ----- ------ -------
1 A 5000 1 1
2 B 6000 1 1
3 C 7000 1 1
4 D 9000 2 2
5 E 8000 2 2
6 F 9000 2 2
DEPT
deptno dname location
------ ----- --------
1 TRN Bby
2 EXP Dlh
3 MKTG Cal
* You can delete the parent row provided child row don't exist
delete from dept where deptno =3;
* You cannot delete the parent row when child rows exist
delete from dept where deptno = 2;
ON DELETE CASCADE -> if you delete the parent row then it will automatically delete the child rows also
Copyright® MH-19
* You can update the parent column provided the child rows don't exist
update dept set deptno = 4 where deptno = 3;
* You cannot update the parent column when child rows exist
update dept set deptno = 4 where deptno = 2;
ON UPDATE CASCADE -> if you update the parent column then it will automatically update the child
rows also
ORDER_MST
branch_cd onum cnum odate -> Parent
------------- -------- -------- --------
B1 1
B1 2
B1 3
B2 1
B2 2
ORDER_DTLS
branch_cd onum prod_cd qty -> Child
------------- ------- ---------- -----
B1 1 DVD 10000
B1 1 USB 20000
CHECK CONSTRAINT: -
Copyright® MH-19
DEFAULT is not a constraint
DEFAULT is a clause that you can use with CREATE TABLE
* If you specify some value, then it will take that value
* If nothing is specified, then it will take default value
to make use of DEFAULT value and AUTO_INCREMENT, use the following INSERT statement: -
insert into emp (ename,deptno,comm,mob_no)
values ( ...................................... ) ;
MySQL
Data is of 2 types: -
1. User Data
* User created
* User tables and indexes
STORED OBJECTS: -
VIEWS: -
* Handle to a table
* Stores the address of table (HD pointer) (also known as LOCATOR)
* Used for indirect access to the table
* USED FOR SECURITY PURPOSES
* Used to restrict the access of the users
* VIEWS are in all RDBMS and some DBMS also
EMP
empno ename sal deptno
------ ------ ----- ------
1 A 5000 1
2 B 6000 1
3 C 7000 1
4 D 9000 2
5 E 8000 2
Copyright® MH-19
MYSQL> create view viewname .............;
OUTPUT: -
empno ename
------ ------
1 A
2 B
3 C v1 = select empno, ename from emp;
4 D
5 E
* Constraints specified on the base table will be enforced when you INSERT via the view
Copyright® MH-19
edac_mysql> create view v2 as select * from emp where deptno = 1;
OUTPUT: -
empno ename sal deptno
------ ------ ----- ------
1 A 5000 1
2 B 6000 1
3 C 7000 1
--------------------------------------------------------------------------
scott_mysql> insert into cdac.v2 values (6, 'F', 6000, 2 ); -> ERROR
* View with check option (like having different check constraints for different users, which otherwise is not
possible)
desc emp;
desc v1;
--------------------------------------------------------------
* View based on computed column; it is recommended you specify an alias for the virtual column
* Can only SELECT from this view
* DML operations are not allowed
* Common for all RDBMS
Copyright® MH-19
create or replace view v1 as
select upper(ename) as u_name, sal from emp;
* View based on GROUP BY clause, it is recommended you specify an alias for the virtual column
show tables; -> will show tables and views but it won't tell which is a table and which is a view
USES: -
* To exceed 255 levels limit of function within function
* To exceed 255 SELECT statements limit for SET operators
e.g., UNION of 300 SELECTs
* To exceed 255 levels limit of sub-queries
* To simplify the writing of complex SELECT statements
e.g., JOIN of 20 tables
* Complex queries can be stored in view definition
(e.g., join of 10 tables)
* To convert 3D table into 2D table
* To convert 2D table into 3D table
* To apply Relational methods on Object tables
* To apply Object methods on Relational tables
* Data mapping
* Data migration
* EAI (Enterprise Application Integration)
* EIM (Enterprise Integration Management)
Copyright® MH-19
MySQL - PL
* MySQL programming language
* Programming language of MySQL
* Used for database programming
e.g., HRA_CALC, TAX_CALC, ATTENDANCE_CALC, etc.
* Used for server-side data processing
* MySQL - PL program can be called in MySQL command line client, MySQL Workbench, Oracle Forms,
Oracle Reports, Oracle Menus, Oracle Graphics, Oracle Apex, Java, etc.
* Few 4 GL features (supports few OOPS features)
begin
..................
begin
.....................
.....................
end;
...................
end;
* Screen input and screen output is not allowed (scanf, printf, etc are not available)
* Used ONLY for processing
* Can use SELECT statement inside the block but it's not recommended
* SQL commands that are allowed in MySQL PL are : -
DDL, DML, DQL, DTL/TCL
* DCL commands not allowed inside the MySQL PL block
TEMPP
FIR SEC
------ --------
Copyright® MH-19
* MySQL PL programs are written in the form of stored procedures
STORED OBJECTS: -
STORED PROCEDURES: -
PROGRAM 1: -
call abc();
if you don't want procedure in future then you can drop it: -
Copyright® MH-19
Day11
PROGRAM 2: -
delimiter //
create procedure abc()
begin
declare x int; -> scope of x is limited to this block (local variable)
set x = 10;
insert into tempp values(x, 'inside abc');
end; //
delimiter ;
* In MySQL PL, when you declare a variable, if you don't initialize it, it will store a null value
* You can declare a variable and assign a value simultaneously
delimiter //
create procedure abc()
begin
declare x int default 10;
insert into tempp values(x, 'inside abc');
commit; -> optional
end; //
delimiter ;
PROGRAM 2: -
delimiter //
create procedure abc()
begin
declare x char(15) default 'CDAC';
insert into tempp values(1, x);
end; //
delimiter ;
OUTPUT: -
TEMPP
FIR SEC
------ --------
1 CDAC
PROGRAM 3: -
Write a program for HRA calculation ,HRA = 40% of sal : -
delimiter //
create procedure abc()
begin
declare x char(15) default 'KING';
declare y float default 3000
declare z float default 0.4;
declare hra float;
set hra = y*z;
insert into tempp values(y, x);
insert into tempp values(hra, 'HRA');
end; //
delimiter ;
delimiter //
create procedure abc( x char(15), y float, z float) -> PARAMETERIZED Procedure
begin
declare hra float;
set hra = y*z;
insert into tempp values(y, x);
insert into tempp values(hra, 'HRA');
end; //
delimiter ;
----------------------------------------------------------------------------
EMP
ename sal job
--------- --------- ---------
SCOTT 3000 CLERK
KING 5000 MANAGER
delimiter //
create procedure abc()
begin
declare x int;
select sal into x from emp
where ename = 'KING';
/* processing, e.g. set hra = x*0.4 */
insert into tempp values(x , 'KING');
end; //
delimiter ;
delimiter //
create procedure abc(y char (15))
begin
declare x int;
select sal into x from emp
where ename = y ;
/* processing, e.g. set hra = x*0.4 */
insert into tempp values(x , 'KING');
end; //
delimiter //
create procedure abc()
begin
declare x int;
declare y char(15);
select sal, job into x, y from emp
where ename = 'KING' ;
/* processing, e.g. set hra = x*0.4; set y = lower(y), etc. */
insert into tempp values(x , y);
end; //
delimiter ;
delimiter // EMP
create procedure abc() ename sal
begin --------- ---------
declare x int; KING 5000
select sal into x from emp
where ename = 'KING' ;
if x > 4000 then
insert into tempp values(x , 'High Sal');
end if;
end; //
delimiter ;
delimiter //
create procedure abc()
begin
declare x int;
select sal into x from emp
where ename = 'KING' ;
if x > 4000 then
insert into tempp values(x , 'High Sal');
else
if x < 4000 then
insert into tempp values(x , 'Low Sal');
else
insert into tempp values(x , 'Medium Sal');
end if;
end if;
end; //
delimiter ;
ELSEIF construct: -
delimiter //
create procedure abc()
begin
declare x int;
select sal into x from emp
where ename = 'KING' ;
if x > 4000 then
insert into tempp values(x , 'High Sal');
elseif x < 4000 then
insert into tempp values(x , 'Low Sal');
else
insert into tempp values(x , 'Medium Sal');
end if;
end; //
delimiter ;
delimiter //
create procedure abc()
begin
declare x boolean default TRUE;
if x then
insert into tempp values(1 , 'Mumbai');
end if;
end; //
delimiter ;
OUTPUT: -
TEMPP
FIR SEC
------ --------
1 Mumbai
delimiter //
create procedure abc()
begin
declare x boolean default FALSE;
if not x then
insert into tempp values(1 , 'Delhi');
end if;
end; //
delimiter ;
WHILE loop: -
* Check for condition before entering the loop
Syntax: -
WHILE expression DO
............................................;
............................................;
END WHILE;
delimiter //
create procedure abc()
begin
declare x int default 1;
while x < 10 do
insert into tempp values(x , 'in while loop');
set x = x+1;
end while;
end; //
delimiter ;
OUTPUT: -
TEMPP
FIR SEC
------ --------
1 in while loop
2 in while loop
3 in while loop
4 in while loop
5 in while loop
6 in while loop
7 in while loop
8 in while loop
9 in while loop
delimiter //
create procedure abc()
begin
declare x int default 1;
declare y int default 1;
while x < 10 do
while y < 10 do
insert into tempp values(y , 'in y loop');
set y = y+1;
end while;
insert into tempp values (x, 'in x loop')
set x = x+1;
end while;
end; //
delimiter ;
OUTPUT: -
TEMPP
FIR SEC
1 in y loop
2 in y loop
.
.
.
9 in y loop
1 in x loop
2 in x loop
.
.
.
8 in x loop
9 in x loop
delimiter //
create procedure abc()
begin
declare x int default 1;
declare y int default 1;
while x < 10 do
while y < x do
insert into tempp values(y , 'in y loop');
set y = y+1;
end while;
insert into tempp values (x, 'in x loop')
set x = x+1;
end while;
end; //
delimiter ;
Syntax: -
REPEAT
......................................;
......................................;
UNTIL expression_is_not_satisfied
END REPEAT;
delimiter //
create procedure abc()
begin
declare x int default 1; (try for x = 100)
repeat
insert into tempp values(x , 'in loop');
set x = x+1;
until x > 5
end repeat;
end; //
delimiter ;
OUTPUT: -
TEMPP
FIR SEC
1 in loop
2 in loop
3 in loop
4 in loop
5 in loop
LEAVE statement -> allows you to exit the loop (similar to 'break' statement)
ITERATE statement -> allows you to skip the entire code under it, and start a new iteration
(similar to 'continue' statement)
LOOP statement -> executes a block of code repeatedly with an additional flexibility of using
LOOP LABEL (you can give a name to a loop)
delimiter //
create procedure abc()
begin
declare x int default 1;
pqr_loop:loop -> LABEL
if x > 10 then
leave pqr_loop;
end if;
set x = x + 1;
if mod(x,2) != 0 then
iterate pqr_loop;
else
insert into tempp values (x , 'inside loop');
end if;
end loop;
end; //
delimiter ;
OUTPUT: -
TEMPP
FIR SEC
------ --------
2 inside loop
4 inside loop
6 inside loop
8 inside loop
10 inside loop
Session Variables: -
* Global variables
* Create and initialize simultaneously
* Available in the server RAM till you end your session
* You can manipulate session variables
TEMPP
fir sec
------- --------
* Present in all RDBMS, some DBMS, and some front-end s/w's also
* CURSOR is a type of a variable
* CURSOR can store multiple rows
* CURSOR is similar to 2D ARRAY
* CURSORS are used for processing multiple rows
* CURSORS are used for storing multiple rows
* CURSORS are used for handling multiple rows
* CURSORS are used for storing the data temporarily
* CURSOR is based on SELECT statement in MySQL
* CURSOR is a READ_ONLY variable
* You will have to fetch 1 row at a time into some intermediate variables and do your processing with
those variables
* Can only fetch sequentially (top to bottom)
* YOU CANNOT FETCH BACKWARDS IN A CURSOR
* Can only fetch 1 row at a time
delimiter //
create procedure abc()
begin
declare a int;
declare b varchar(15);
declare c int;
declare d int;
declare x int default 1;
declare c1 cursor for select * from emp; -> CURSOR Declaration/Definition
open c1; -> opens the CURSOR and fires the SELECT statement
while x < 6 do (try x < 4, x < 11)
fetch c1 into a,b,c,d;
/* processing, e.g. set hra_calc = c*0.4, etc
update emp set hra = hra_calc where empno = a */
insert into tempp values(a, b);
set x = x + 1;
end while;
close c1; -> will close the cursor and it will free the RAM
end; //
delimiter;
OUTPUT: -
TEMPP
fir sec
------- --------
1 A
2 B
3 C
4 D
5 E
delimiter //
create procedure abc()
begin
declare a int;
declare b varchar(15);
declare c int;
declare d int;
declare x int default 0;
declare y int;
declare c1 cursor for select * from emp;
select count(*) into y from emp;
open c1;
while x < y do
fetch c1 into a,b,c,d;
insert into tempp values(a, b);
set x = x + 1;
end while;
close c1;
end; //
delimiter;
delimiter //
create procedure abc()
begin
declare a int;
declare b varchar(15);
declare c int;
declare d int;
declare finished int default 0;
declare c1 cursor for select * from emp;
declare continue handler for not found set finished = 1;
open c1;
cursor_c1_loop : loop
fetch c1 into a,b,c,d;
if finished = 1 then
leave cursor_c1_loop;
end if;
insert into tempp values(a, b);
end loop cursor_c1_loop;
close c1;
end; //
delimiter;
* NOT FOUND IS A CURSOR ATTRIBUTE, IT RETURNS A BOOLEAN TRUE VALUE IF THE LAST FETCH WAS
UNSUCCESSFUL
delimiter //
create procedure abc()
begin
declare a varchar(15);
declare b int;
declare finished int default 0;
declare c1 cursor for select ename, sal from emp;
declare continue handler for not found set finished = 1;
open c1;
cursor_c1_loop : loop
fetch c1 into a,b;
if finished = 1 then
leave cursor_c1_loop;
end if;
insert into tempp values(b, a);
end loop cursor_c1_loop;
close c1;
end; //
delimiter;
OUTPUT: -
TEMPP
fir sec
------- --------
5000 A
6000 B
7000 C
9000 D
8000 E
close c1;
open c1;
delimiter //
create procedure abc()
begin
declare a int;
declare b varchar(15);
declare c int;
declare d int;
declare finished int default 0;
declare c1 cursor for select * from emp where deptno = 1;
declare continue handler for not found set finished = 1;
open c1;
cursor_c1_loop : loop
fetch c1 into a, b, c, d;
if finished = 1 then
leave cursor_c1_loop;
end if;
insert into tempp values(a, b);
end loop cursor_c1_loop;
close c1;
end; //
delimiter;
CURSOR C1
l_name bonus
------ -----
a 5500
b 6500
c 7500
d 9500
e 8500
OUTPUT: -
TEMPP
fir sec
------- --------
5500 a
6500 b
7500 c
9500 d
8500 e
delimiter //
create procedure abc()
begin
declare a varchar(15);
declare b int;
etc.
declare finished int default 0;
declare c1 cursor for select * from dept;
declare c2 cursor for select * from dept;
declare continue handler for not found set finished = 1;
open c1;
open c2;
cursor_c1_loop : loop
fetch c1 into a, b;
if finished = 1 then
leave cursor_c1_loop;
end if;
insert into tempp values(a, b);
end loop cursor_c1_loop;
close c1;
end; //
delimiter;
* IN MySQL, NO UPPER LIMIT ON THE NUMBER OF CURSORS THAT CAN BE OPENED AT A TIME
delimiter //
create procedure abc()
begin
declare a varchar(15);
declare b int;
etc.
declare finished int default 0;
declare c1 cursor for select empno, dname from emp, dept
where dept.deptno = emp.deptno;
declare continue handler for not found set finished = 1;
open c1;
cursor_c1_loop : loop
fetch c1 into a, b;
if finished = 1 then
leave cursor_c1_loop;
end if;
insert into tempp values(a, b);
end loop cursor_c1_loop;
close c1;
end; //
delimiter;
जळगांव चे DEVELOPERS Copyright® MH-19
CURSOR C1
empno dname
-------- ---------
1 TRN
2 TRN
3 TRN
4 EXP
5 EXP
OUTPUT: -
TEMPP
fir sec
-------- ---------
1 TRN
2 TRN
3 TRN
4 EXP
5 EXP
delimiter //
create procedure abc()
begin
declare a int;
declare b varchar(15);
declare c int;
declare d int;
declare finished int default 0;
declare c1 cursor for select * from emp;
declare continue handler for not found set finished = 1;
open c1;
cursor_c1_loop : loop
fetch c1 into a, b, c, d;
if finished = 1 then
leave cursor_c1_loop;
end if;
update emp set sal = sal + 1;
end loop cursor_c1_loop;
close c1;
end; //
delimiter;
CURSOR C1
empno ename sal deptno
------ ----- ------ ---------
1 A 5000 1
2 B 6000 1
3 C 7000 1
4 D 9000 2
5 E 8000 2
delimiter //
create procedure abc()
begin
declare a int;
declare b varchar(15);
declare c int;
declare d int;
declare finished int default 0;
declare c1 cursor for select * from emp for update; -> LOCKS THE ROWS
declare continue handler for not found set finished = 1;
open c1;
cursor_c1_loop : loop
fetch c1 into a, b, c, d;
if finished = 1 then
leave cursor_c1_loop;
end if;
if c > 7000 then
update emp set sal = sal + 1 where empno = a;
end if;
end loop cursor_c1_loop;
close c1;
commit; -> LOCKS ARE AUTOMATICALLY RELEASED WHEN
end; // YOU ROLLBACK OR COMMIT
delimiter;
Types of CURSORS: -
1. EXPLICIT CURSOR
* User/programmer created
* Have to be declared explicitly
* Used for storing/processing multiple rows
* USED TO LOCK THE ROWS MANUALLY
BEFORE YOU ISSUE UPDATE OR DELETE, YOU SHOULD LOCK THE ROWS MANUALLY: -
* TO LOCK THE ROWS MANUALLY, YOU WILL REQUIRE A CURSOR WHOSE SELECT STATEMENT IS HAVING A
FOR UPDATE CLAUSE; SIMPLY OPEN THE CURSOR AND THEN CLOSE IT; THE ROWS OF THE TABLE WILL
REMAIN LOCKED TILL YOU ISSUE A ROLLBACK OR COMMIT: -
...........................;
..................................;
declare c1 cursor for select * from emp for update;
open c1;
close;
......................;
IN (BY DEFAULT)
* Read only
* Can pass constant, variable, expression
* Call by value
* FASTEST in terms of processing speed
delimiter //
create procedure abc(in y int) -> IN is optional
begin
insert into tempp values(y, 'inside abc');
end; //
delimiter ;
call abc(5);
set @x = 10;
call abc(@x);
set @x =10;
call abc(2*@x+5);
OUTPUT: -
TEMPP
fir sec
-------- ---------
5 inside abc
10 inside abc
25 inside abc
* Write only
* Can pass variables only (constants and expressions are NOT ALLOWED)
* Call by reference
* Procedure can return a value indirectly if you call by reference
* Used on public network
delimiter //
create procedure abc(out y int)
begin
set y = 100;
end; //
delimiter ;
जळगांव चे DEVELOPERS Copyright® MH-19
set @x = 10;
select @x from dual; -> 10
delimiter //
create procedure abc(inout y int)
begin
set y = y*y*y;
end; //
delimiter ;
set @x = 10;
select @x from dual; -> 10
STORED OBJECTS: -
1. Deterministic
2. Not-Deterministic
* For the same input parameters, if the stored function returns the same result, it is considered deterministic,
and otherwise the stored function is not-deterministic.
* You have to decide whether a stored function is deterministic or not.
* If you declare it incorrectly, the stored function may produce an unexpected result, or the available
optimization is not used which degrades the performance.
delimiter //
create function abc()
returns int
deterministic
begin
return 10;
end; //
delimiter ;
delimiter //
create procedure pqr()
begin
declare x int;
set x = abc();
insert into tempp values(x, 'after abc');
end; //
delimiter ;
call pqr();
OUTPUT: -
TEMPP
fir sec
-------- ---------
10 after abc
----------------------------------------------------------------------------------------------
delimiter //
create function abc(y int)
returns int
deterministic
begin
return y*y;
end; //
delimiter ;
call pqr();
OUTPUT: -
TEMPP
fir sec
-------- ---------
100 after abc
INTERVIEW QUESTION: -
****What is similarity between STORED PROCEDURE and STORED FUNCTION?
****What is difference between STORED PROCEDURE and STORED FUNCTION?
- Stored function can be called in select statement
- Stored function can be called in SQL statements
select abc(sal) from emp;
select abc(10) from dual;
delete from emp where abc(sal) = 100000;
delimiter //
create function abc(y int)
returns int
deterministic
begin
if y > 5000 then
return TRUE;
else
return FALSE;
end if;
end; //
delimiter ;
delimiter //
create procedure pqr()
begin
declare x int;
select sal into x from emp where ename = 'KING';
if abc(x) then
insert into tempp values(x, '> 5000');
else
insert into tempp values(x, '<= 5000');
end if;
end; //
delimiter ;
call pqr();
OUTPUT: -
TEMPP
fir sec
-------- ---------
9000 > 5000