Oracle Batch32
Oracle Batch32
Oracle Batch32
oracle :-
1 sql
2 pl/sql
Database :-
---------------
univ db bank db
students customers
courses accounts
faculty loans
colleges employees
Types of Databases :-
------------------------------
=> organizations uses OLTP DB for storing day-to-day transactions and OLAP for analysis.
=> OLTP is for running business and OLAP is for to analyze business.
=> day-to-day operations on db includes
C create
R read
U update
D delete
DBMS :-
-----------
Evolution of DBMS :-
----------------------------
Types of DBMS :-
----------------------
HDBMS
NDBMS
RDBMS
ORDBMS
RDBMS :-
--------------
Informtion rule :-
-------------------------
=> according to information rule data must be organized in tables i.e. rows and columns
CUST
CID NAME ADDR => COLUMNS / FIELDS / ATTRIBUTES
10 A HYD
11 B BLR => ROW / RECORD / TUPLE
=> every table must contain primary key to uniquely identify the records
ex :- accno,empid,aadharno,panno,voterid
RDBMS features :-
----------------------------
NoSQL Databases :-
--------------------------
MongoDB
cassandra
20-apr-24
ORDBMS :-
----------------
==============================================================
ORACLE
=======
=> oracle is basically rdbms software and also supports features of ordbms
and used to manage database.
versions of oracle :-
---------------------------
History :-
------------
versions :-
---------------
2,3,4,5,6,7,8i,9i,10g,11g,12c,18c,19c,21c,23c
i => intenet
g => grid
c => cloud
=> from version 8 onwards suffix "i" is added because from 8 onwards
oracle supports internet applications i.e. oracle db can used for
web applications.
=> grid means collection of servers , from 10g onwards oracle db can
accessed through multiple servers and adv of grid is if one server is
down we can access db through another server.
=> from 12c onwards oracle db can be deployed in
1 on premises server
2 cloud server
=> " on cloud " db is deployed in the server managed by cloud service provider
cloud reduces initial investment for client.
1 server
2 client
server :-
------------
1 DB
2 INSTANCE
CLIENT :-
---------------
1 connects to server
2 submit requsts to server
3 receives response from server
client tool :-
---------------
USER-----JDBC-----------------------------------ORACLE-------------DB
SQL :-
---------
=> sql is introduced by IBM and initial name was "SEQUEL" and later it is
renamed to SQL.
USER-----SQLPLUS-------------SQL-----------------ORACLE-------------DB
USER---MYSQLWORKBENCH------------SQL------------MYSQL--------DB
USER-----SSMS-----------------------------SQL--------------SQL SERVER-----DB
SQL
SCHEMA :-
----------------
SERVER
DATABASE
USER
TABLE
DATA
SERVER
XE
SYS / MANAGER (admin)
SYSTEM / MANAGER (admin)
=> to connect to oracle open sqlplus and enter username & password
USERNAME :- SYSTEM
PASSWORD :- MANAGER
OR
USERNAME :- SYSTEM/MANAGER
syntax :-
-----------
Example :-
Datatypes in ORACLE :-
----------------------------------
DATATYPES
ex :- NAME CHAR(10)
sachin----
wasted
ravi------
wasted
=> in CHAR datatype extra bytes are wasted , so don't use char for variable
length fileds and use char for fixed length fields
ex :- GENDER CHAR(1)
M
F
STATE_CODE CHAR(2)
AP
TG
COUNTRY_CODE CHAR(3)
IND
USA
VARCHAR2(size) :-
---------------------------
ex :- NAME VARCHAR2(10)
sachin----
released
ravi------
released
=> char / varchar2 allows ascii chars (256) that includes A-Z,a-z,0-9,special chars
i.e. char / varchar2 allows alphanumeric data.
ex :- PANNO CHAR(10)
ASKD-----
VEHNO CHAR(10)
TS09AB1234
EMAILID VARCHAR2(20)
LONG :-
-----------
ex :- review LONG
ex :- TEXT CLOB
=> allows unicode chars (65536) that allows all ascii and also chars belongs to
different languages.
NUMBER(P) :-
---------------------
=> allows numbers without decimal (integers) upto 38 digits
EX :- EMPID NUMBER(4)
10
100
1000
10000 => NOT ALLOWED
AADHARNO NUMBER(12)
PHONE NUMBER(10)
ACCNO NUMBER(12)
NUMBER(P,S) :-
-----------------------
ex :- SALARY NUMBER(7,2)
5000
5000.55
50000.55
500000.55 => not allowed
BALANCE NUMBER(11,2)
SAVG NUMBER(5,2)
DATE :-
----------
ex :- DOB DATE
TIMESTAMP :-
--------------------
ex :- T TIMESTAMP
Binary Types :-
--------------------
=> bfile is called external lob because lob stored outside db and db stores path
=> blob is called internal lob because lob stored inside db
24-apr-24
Rules :-
----------
Exampe :-
EMP
EMPID ENAME JOB SAL HIREDATE DNO
USER---SQLPLUS---------------CREATE TABLE------------------ORACLE-------------DB
=> above command created table structure / definition / metadata that includes
columns,datatype and size.
DESC :- (DESCRIBE)
---------------
Ex :-
SQL>DESC EMP
EMPID NUMBER(4)
ENAME VARCHAR2(10)
JOB VARCHAR2(10)
SAL NUMBER(7,2)
HIREDATE DATE
DNO NUMBER(2)
Question :-
CUST
CUSTID NAME GENDER DOB AADHARNO PANNO ADDR CITY STATE PHONE
PHOTO EMAILID
1 single row
2 multiple rows
Ex :-
NOTE :-
=> above insert commands inserted data into instance (ram) to save this data execute
COMMIT.
SQL>COMMIT;
=> insert command can be executed multiple times with different values by using variables
prefixed with "&".
SQL> /
SQL>COMMIT ;
NOTE :-
=> in normal exit operations are saved and in abnormal exit operations are cancelled
25-APR-24
INSERTING NULLS :-
----------------------------
method 1 :-
method 2 :-
Operators in oracle :-
------------------------------
SQL = ENGLISH
QUERIES = SENTENCES
CLAUSES = WORDS
Ex :-
WHERE clause :-
----------------------
=> WHERE clause is used to get specific row/rows from table based on a condition
SELECT columns / *
FROM tabname
WHERE condition ;
condiiton :-
---------------
COLNAME OP VALUE
ex :-
NOTE :-
=> relational operators can be used with numeric,char and date fields
26-APR-24
compound condition :-
-----------------------------
=> multiple conditions combined with AND / OR operators are called
compound condition.
Ex :-
SELECT *
FROM EMP
WHERE JOB='CLERK' OR JOB='MANAGER' ;
SELECT *
FROM EMP
WHERE EMPID = 100 OR EMPID = 103 OR EMPID = 105 ;
SELECT *
FROM EMP
WHERE JOB='CLERK' AND SAL > 4000 ;
=> employees earning more than 5000 and less than 10000 ?
SELECT *
FROM EMP
WHERE SAL > 5000 AND SAL < 10000 ;
=>
STUDENT
SNO SNAME S1 S2 S3
1 A 80 90 70
2 B 30 60 50
=> list of employees working as clerk,manager and earning more than 5000 ?
SELECT *
FROM EMP
WHERE JOB='CLERK'
OR
JOB='MANAGER'
AND
SAL > 5000 ;
above query returns clerk records earning less than 5000 because SAL > 5000 is applied
only to MANAGERS but not applied to CLERK because operator AND has got more
priority then operator OR , to overcome this problem use ( ) .
SELECT *
FROM EMP
WHERE (
JOB='CLERK'
OR
JOB='MANAGER'
)
AND
SAL > 5000 ;
IN operator :-
--------------------
Ex :-
BETWEEN operator :-
-------------------------------
WHERE COLNAME BETWEEN V1 AND V2 (COL >= V1 AND COL <= V2)
SELECT *
FROM EMP
WHERE HIREDATE NOT BETWEEN '01-JAN-20' AND '31-DEC-20' ;
=> employees working as clerk,manager and earning between 5000 and 10000
and not joined in 2024 and working for dept 10,20 ?
SELECT *
FROM EMP
WHERE JOB IN ('CLERK','MANAGER')
AND
SAL BETWEEN 5000 AND 10000
AND
HIREDATE NOT BETWEEN '01-JAN-24' AND '31-DEC-24'
AND
DNO IN (10,20);
=> list of samsung,redmi,realme mobile phones price between 10000 and 20000 ?
PRODUCTS
prodid pname price category brand
SELECT *
FROM PRODUCTS
WHERE BRAND IN ('SAMSUNG','REDMI','REALME')
AND
PRICE BETWEEN 10000 AND 20000
AND
CATEGORY='MOBILES' ;
LIKE operator :-
----------------------
WILDCARD chars :-
-----------------------------
27-APR-24
IS operator :-
-------------------
summary :-
ALIAS :-
------------
Ex :-
SELECT ENAME,
ROUND((SYSDATE-HIREDATE)/365) AS EXPERIENCE
FROM EMP ;
SELECT ENAME,SAL,
SAL*0.2 AS HRA,
SAL*0.3 AS DA,
SAL*0.1 AS TAX,
SAL + (SAL*0.2) + (SAL*0.3) - (SAL*0.1) AS TOTSAL
FROM EMP ;
STUDENT
SNO SNAME S1 S2 S3
1 A 80 90 70
2 B 30 60 50
1 240 80
2 140 46.
ORDER BY clause :-
----------------------------
=> order by clause is used to sort table data based on one or more columns either in
ascending or in descending order.
SELECT columns
FROM tabname
[WHERE cond]
ORDER BY colname ASC/DESC , ---------- ;
SELECT EMPNO,ENAME,SAL
FROM EMP
ORDER BY ENAME ASC ;
SELECT EMPNO,ENAME,SAL
FROM EMP
ORDER BY SAL DESC ;
=> arrange employee list dept wise asc and with in dept sal wise desc ?
SELECT EMPNO,ENAME,SAL,DEPTNO
FROM EMP
ORDER BY DEPTNO ASC , SAL DESC ;
1A 3000 20 5 E 6000 10
2 B 5000 10 2 B 5000 10
3C 4000 30 ===============> 4 D 5000 20
4D 5000 20 1 A 3000 20
5E 6000 10 3 C 4000 30
=> arrange employee list dept wise asc and with in dept hiredate wise asc ?
SELECT EMPNO,ENAME,HIREDATE,DEPTNO
FROM EMP
ORDER BY DEPTNO ASC , HIREDATE ASC ;
29-apr-24
3 C 90 80 70 80
4 D 90 70 80 80
1 A 80 90 70 80
2 B 60 70 50 60
=> display employee list working as clerk,manager and arrange output sal wise desc ?
SELECT EMPNO,ENAME,JOB,SAL
FROM EMP
WHERE JOB IN ('CLERK','MANAGER')
ORDER BY SAL DESC ;
Question :-
----------------
=> display employees joined in 1981 year and arrange output name wise asc ?
DISTINCT clause :-
---------------------------
syn :-
Ex :-
SQL>SELECT DISTINCT JOB FROM EMP ;
CLERK
SALESMAN
ANALYST
MANAGER
PRESIDENT
10
20
30
DEPTNO JOB
---------- ---------
20 MANAGER
20 ANALYST
10 PRESIDENT
10 CLERK
30 SALESMAN
10 MANAGER
20 CLERK
30 MANAGER
30 CLERK
FETCH clause :-
------------------------
syn :-
SELECT columns
FROM tabname
[WHERE cond]
[ORDER BY col ASC/DESC]
FETCH FIRST <N> ROWS ONLY ;
SELECT EMPNO,ENAME,SAL
FROM EMP
FETCH FIRST 50 PERCENT ROWS ONLY ;
SELECT EMPNO,ENAME,SAL
FROM EMP
OFFSET 4 ROWS FETCH NEXT 1 ROW ONLY ;
SELECT EMPNO,ENAME,SAL
FROM EMP
OFFSET 4 ROWS FETCH NEXT 6 ROWS ONLY ;
SELECT EMPNO,ENAME,SAL
FROM EMP
ORDER BY SAL DESC
FETCH FIRST 5 ROWS ONLY ;
summary :-
30-APR-24
INSERT
UPDATE
DELETE
MERGE
INSERT ALL
UPDATE command :-
------------------------------
syn :-
UPDATE <TABNAME>
SET COLNAME = VALUE , COLNAME = VALUE ,--------------
[WHERE COND] ;
Ex :-
=> update all employees comm with 500 ?
=> update employees comm with null whose comm <> null ?
NULL assignment =
NULL comparision IS
=> increment sal by 20% and comm by 10% those working as salesman and joined in 1981
year ?
UPDATE EMP
SET SAL = SAL + (SAL*0.2) , COMM = COMM + (COMM * 0.1)
WHERE JOB='SALESMAN'
AND
HIREDATE LIKE '%81' ;
Question :-
=> increase all the samsung,redmi,realme mobile phones and tvs price by 10% ?
products
prodid pname price category brand
DELETE command :-
-----------------------------
=> command used to delete row/rows from table
=> we can delete all rows or specific rows
ex :-
FLASHBACKING DATA :-
----------------------------------
=> using flashback we can see the data that exists some time back
=> a normal query returns current data but a query that returns past data is called flashback
query
=> useful to recover data after commit.
syn :-
SELECT columns
FROM tabname
AS OF TIMESTAMP ( SYSDATE - INTERVAL );
Ex :-
=> the following query returns 5 mins back data in emp table ?
SELECT EMPNO,ENAME,SAL,COMM
FROM EMP
AS OF TIMESTAMP (SYSDATE - INTERVAL '5' MINUTE) ;
NOTE :- we can flashback upto 900secs (15mins)
STEP 1 :-
STEP 2 :-
SQL> COMMIT ;
STEP 3 :-
=> to recover data after commit , get the data that exists 5 mins back and insert that data
into current emp table.
create
alter
drop
truncate
rename
flashback
purge
Example 1 :-
Example 2 :-
ALTER command :-
---------------------------
1 adding columns
2 droping columns
3 renaming a column
4 modifying a column
changing datatype
change size
syn :-
Ex :-
after adding by default the new column is filled with NULLs , to insert data into the new
column
use update command.
UPDATE EMP SET GENDER = 'F' , DOB = '10-FEB-1960' WHERE EMPNO = 7499 ;
Droping columns :-
----------------------------
syn :-
ex :-
Renaming a column :-
---------------------------
syn :-
Ex :-
Question :-
ans :-
Modifying a column :-
------------------------------
Ex :-
NOTE :-
EMPNO EMPID
7369 TCS7369
02-may-24
DROP command :-
--------------------------
ex :-
=> before 10g ver when table is dropped then it is permanently removed and cannot be
restored but from 10g onwards when table is dropped then it is moved to recyclebin
SQL>SHOW RECYCLEBIN
FLASHBACK command :-
------------------------------------
Ex :-
=> table is restored with columns and rows that exists before drop
PURGE command :-
----------------------------
ex :-
=> after deleting table from recyclebin we cannot flashback the table.
TRUNCATE command :-
---------------------------------
=> deletes all the data from table but keeps structure
=> will empty the table
=> releases memory allocated for table
ex :-
DROP DELETE/TRUNCATE
drops structure with data deletes only data but not structure
DELETE TRUNCATE
1 DML DDL
7 slower faster
RENAME :-
------------------
ex :-
=> a function accepts some input performs some calculation and returns one value
Types of functions :-
---------------------------
=> these functions process one row at a time and returns one value per row
character functions :-
----------------------------
UPPER() :-
---------------
UPPER(arg)
ex :-
LOWER() :-
----------------
03-may-24
LENGTH() :-
-------------------
SELECT *
FROM EMP
WHERE LENGTH(ENAME) = 4 ;
SUBSTR() :-
-----------------
SUBSTR(string,start,[no of chars])
ex :-
SELECT EMPNO,ENAME,
SUBSTR(ENAME,1,3)||SUBSTR(EMPNO,1,3)||'@tcs.com' AS EMAILID
FROM EMP ;
=> store emailids in db ?
UPDATE EMP
SET EMAILID = SUBSTR(ENAME,1,3)||SUBSTR(EMPNO,1,3)||'@tcs.com' ;
INSTR() :-
-------------
INSTR(string,char,[start,occurance])
ex :- H E L LO W E L C O M E
1 2 3 4 5 6 7 8 9 10 11 12 13
CUST
CID CNAME
10 sachin tendulkar
11 virat kohli
SELECT CID,
SUBSTR(CNAME,1,INSTR(CNAME,' ')-1) AS FNAME,
SUBSTR(CNAME,INSTR(CNAME,' ')+1) AS LNAME
FROM CUST ;
CUST
CID CNAME
10 sachin ramesh tendulkar
11 mahendra singh dhoni
04-MAY-24
REPLACE() :-
---------------------
REPLACE(str1,str2,str3)
ex :-
TRANSLATE() :-
-------------------------
TRANSLATE(str1,str2,str3)
ex :-
NOTE :-
=> translate function can be used to encrypt data i.e. converting plain text to cipher text
ex :-
SELECT
REPLACE (TRANSLATE( '@*HE#$LL%^O!' ,'@*#$%^!','*******') ,'*','')
FROM DUAL ;
NUMERIC FUNCTIONS :-
-----------------------------------
ROUND
TRUNC
CEIL
FLOOR
38.456789 => 38
38.45
38.4567
ROUND() :-
---------------
ROUND(number,[decimal places])
ex :-
ROUND(38.5768) => 39
38----------------------------------38.5-----------------------------------39
ROUND(38.4768) => 38
300---------------------------------350------------------------------------400
380----------------------------------385-------------------------------------390
ROUND(386,-3) => 0
0---------------------------------------500---------------------------------------1000
SELECT ENAME ,
ROUND((SYSDATE-HIREDATE)/365) AS EXPR
FROM EMP ;
TRUNC() :-
----------------
=> rounds number always to lowest
TRUNC(number,[decimal places])
ex :-
TRUNC(38.8765) => 38
TRUNC(38.8765,2) => 38.87
TRUNC(386,-2) => 300
TRUNC(999,-3) => 0
CEIL() :-
-----------
CEIL(number)
EX :-
CEIL(3.1) => 4
FLOOR() :-
----------------
FLOOR(number)
ex :-
FLOOR(3.9) => 3
Question :-
Question :-
SELECT ROUND(TRUNC(4567,-1),-3) FROM DUAL ;
-----------------------
4560
O/ P:- 5000
DATE functions :-
-----------------------
ADD_MONTHS() :-
---------------------------
ADD_MONTHS(DATE,MONTHS)
Ex :-
Ex :-
GOLD_RATES
DATEID RATE
01-JAN-20 ?
02-JAN-20 ?
04-MAY-24 ?
06-MAY-24
MONTHS_BETWEEN() :-
----------------------------------
MONTHS_BETWEEN(date1,date2)
ex :-
MONTHS_BETWEEN(SYSDATE,'06-MAY-23') =>
SELECT ENAME,
FLOOR(MONTHS_BETWEEN(SYSDATE,HIREDATE)) AS EXPR
FROM EMP ;
SELECT ENAME,
FLOOR(MONTHS_BETWEEN(SYSDATE,HIREDATE)/12) AS YEARS,
MOD(FLOOR(MONTHS_BETWEEN(SYSDATE,HIREDATE)),12) AS MONTHS
FROM EMP ;
CONVERSION FUNCTIONS :-
------------------------------------------
1 TO_CHAR
2 TO_DATE
3 TO_NUMBER
TO_CHAR(DATE,'format')
yyyy 2024
yy 24
mm 05
mon may
month may
hh 11 (1-12)
hh24 11 (1-24)
mi 56
ss 20
AM/PM AM time OR PM time
Q 2 (1-4)
jan-mar 1
apr-jun 2
jul-sep 3
oct-dec 4
SELECT TO_CHAR(SYSDATE,'yyyy yy') FROM DUAL ;
SELECT *
FROM EMP
WHERE TO_CHAR(HIREDATE,'YYYY') IN (1980,1983,1985) ;
SELECT *
FROM EMP
WHERE MOD(TO_CHAR(HIREDATE,'YYYY'),4) = 0 ;
SELECT *
FROM EMP
WHERE TO_CHAR(HIREDATE,'MM') IN (1,4,12) ;
SELECT *
FROM EMP
WHERE TO_CHAR(HIREDATE,'d') = 1 ;
TO_CHAR(HIREDATE,'dy') = 'sun' ;
TO_CHAR(HIREDATE,'fmday') = 'sunday' ;
SELECT *
FROM EMP
WHERE TO_CHAR(HIREDATE,'YYYY-Q') = '1981-2' ;
Ex :-
SELECT *
FROM EMP
WHERE HIREDATE = SYSDATE ; => NO ROWS
SELECT *
FROM EMP
WHERE TO_CHAR(HIREDATE,'DD-MM-YYYY') = TO_CHAR(SYSDATE,'DD-MM-YYYY') ;
07-may-24
TO_CHAR(number,'format')
formats :-
-------------
9 represents a digit
0 represents a digit
G thousand seperator
D decimal seperator
L currency symbol
C currency
ex :-
=> display ENAME SAL ? display salaries with thousand seperator and currency symbol ?
SELECT ENAME,
TO_CHAR(SAL,'C99G999') AS SAL
FROM EMP ;
TO_DATE(DATE STRING,'FORMAT')
Ex :-
calculate '05/07/24' + 30 ?
SELECT TO_CHAR(TO_DATE('&DATE','DD-MON-YYYY'),'DAY')
FROM DUAL ;
SELECT LEVEL
FROM DUAL
WHERE MOD(LEVEL,2) = 0
CONNECT BY LEVEL <= 20;
01-JAN-24 ?
02-JAN-24 ?
31-DEC-24 ?
special functions :-
--------------------------
NVL() :-
---------
NVL(arg1,arg2)
ex :-
ex :-
08-MAY-24
Ananlytical functions :-
-------------------------------
Ex :-
=> find ranks of the employees based on sal and highest paid should get 1st rank ?
SELECT ENAME,SAL,
RANK() OVER (ORDER BY SAL DESC) AS RNK
FROM EMP ;
SELECT ENAME,SAL,
DENSE_RANK() OVER (ORDER BY SAL DESC) AS RNK
FROM EMP ;
1 rank function generates gaps but dense_rank will not generate gaps
2 in rank function ranks may not be in sequence but in dense_rank ranks are always in
sequence
=> find the ranks based on sal desc , if salaries are same then ranking should be based on
hiredate ?
SELECT ENAME,HIREDATE,SAL,
DENSE_RANK() OVER (ORDER BY SAL DESC,HIREDATE ASC) AS RNK
FROM EMP ;
GROUP functions :-
--------------------------
=> these functions process group of rows and returns one value
=> these functions are also called multi row functions or aggregate functions
MAX
MIN
SUM
AVG
COUNT
COUNT(*)
MAX() :-
-------------
MAX(arg)
Ex :-
MIN() :-
------------
MIN(arg)
SUM() :-
------------
SUM(arg)
SELECT SUM(SAL) FROM EMP ; => 33025
33000--------------------33050-----------------------------33100
=> after rounding display total sal with thousand seperator and currency ?
SELECT
TO_CHAR( ROUND(SUM(SAL),-2) , 'C99G999')
FROM EMP ;
o/p :- USD33,000
AVG() :-
-----------
AVG(arg)
ex :-
2201---------------------------------------2202
COUNT() :-
-----------------
COUNT(arg)
COUNT(*) :-
------------------
T1
F1
10
NULL
20
NULL
30
SELECT COUNT(*)
FROM EMP
WHERE TO_CHAR(HIREDATE,'YYYY-Q') = '1981-2' ;
NOTE :-
=> group functions are not allowed in where clause and they are allowed only in select ,
having clauses.
SELECT ENAME
FROM EMP
WHERE SAL = MAX(SAL) ; => ERROR
SELECT DEPTNO
FROM EMP
WHERE COUNT(*) = 3 ; => ERROR
STRING :- upper,lower,length,substr,instr,replace,translate
NUMERIC :- round,trunc,ceil,floor,mod
DATE :- add_months,months_between
CONVERSION :- to_char,to_date,to_number
SPECIAL :- nvl
ANALYTICAL :- rank,dense_rank
GROUP :- max,min,sum,avg,count,count(*)
1 simple case
2 searched case
simple case :-
------------------
CASE COLNAME
WHEN VALUE1 THEN RETURN EXPR1
WHEN VALUE2 THEN RETURN EXPR2
WHEN VALUE3 THEN RETURN EXPR3
---------------
ELSE RETURN EXPR
END
SELECT ENAME,
CASE DEPTNO
WHEN 10 THEN 'ACCOUNTS'
WHEN 20 THEN 'RESEARCH'
WHEN 30 THEN 'SALES'
ELSE ' UNKNOWN'
END AS DNAME
FROM EMP ;
09-may-24
UPDATE EMP
SET SAL = CASE JOB
WHEN 'CLERK' THEN SAL + (SAL*0.1)
WHEN 'SALESMAN' THEN SAL + (SAL*0.15)
WHEN 'MANAGER' THEN SAL + (SAL*0.2)
ELSE SAL+(SAL*0.05)
END ;
searched case :-
------------------------
=> use searched case when conditions not based on "=" operator.
CASE
WHEN COND1 THEN RETURN EXPR1
WHEN COND2 THEN RETURN EXPR2
WHEN COND3 THEN RETURN EXPR3
----------------------------
ELSE RETURN EXPR
END
0-2000
2001-4000
ABOVE 4000
SELECT ENAME,SAL,
CASE
WHEN SAL BETWEEN 0 AND 2000 THEN '0-2000'
WHEN SAL BETWEEN 2001 AND 4000 THEN '2001-4000'
WHEN SAL>4000 THEN 'ABOVE 4000'
END AS SALRANGE
FROM EMP ;
STUDENT
SNO SNAME S1 S2 S3
1 A 80 90 70
2 B 30 60 50
SELECT SNO,
S1+S2+S3 AS TOTAL,
ROUND((S1+S2+S3)/3 ,2) AS AVG,
CASE
WHEN S1>=35 AND S2>=35 AND S3>=35 THEN 'PASS'
ELSE 'FAIL'
END AS RESULT
FROM STUDENT ;
========================================================================
=
INTEGRITY CONSTRAINTS
======================
=> Integrity constraints are rules to maintain data integrity i.e. data quality or
data consistency.
Types of constraints :-
-----------------------------
NOT NULL
UNIQUE
PRIMARY KEY
CHECK
FOREIGN KEY
DEFAULT
1 column level
2 table level
column level :-
---------------------
=> if constraints are declared immediately after declaring column then it is called
column level
NOT NULL :-
------------------
UNIQUE :-
---------------
ex :-
PRIMARY KEY :-
-----------------------
ex :-
CREATE TABLE EMP12
(
EMPNO NUMBER(4) PRIMARY KEY,
ENAME VARCHAR(10) NOT NULL
);
NOTE :- only one primary key is allowed per table. if we want multiple primary keys then
declare one column with primary key and other columns with unique not null.
ex :-
=> columns declared with UNIQUE NOT NULL are called secondary keys or alternate keys
CHECK constraint :-
--------------------------
CHECK(condition)
M
F
D => NOT ALLOWED
5000
2555 => NOT ALLOWED
FOREIGN KEY :-
-------------------------
EMP
EMPNO ENAME SAL DNO DNAME LOC
1 A 5000 10 HR HYD
2 B 4000 10 HR HYD
3 C 3000 10 HR HYD
20 10 HR HYD
=> above table contains redundency i.e. repeation of data and it leads to
memory wastage and insert,update,delete anamolies , to to reduce
redundency divide the table into two tables and establish relationship
by using foreign key
=> to establish relationship take primary key of one table and add it to
another table as foreign key and declare with references constraint.
ex :-
DEPT
DNO DNAME LOC
10 HR HYD
20 IT BLR
EMP
EMPNO ENAME SAL DNO REFERENCES DEPT(DNO)
1 A 5000 10
2 B 6000 20
3 C 7000 90 => INVALID
4 D 3000 10
5 E 2000 NULL
=> values entered in foreign key column should match with values entered in primary key
column
=> after declaring foreign key a relationship is created between two tables called
parent / child relationship.
=> primary key table is parent and foreign key table is child.
QUESTION :-
------------------
ACCOUNTS
ACCNO ACTYPE BAL
Rules :-
TRANSACTIONS
TRID TTYPETDATETAMT ACCNO
Rules :-
Relationship Types :-
----------------------------
=> by default oracle creates one to many relationship between two tables
=> to establish one to one relationship declare foreign key with unique constraint.
DEPT
DNO DNAME
10 HR
20 IT
MGR
MGRNO MNAME START_DT END_DT DNO REFERENCES
DEPT(DNO) UNQUE
1 A 1/ 20/ 10
2 B 21/ 30 20
11-MAY-24
=> if relationship is many to many then create 3rd table and add primary keys of both tables
as foreign keys
ex :-
STUDENT COURSE
SID SNAME CID CNAME
1 A 10 JAVA
2 B 11 ORACLE
REGISTRATIONS
SID CID DOR FEE
1 10 ? 5000
1 11 ? 5000
2 10 ? 5000
=> if relationship is one to one then we can add foreign key to any table
=> if relationship is one to many then we must add foreign key to many side table
=> if relationship is many to many then create 3rd and add primary keys of both tables as
foreign keys
DEFAULT :-
----------------
=> while inserting if we skip hiredate then oracle inserts default value
Ex :-
TABLE LEVEL :-
----------------------
=> if constraints are declared after declaring all columns then it is called table level
=> use table level to declare constraint for multiple or combination of columns
Declaring check constraint at table level :-
-------------------------------------------------------
PRODUCTS
prodid pname price mfd_dt exp_dt
100 AAAA 50 01-MAY-24 01-JAN-24 INVALID
=> In some tables we may not be abled to uniquely identity by using single
column and we need combination to uniquely identify and that
combination should be declared primary key at table level.
ex :-
STUDENT COURSE
SID SNAME CID CNAME
------- ----
1 A 10 JAVA
2 B 11 ORACLE
REGISTRATIONS
SID CID DOR FEE
-----------------------
1 10 ? 5000
1 11 ? 5000
2 10 ? 5000
Question :-
SALES
DATEID PRODID CUSTID QTY AMT
10-MAY-24 100 10 1 2000
10-MAY-24 100 11 1 2000
10-MAY-24 101 10 1 1000
11-MAY-24 100 10 1 2000
14-may-24
ex :-
REGISTRATIONS
SID CID DOR FEE
-----------------------
1 10 ? 5000
1 11 ? 5000
2 10 ? 5000
CERTIFICATES
CERTNO DOI SID CID
1000 14- 1 10
1001 14- 1 11
1002 14- 2 11 => INVALID
=> in the above example SID,CID combination should match with registrations
table sid,cid combination , so declare this combination as foreign key
A CHECK
B UNIQUE
C NOT NULL
D PRIMARY KEY
E FOREIGN KEY
ANS :- C
=> oracle not only stores data and it also stores metadata and this metadata organized in
tables called system tables or data dictionary tables
ALL_USERS :-
-------------------
USER_TABLES :-
------------------------
USER_CONSTRAINTS :-
----------------------------------
SELECT CONSTRAINT_NAME,CONSTRAINT_TYPE,
SEARCH_CONDITION
FROM USER_CONSTRAINTS
WHERE TABLE_NAME='EMP55' ;
CONSTRAINT_NAME C SEARCH_CONDITION
-------------------------- - ------------------------------
SYS_C009254 C "ENAME" IS NOT NULL
SYS_C009255 C SAL BETWEEN 5000 AND 10000
SYS_C009257 R
SYS_C009256 P
Droping constraints :-
------------------------------
Ex :-
DROP TABLE DEPT55 ; => ERROR => can't drop table because referenced by fk
CASCADE :-
-------------------
DROP TABLE DEPT55 CASCADE CONSTRAINTS ; => drops table with dependent fk
summary :-
importance of constraints
types of constraints
declaring constraints
column level
table level
droping constraints
getting constraints information
========================================================================
==
15-may-24 JOINS
---------
=> join is an operation performed to display data from two or more tables
=> In db related data stored in multiple tables , to gather or to combine data stored in
multiple tables we need to join those tables.
ex :-
ORDERS CUST
ordid orddt deldt cid cid cname caddr
1000 10 15 10 10 A HYD
1001 12 17 11 11 B HYD
1002 13 20 12 12 C HYD
output :-
------------
Types of joins :-
---------------------
1 INNER JOIN
2 OUTER JOIN
LEFT OUTER
RIGHT OUTER
FULL OUTER
3 SELF JOIN
4 NON EQUI
5 CROSS JOIN
INNER JOIN :-
---------------------
=> to perform inner join between the tables there must be a common field and name of the
common field need not to be same and pk-fk relationship is not compulsory.
=> inner join is perfomed on the common column with same datatype.
syntax :-
SELECT columns
FROM tab1 INNER JOIN tab2
ON join condition ;
join condition :-
---------------------
=> based on the join condition oracle joins the records of two tables.
=> join conditions specifies which record of 1st table joined with which record of 2nd table.
Ex :-
EMP DEPT
EMPNO ENAME SAL DEPTNO DEPTNO DNAME
LOC
1 A 3000 10 10 ACCOUNTS NEW YORK
2 B 4000 20 20 RESEARCH
3 C 6000 30 30 SALES
4 D 4000 20 40 OPERATIONS
5 E 2000 NULL
SELECT ENAME,SAL,DNAME,LOC
FROM EMP INNER JOIN DEPT
ON EMP.DEPTNO = DEPT.DEPTNO ;
A ACCOUNTS
B RESEARCH
C SALES
D RESEARCH
note :-
-----------
=> In join queries declare table alias and prefix column names with table alias for two reasons
1 to avoid ambiguity
2 for faster execution
=> display employee details with dept details working at NEW YORK loc ?
SELECT E.ENAME,D.DNAME,D.LOC
FROM EMP E INNER JOIN DEPT D
ON E.DEPTNO = D.DEPTNO /* join cond */
WHERE D.LOC = 'NEW YORK' /* filter cond */ ;
SELECT columns
FROM t1 INNER JOIN t2
ON join cond 1
INNER JOIN t3
ON join cond 2
INNER JOIN t4
ON join cond 3
example :-
-----------------
SELECT E.ENAME,
D.DNAME,
L.CITY,L.STATE,
C.COUNTRY_NAME
FROM EMP E INNER JOIN DEPT D
ON E.DEPTNO = D.DEPTNO
INNER JOIN LOCATIONS L
ON D.LOCID = L.LOCID
INNER JOIN COUNTRIES C
ON L.COUNTRY_ID = C.COUNTRY_ID ;
Question :-
16-MAY-24
OUTER JOIN :-
----------------------
=> inner join returns only matching records but it will not return unmatched records ,
to display unmatched records perform outer join
ex :-
EMP DEPT
EMPNO ENAME SAL DEPTNO DEPTNO DNAME
LOC
1 A 3000 10 10 ACCOUNTS NEW YORK
2 B 4000 20 20 RESEARCH
3 C 6000 30 30 SALES
4 D 4000 20 40 OPERATIONS => unmatched record
5 E 2000 NULL => unmatched record
=> outer join is 3 types
=> returns all rows (matched + unmatched) from left side table and matching rows
from right side table.
SELECT E.ENAME,D.DNAME
FROM EMP E LEFT OUTER JOIN DEPT D
ON E.DEPTNO = D.DEPTNO ;
=> returns all rows from emp table and matching rows from dept table
A ACCOUNTS
B RESEARCH
C SALES
D RESEARCH
E NULL => unmatched from emp
=> returns all rows from right side table and matching rows from left side table
SELECT E.ENAME,D.DNAME
FROM EMP E RIGHT OUTER JOIN DEPT D
ON E.DEPTNO = D.DEPTNO ;
=> returns all rows from dept table and matching rows from emp table
A ACCOUNTS
B RESEARCH
C SALES
D RESEARCH
NULL OPERATIONS => unmatched from dept
SELECT E.ENAME,D.DNAME
FROM EMP E FULL OUTER JOIN DEPT D
ON E.DEPTNO = D.DEPTNO ;
A ACCOUNTS
B RESEARCH
C SALES
D RESEARCH
E NULL => unmatched from emp
NULL OPERATIONS=> unmatched from dept
SELECT E.ENAME,D.DNAME
FROM EMP E LEFT OUTER JOIN DEPT D
ON E.DEPTNO = D.DEPTNO
WHERE D.DNAME IS NULL ;
E NULL
SELECT E.ENAME,D.DNAME
FROM EMP E RIGHT OUTER JOIN DEPT D
ON E.DEPTNO = D.DEPTNO
WHERE E.ENAME IS NULL ;
NULL OPERATIONS
both tables :-
-----------------
SELECT E.ENAME,D.DNAME
FROM EMP E FULL OUTER JOIN DEPT D
ON E.DEPTNO = D.DEPTNO
WHERE E.ENAME IS NULL
OR
D.DNAME IS NULL ;
E NULL
NULL OPERATIONS
Question :-
EMP PROJECTS
EMPNO ENAME SAL PROJID PROJID NAME DURATION CLIENT
1 100 100
2 101 101
3 NULL 102
=> display employee details with project details and also display employees not assigned to
any project ?
SELF JOIN :-
-----------------
EMP X EMP Y
EMPNO ENAME MGR EMPNO ENAME MGR
7369 smith 7902 7369 smith 7902
7499 allen 7698 7499 allen 7698
7566 jones 7839 7566 jones 7839
7698 blake 7839 7698 blake 7839
7839 king ------- 7839 king -------
7902 ford 7566 7902 ford 7566
=> display ENAME MGRNAME ?
smith ford
allen blake
jones king
blake king
ford jones
SELECT X.ENAME,X.SAL,
Y.ENAME AS MANAGER,Y.SAL AS MGRSAL
FROM EMP X INNER JOIN EMP Y
ON X.MGR = Y.EMPNO
WHERE X.SAL > Y.SAL ;
SELECT X.ENAME,X.HIREDATE,
Y.ENAME AS MANAGER , Y.HIREDATE AS MGRHIRE
FROM EMP X INNER JOIN EMP Y
ON X.MGR = Y.EMPNO
WHERE X.HIREDATE < Y.HIREDATE ;
Question :-
TEAMS
ID COUNTRY
1 IND
2 AUS
3 ENG
output :-
IND VS AUS
IND VS ENG
AUS VS ENG
17-MAY-24
GROUP BY clause :-
-----------------------------
=> GROUP BY clause is used for grouping rows based on one or more columns
to calculate min,max,sum,avg,count for each group. For example
to count no of employees for each dept first we need to group rows based
on dept
EMP
EMPNO ENAME SAL DEPTNO
1 A 4000 10 GROUP BY 10 7000
2 B 3000 20 ======> 20 9000
3 C 5000 30 30 5000
4 D 6000 20
5 E 3000 10
=> GROUP BY clause converts detailed data into summarized data which is
useful for analysis.
syntax :-
SELECT columns
FROM tabname
[ WHERE cond]
GROUP BY <colname>
[HAVING cond]
[ORDER BY col ASC/DESC]
Execution :-
FROM
WHERE
GROUP BY
HAVING
SELECT
ORDER BY
SELECT DEPTNO,SUM(SAL)
FROM EMP
GROUP BY DEPTNO ;
10 8750
20 10875
30 9400
SELECT DEPTNO,COUNT(*)
FROM EMP
WHERE COUNT(*) > 3
GROUP BY DEPTNO ; => ERROR
note :-
=> oracle cannot calculate dept wise count before group by and it can
calculate only after group by , so apply the condition COUNT(*) > 3
after group by using HAVING clause.
SELECT DEPTNO,COUNT(*)
FROM EMP
GROUP BY DEPTNO
HAVING COUNT(*) > 3 ;
WHERE VS HAVING :-
--------------------------------
WHERE HAVING
PERSONS
AADHARNO NAME AGE GENDER ADDR CITY STATE
SELECT STATE,COUNT(*)
FROM PERSONS
WHERE STATE IN ('AP','TS','KA','KL','TN')
GROUP BY STATE
HAVING COUNT(*) > 50000000
=> find the total sal paid to departments where deptno = 10,20 and total sal > 10000 ?
SELECT DEPTNO,SUM(SAL)
FROM EMP
WHERE DEPTNO IN (10,20)
GROUP BY DEPTNO
HAVING SUM(SAL) > 10000;
18-may-24
=> display dept wise and with in dept job wise total sal ?
10 CLERK 1300
MANAGER 2450
PRESIDENT 5000
20 ANALYST 6000
CLERK 1900
MANAGER 2975
30 CLERK 950
MANAGER 2850
SALESMAN 5600
=> display year wise and with in year quarter wise no of employees joined ?
1981 1 ?
2 ?
3 ?
4 ?
NOTE :-
=> alias can be used in ORDER BY clause because order by clause is executed after select.
SELECT columns
FROM tab1 INNER JOIN tab2
ON join cond
GROUP BY colname
ORDER BY col ASC/DESC ;
Ex :-
SELECT D.DNAME,SUM(E.SAL)
FROM EMP E INNER JOIN DEPT D
ON E.DEPTNO = D.DEPTNO
GROUP BY D.DNAME ;
Question :-
--------------
2
SALES
DATEID PRODID CUSTID QTY AMT
17-MAY-24 100 10 1 2000
PRODUCTS
PRODID PNAME PRICE CATEGORY
100 A 2000 ELECTRONICS
CUST
CUSTID NAME ADDR COUNTRY
10 K HYD IND
Types of sub-queries :-
------------------------------
=> if inner query returns one value then it is called single row sub-query
SELECT columns
FROM tabname
WHERE colname OP (SELECT STATEMENT);
=> OP must be any relational operator like > >= < <= <>
Examples :-
SELECT *
FROM EMP
WHERE SAL > (SELECT SAL FROM EMP WHERE ENAME='BLAKE') ;
SELECT *
FROM EMP
WHERE HIREDATE < (SELECT HIREDATE FROM EMP WHERE ENAME='KING');
---------------------------------------------------------------------------------
17-NOV-81
SELECT ENAME
FROM EMP
WHERE SAL = (SELECT MAX(SAL) FROM EMP) ;
----------------------------------------------
5000
SELECT ENAME
FROM EMP
WHERE HIREDATE = (SELECT MIN(HIREDATE) FROM EMP);
SELECT MAX(SAL)
FROM EMP
WHERE SAL <> (SELECT MAX(SAL) FROM EMP) ;
o/p :- 3000
SELECT ENAME,SAL
FROM EMP
WHERE SAL = ( SELECT MAX(SAL)
FROM EMP
WHERE SAL <> (SELECT MAX(SAL) FROM EMP) );
UPDATE EMP
SET SAL = SAL + (SAL*0.1)
WHERE HIREDATE = (SELECT MIN(HIREDATE) FROM EMP) ;
20-MAY-24
=> if inner query returns more than one value then it is called multi row sub-query
SELECT columns
FROM tabname
WHERE colname OP (SELECT STATEMENT) ;
= IN
<> NOT IN
sub-query :-
----------------
SELECT ENAME
FROM EMP
WHERE DEPTNO IN (SELECT DEPTNO
FROM DEPT
WHERE LOC IN ('NEW YORK','CHICAGO')) ;
join :-
--------
SELECT E.ENAME
FROM EMP E INNER JOIN DEPT D
ON E.DEPTNO = D.DEPTNO
WHERE D.LOC IN ('NEW YORK','CHICAGO') ;
JOIN :-
----------
SELECT E.ENAME,D.DNAME
FROM EMP E INNER JOIN DEPT D
ON E.DEPTNO = D.DEPTNO
WHERE D.LOC IN ('NEW YORK','CHICAGO') ;
SUB-QUERY :-
--------------------
not possible
1 to display data from one table and condition based on another table
then we can use join or sub-query
=> use ANY,ALL operators for > < comparision with multiple values
SELECT *
FROM EMP
WHERE SAL > ALL (SELECT SAL FROM EMP WHERE JOB='MANAGER');
2975
2850
2450
SELECT *
FROM EMP
WHERE SAL > ANY (SELECT SAL FROM EMP WHERE JOB='MANAGER');
co-related sub-queries :-
---------------------------------
=> if sub-query references values of outer query then it is called co-related sub-query
=> execution starts from outer query and inner query is executed no of times
depends on no of rows return by outer query.
ex :-
EMP
EMPNO ENAME SAL DEPTNO
1 A 3000 10
2 B 4000 20
3 C 5000 30
4 D 6000 10
5 E 2000 20
SELECT *
FROM EMP
WHERE SAL > (SELECT AVG(SAL) FROM EMP);
-----------------------------------------------
4000
SELECT *
FROM EMP X
WHERE SAL > (SELECT AVG(SAL)
FROM EMP
WHERE DEPTNO = X.DEPTNO) ;
SELECT *
FROM EMP X
WHERE SAL = (SELECT MAX(SAL)
FROM EMP
WHERE DEPTNO = X.DEPTNO) ;
SELECT A.SAL
FROM EMP A
WHERE 3 > (SELECT COUNT(B.SAL)
FROM EMP B
WHERE A.SAL < B.SAL)
EMP A EMP B
SAL SAL
5000 5000 3 > (0) TRUE
1000 1000 3 > (4) FALSE
3000 3000 3 > (1) TRUE
3000 3000 3 > (1) TRUE
2975 2975 3 > (3) FALSE
EMP A EMP B
SAL SAL
5000 5000 3 > (0) TRUE
1000 1000 3 > (3) FALSE
3000 3000 3 > (1) TRUE
3000 3000 3 > (1) TRUE
2975 2975 3 > ( 2) TRUE
21-may-24
ROWID :-
-------------
=> returns physical address of a row i.e. where the record is stored in memory
=> ROWID is called psuedo column because it is not a column but acts like a column
ex :-
EMP44
EMPNO ENAME SAL ROWID
1 A 5000 AAA
2 B 6000 AAB
3 C 7000 AAC
1 A 5000 AAD
2 B 6000 AAE
DELETE FROM EMP44 WHERE ROWID LIKE '%AAD' ;
DELETE
FROM EMP44 X
WHERE ROWID <> (SELECT MIN(ROWID)
FROM EMP44
WHERE EMPNO = X.EMPNO
AND
ENAME = X.ENAME
AND
SAL = X.SAL);
EMP44
EMPNO ENAME SAL ROWID
1 A 5000 AAA <> (AAA) FALSE
2 B 6000 AAB <> (AAB) FALSE
3 C 7000 AAC <> (AAC) FALSE
1 A 5000 AAD <> (AAA) TRUE
2 B 6000 AAE <> (AAB) TRUE
INLINE views :-
----------------------
SELECT columns
FROM (select statement)
WHERE cond ;
default order :-
-------------------
FROM
WHERE
GROUP BY
HAVING
SELECT
ORDER BY
SELECT
FROM
WHERE
ORDER BY
SELECT
FROM (SELECT
FROM
ORDER BY )
WHERE
example 1 :-
=> display ranks of the employees based on sal and highest paid should get 1st rank ?
SELECT empno,ename,sal,
dense_rank() over (order by sal desc) as rnk
FROM emp ;
above query returns ranks of all the employees , but to display top 5 employees
SELECT empno,ename,sal,
dense_rank() over (order by sal desc) as rnk
FROM emp
WHERE rnk <= 5 ; => error
SELECT *
FROM E
WHERE rnk<=5 ;
ROWNUM :-
-------------------
=> rownum returns record number for the records return by select query
=> rownum is also a psuedo column
psuedo columns :-
-------------------------
1 rowid
2 rownum
3 sysdate
4 level
ex :-
=> rownum is useful when fetching records from table based on record number
ex :-
SELECT empno,ename,sal
FROM emp
WHERE rownum <= 5 ;
SELECT empno,ename,sal
FROM emp
WHERE rownum = 5 ; => no rows
NOTE :- in where condition with rownum = > >= operators will not work
only < <= operators will work, to overcome this problem use INLINE views
SELECT *
FROM (SELECT ROWNUM AS RNO,EMPNO,ENAME,SAL FROM EMP) E
WHERE RNO = 5 ;
WHERE MOD(RNO,2) = 0 ;
SELECT *
FROM (SELECT ROWNUM AS RNO,EMPNO,ENAME,SAL FROM EMP) E
WHERE RNO >= (SELECT COUNT(*)-2 FROM EMP) ;
=>
TRANSACTIONS
TRID TTYPETDATETAMT ACCNO
1 W ? 2000 100
SELECT *
FROM (SELECT *
FROM TRANSACTIONS
WHERE ACCNO = 100
ORDER BY TDATE DESC) E
WHERE ROWNUM<=5 ;
22-MAY
21-
20-
19-
18-
=============================================================
DATABASE TRANSACTIONS :-
-------------------------------------------
ex :- money transfer
acct1-----------------1000-------------------->acct2
update1 update2
(bal=bal-1000) (bal=bal+1000)
successful failed INVALID
=> every txn must gurantee a property called atomocity i.e. all or none
if txn contains multiple operations then if all are successful then
it must be saved , if one of the operation fails then entire txn must be
cancelled.
=>a txn begins automatically whenever user submits dml command to oracle
=> a txn ends with any of the following commands
1 commit / rollback
2 ddl command (txn ends with commit)
Example 1 :-
Example 2 :-
create table a(a number(2)); => commit
insert into a values(10); => txn starts t1
insert into a values(20);
create table b(b number(2)); => commit
insert into a values(30); => txn begins t2
insert into a values(40);
rollback ; => txn ends
SAVEPOINT :-
--------------------
=> we can declare savepoint and we can rollback upto the savepoint
=> using savepoint we can cancel part of the txn
SELECT * FROM A ;
10
20
23-MAY-24
LOCKING :-
-----------------
=> accessing same data by no of uses at the sametime is called concurrent acess
when data accessed concurrently users encounters following problems
1 dirty read
2 lost update
3 phantom read
4 non repeatable read
=> to overcome these problems every db system supports a mechanism called locking
mechansim
1 SHARED LOCK
2 EXCLUSIVE LOCK
=> oracle will apply shared lock whenever we try to read data i.e. whenever user submits
select stmt
=> oracle will apply exclusive lock whenever we try to modify the data. whenever user submits
DML commands.
S X
S YES YES
X YES NO
Example :-
SYSTEM BATCH32
DEADLOCK :-
-------------------
=> deadlock is the situation where two users mutually waits for one another
if deadlock occurs then oracle returns error so that one transaction
can be cancelled and another can be continued.
ex :-
SYSTEM BATCH32
---------WAIT--------------- -----------WAIT-----------------------
--------------------------------------------DEADLOCK-------------------------------------------------------------
6 ROLLBACK;
=> complete table is locked i.e. all the records of the table are locked
EX :-
========================================================================
DB OBJECTS :-
---------------------
1 TABLES
2 SEQUENCES
3 SYNONYMS
4 VIEWS
5 INDEXES
SEQUENCES :-
-----------------------
=> sequence is a db object created to generate sequence numbers for primary key columns
syn :-
Ex :-
CREATE SEQUENCE S1
START WITH 1
INCREMENT BY 1
MAXVALUE 5 ;
using sequence :-
------------------------
Example 2 :-
CREATE SEQUENCE S2
START WITH 100
INCREMENT BY 1
MAXVALUE 999;
Example 3 :-
CREATE SEQUENCE S3
START WITH 1
INCREMENT BY 1
MAXVALUE 9999;
INVOICE
INVNO INVDT INVAMT
NIT/0524/1 ? ?
NIT/0524/2 ? ?
Droping :-
---------------
SQL>DROP SEQUENCE S1 ;
SYNONYMS :-
--------------------
=> if tablename is lengthy then we can give a simple and short name
to the table called synonym and instead of using tablename
we can use synonym name in SELECT / INSERT / UPDATE / DELETE
queries.
=> after creating synonym instead of using tablename use synonym name
1 SELECT * FROM E ;
Question :-
SYNONYM ALIAS
1 stored in db not stored in db
Droping synonym :-
------------------------
SQL>DROP SYNONYM E ;
========================================================================
==
24-may-24
PL/SQL
=======
ORACLE
NON-PROC PROC
SQL PL/SQL
(commands) (blocks)
Features :-
--------------
improves performance :-
---------------------------------
=> In pl/sql , sql commands can be grouped into one block and we submit that block to oracle,
so in pl/sql no of requests and response between user and oracle are reduced and
performance is improved.
supports conditional statements :-
------------------------------------------
=> pl/sql supports conditional statements like IF-ELSE , so in pl/sql we can execute
sql commands based on conditions.
supports loops :-
----------------------
=> pl/sql supports looping statements like while,for , so with the help of loops we can execute
commands repeatedly multiple times.
=> pl/sql supports error handling , In pl/sql if any statement causes error then we can
handle that error and we can display our own simple and user friendly message.
supports reusability :-
----------------------------
=> pl/sql programs can be stored in db , so applications which are connected to db can
reuse pl/sql programs.
supports security :-
--------------------------
=> because these programs are stored in db , so only authorized uses can execute these
programs
1 Anonymous Blocks
2 Named Blocks
procedures
functions
packages
triggers
Anonymous Blocks :-
-----------------------------
=> a program without name is called anonymous block
DECLARE
declaration-part; optional
BEGIN
execution-part;
END;
/ => compilation & execution starts
DBMS_OUTPUT.PUT_LINE(message);
---------------------- --------------
PACKAGE PROCEDURE
=> by default messages are not send to output , to send messages to output execute the
following command.
SQL>SET SERVEROUTPUT ON
1 EDITORs
2 IDEs
EDITOR IDE
compilation NO YES
execution NO YES
debugging NO YES
using NOTEPAD :-
--------------------------
=> open notepad and enter following code
BEGIN
DBMS_OUTPUT.PUT_LINE('HELLO');
END;
/
SQL>@D:\PLSQL\PROG1.SQL
Datatypes in PL/SQL :-
------------------------------
1 NUMBER(P) / NUMBER(P,S)
2 CHAR/VARCHAR2/LONG/CLOB
3 NCHAR/NVARCHAR2/NCLOB
4 DATE / TIMESTAMP
5 BFILE / BLOB
6 BOOLEAN
Declaring variable :-
----------------------------
variablename datatype(size) ;
ex :-
x number(4);
s varchar2(20);
d date;
b boolean;
variablename := value ;
:= assignment
= comparision
ex :- x := 100;
s := 'abc';
d := sysdate;
b := TRUE ;
DECLARE
a NUMBER(3);
b NUMBER(3);
c NUMBER(3);
BEGIN
a := &a;
b := &b;
c := a+b;
DBMS_OUTPUT.PUT_LINE(c);
END;
/
=> write a prog to input date and print day of the week ?
DECLARE
d DATE ;
BEGIN
d := '&date' ;
DBMS_OUTPUT.PUT_LINE(TO_CHAR(d,'day'));
END;
/
=> From pl/sql to work with db execute sql commands from pl/sql program
=> the following commands can be executed from pl/sql program.
1 DML (insert,update,delete,merge)
2 DQL (select)
3 TCL (commit,rollback,savepoint)
SELECT stmt syntax :-
----------------------------------
ex :-
=> write a prog to input empno and print name & salary ?
DECLARE
vempno NUMBER(4);
vename VARCHAR2(10);
vsal NUMBER(7,2);
BEGIN
vempno := &empno;
SELECT ename,sal INTO vename,vsal
FROM emp
WHERE empno = vempno;
DBMS_OUTPUT.PUT_LINE(vename||' '||vsal);
END;
/
=> write a prog to input empno and calculate and print experience ?
DECLARE
vempno NUMBER(4);
vhire DATE;
vexpr NUMBER(2);
BEGIN
vempno := &empno;
SELECT hiredate INTO vhire
FROM emp
WHERE empno = vempno;
vexpr := (SYSDATE-vhire)/365 ;
DBMS_OUTPUT.PUT_LINE(' experience = '||vexpr||' '||'years');
END;
/
experience = ?? years
27-MAY-24
DECLARE
veno NUMBER(4);
vsal NUMBER(7,2);
vcomm NUMBER(7,2);
vtotsal NUMBER(8,2);
BEGIN
veno := &empno;
SELECT sal,comm INTO vsal,vcomm
FROM emp
WHERE empno = veno;
vtotsal := vsal + NVL(vcomm,0);
DBMS_OUTPUT.PUT_LINE('Total Sal = '||vtotsal);
END;
/
Conditional statements :-
---------------------------------
1 IF-ELSE
2 MULTI IF
3 NESTED IF
IF-ELSE :-
--------------
IF COND THEN
statements;
ELSE
statements;
END IF;
MULTI IF :-
---------------
IF COND1 THEN
statements;
ELSIF COND2 THEN
statements;
ELSIF COND3 THEN
statements;
ELSE
statements;
END IF;
NESTED IF :-
------------------
IF COND THEN
IF COND THEN
statements;
ELSE
statements;
END IF;
ELSE
statements;
END IF;
=> write a prog to input empno and increment sal by specific amount
after increment if sal execeeds 5000 then cancel that increment ?
DECLARE
veno NUMBER(4);
vamt NUMBER(5);
vsal NUMBER(7,2);
BEGIN
veno := &empno;
vamt := &amount;
UPDATE emp SET sal = sal + vamt WHERE empno = veno ;
SELECT sal INTO vsal FROM emp WHERE empno = veno;
IF vsal > 5000 THEN
ROLLBACK;
ELSE
COMMIT;
END IF;
END;
/
=> write a prog to input empno and increment sal as follows ?
DECLARE
veno NUMBER(4);
vjob VARCHAR2(10);
vpct NUMBER(2);
BEGIN
veno := &empno;
SELECT job INTO vjob FROM emp WHERE empno = veno;
IF vjob='CLERK' THEN
vpct := 10;
ELSIF vjob='MANAGER' THEN
vpct := 15;
ELSIF vjob='SALESMAN' THEN
vpct := 20;
ELSE
vpct := 5;
END IF;
UPDATE emp SET sal = sal + (sal*vpct/100) WHERE empno = veno;
COMMIT;
END;
/
ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
101 S 20000
DECLARE
vacno NUMBER(4);
vtype CHAR(1);
vamt NUMBER(5);
vbal NUMBER(8);
BEGIN
vacno := &acno;
vtype := '&type';
vamt := &amount;
IF vtype='W' THEN
SELECT bal INTO vbal FROM accounts WHERE accno = vacno;
IF vamt > vbal THEN
DBMS_OUTPUT.PUT_LINE('insufficient balance');
ELSE
UPDATE accounts SET bal = bal - vamt WHERE accno = vacno;
END IF;
ELSIF vtype='D' THEN
UPDATE accounts SET bal = bal + vamt WHERE accno = vacno;
ELSE
DBMS_OUTPUT.PUT_LINE('invalid transaction type');
END IF;
COMMIT;
END;
/
LOOPS :-
--------------
1 simple loop
2 while loop
3 for loop
simple loop :-
-------------------
LOOP
statements;
EXIT WHEN COND;
END LOOP;
WHILE loop :-
--------------------
WHILE(cond)
LOOP
statements;
END LOOP;
FOR loop :-
----------------
Ex :-
FOR x IN 1..10
LOOP
statements;
END LOOP;
DECLARE
x NUMBER(2) := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE(x);
x := x+1;
EXIT WHEN x > 20;
END LOOP;
END;
/
DECLARE
x NUMBER(2) := 1;
BEGIN
WHILE(x<=20)
LOOP
DBMS_OUTPUT.PUT_LINE(x);
x := x+1;
END LOOP;
END;
/
BEGIN
FOR x IN 1..20 for(x=1;x<=20;x++)
LOOP
DBMS_OUTPUT.PUT_LINE(x);
END LOOP;
END;
/
BEGIN
FOR x IN 20..1 for(x=20;x<=1;x++)
LOOP
DBMS_OUTPUT.PUT_LINE(x);
END LOOP;
END;
/
BEGIN
FOR x IN REVERSE 1..20
LOOP
DBMS_OUTPUT.PUT_LINE(x);
END LOOP;
END;
/
01-jan-24 ?
02-jan-24 ?
31-dec-24 ?
DECLARE
d1 DATE;
d2 DATE;
BEGIN
d1 := '01-JAN-24';
d2 := '31-DEC-24';
WHILE(d1<=d2)
LOOP
DBMS_OUTPUT.PUT_LINE(d1||' '||TO_CHAR(d1,'day'));
d1 := d1+1;
END LOOP;
END;
/
DECLARE
d1 DATE;
d2 DATE;
BEGIN
d1 := '01-JAN-24';
d2 := '31-DEC-24';
d1 := NEXT_DAY(d1,'sunday');
WHILE(d1<=d2)
LOOP
DBMS_OUTPUT.PUT_LINE(d1||' '||TO_CHAR(d1,'day'));
d1 := d1+7;
END LOOP;
END;
/
28-may-24
INPUT :- ORACLE
OUTPUT :-
O
R
A
C
L
E
DECLARE
s1 VARCHAR2(20);
BEGIN
s1 := '&string';
FOR x IN 1..LENGTH(s1)
LOOP
DBMS_OUTPUT.PUT_LINE(SUBSTR(s1,x,1));
END LOOP;
END;
/
INPUT :- ORACLE
OUTPUT :-
O
OR
ORA
ORAC
ORACL
ORACLE
DECLARE
s1 VARCHAR2(20);
BEGIN
s1 := '&string';
FOR x IN 1..LENGTH(s1)
LOOP
DBMS_OUTPUT.PUT_LINE(SUBSTR(s1,1,x));
END LOOP;
END;
/
INPUT :- ORACLE
OUTPUT :- ELCARO
DECLARE
s1 VARCHAR2(20);
s2 VARCHAR2(20);
BEGIN
s1 := '&string';
FOR x IN 1..LENGTH(s1)
LOOP
s2 := s2||SUBSTR(s1,-x,1);
END LOOP;
DBMS_OUTPUT.PUT_LINE(s2);
IF s1 = s2 THEN
DBMS_OUTPUT.PUT_LINE('palindrome');
ELSE
DBMS_OUTPUT.PUT_LINE('not a palindrome');
END IF;
END;
/
Reference Types :-
-------------------------
1 %TYPE
2 %ROWTYPE
%TYPE :-
------------
ex :- vename emp.ename%TYPE;
=> whatever datatype and size declared for column ename the same type
and size assigned to variable vename.
%ROWTYPE :-
----------------------
ex :- e emp%ROWTYPE;
=> a row from emp table can be assigned to variable "e"
SELECT * INTO e
FROM emp
WHERE empno = 7844;
e
empno ename job mgr hiredate sal comm deptno
7844 turner salesman 1500 0 30
example :-
STUDENT
SNO SNAME S1 S2 S3
1 A 80 90 70
2 B 30 60 50
RESULT
SNO TOTAL AVG RESULT
=> write a prog to input sno and calculate total ,avg,result and insert into result table ?
DECLARE
vsno student.sno%TYPE;
s student%ROWTYPE;
r result%ROWTYPE;
BEGIN
vsno := &sno;
SELECT * INTO s FROM student WHERE sno = vsno ;
r.total := s.s1 + s.s2 + s.s3;
r.avg := r.total/3;
IF s.s1>=35 AND s.s2>=35 AND s.s3>=35 THEN
r.result := 'PASS';
ELSE
r.result := 'FAIL';
END IF;
INSERT INTO RESULT VALUES(vsno,r.total,r.avg,r.result);
COMMIT;
END;
/
s
sno sname s1 s2 s3
1 A 80 90 70
r
sno total avg result
240 80 PASS
CURSOR :-
-----------------
1 declare
2 open
3 fetch
4 close
Declaring cursor :-
-------------------------
ex :-
Opening :-
---------------
OPEN <cursor-name>;
OPEN C1 ;
=> a fetch stmt fetched one row at a time but to process multiple rows
fetch stmt should be executed multiple times. so fetch stmt should be
inside a loop.
Closing cursor :-
-------------------------
CLOSE <cursor-name>;
ex :- CLOSE C1
Attributes :-
--------------------
C1%FOUND
C1%NOTFOUND
C`1%ROWCOUNT
DECLARE
CURSOR C1 IS SELECT ENAME,HIREDATE FROM EMP ;
vename emp.ename%TYPE;
vdoj emp.hiredate%TYPE;
vexpr NUMBER(2);
BEGIN
OPEN C1;
FETCH C1 INTO vename,vdoj;
WHILE(C1%FOUND)
LOOP
vexpr := (SYSDATE-vdoj)/365 ;
DBMS_OUTPUT.PUT_LINE(vename||' '||vexpr);
FETCH C1 INTO vename,vdoj;
END LOOP;
CLOSE C1;
END;
/
29-may-24
EX :-
FOR r IN C1
LOOP
statements;
END LOOP;
Example :-
DECLARE
CURSOR C1 IS SELECT ENAME,SAL FROM EMP ;
BEGIN
FOR R IN C1
LOOP
DBMS_OUTPUT.PUT_LINE(R.ENAME||' '||R.SAL);
END LOOP;
END;
/
=> write a prog to calculate total sal without using sum function ?
DECLARE
CURSOR C1 IS SELECT SAL FROM EMP ;
t NUMBER := 0;
BEGIN
FOR R IN C1
LOOP
t := t + R.SAL;
END LOOP;
DBMS_OUTPUT.PUT_LINE(t);
END;
/
=> write a prog to calculate max sal without using max function ?
DECLARE
CURSOR C1 IS SELECT SAL FROM EMP ;
m NUMBER := 0;
BEGIN
FOR R IN C1
LOOP
IF R.SAL > m THEN
m := R.SAL;
END IF;
END LOOP;
DBMS_OUTPUT.PUT_LINE(m);
END;
/
DECLARE
CURSOR C1 IS SELECT SAL FROM EMP ORDER BY SAL DESC ;
vsal NUMBER(8);
BEGIN
OPEN C1;
FETCH C1 INTO vsal;
DBMS_OUTPUT.PUT_LINE(vsal);
CLOSE C1;
END;
/
STUDENT
SNO SNAME S1 S2 S3
1 A 80 90 70
2 B 30 60 50
RESULT
SNO TOTAL AVG RESULT
=> write a prog to input sno and calculate total ,avg,result and insert into result table ?
DECLARE
CURSOR C1 IS SELECT * FROM STUDENT ;
r RESULT%ROWTYPE;
BEGIN
FOR s IN C1
LOOP
r.total := s.s1 + s.s2 + s.s3;
r.avg := r.total/3;
IF s.s1>=35 AND s.s2>=35 AND s.s3>=35 THEN
r.result := 'FAIL';
ELSE
r.result := 'PASS';
END IF;
INSERT INTO RESULT VALUES(s.sno,r.total,r.avg,r.result);
END LOOP;
COMMIT;
END;
/
=============================================================
1 syntax errors
2 logical errors
3 runtime errors (exceptions)
=> errors raised during program execution are called runtime errors
ex :- X NUMBER(3);
DECLARE
declaration-part;
BEGIN
execution-part; => stmts causes exception
EXCEPTION
error handling - part; => stmts handles exception
END;
/
1 system defined
2 user defined
Example 1 :-
DECLARE
a NUMBER(3);
b NUMBER(3);
c NUMBER(3);
BEGIN
a := &a;
b := &b;
c := a/b;
DBMS_OUTPUT.PUT_LINE(c);
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE('divisor cannot be zero');
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('value exceeding size');
END;
/
Example 2 :-
DECLARE
veno emp.empno%TYPE;
vename emp.ename%TYPE;
vsal emp.sal%TYPE;
BEGIN
veno := &empno;
SELECT ename,sal INTO vename,vsal FROM emp WHERE empno = veno;
DBMS_OUTPUT.PUT_LINE(vename||' '||vsal);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('invalid empno');
END;
/
ex :-
=> write a prog to increment employee sal but sunday updates are not allowed ?
DECLARE
veno emp.empno%TYPE;
vamt NUMBER(5);
BEGIN
veno := &empno;
vamt := &amount;
IF TO_CHAR(sysdate,'dy')='sun' THEN
RAISE_APPLICATION_ERROR(-20001,'sunday not allowed');
END IF;
UPDATE EMP SET SAL = SAL + vamt WHERE EMPNO = veno;
COMMIT;
END;
/
========================================================================
=
30-may-24
1 procedures
2 functions
3 packages
4 triggers
SUB-PROGRAMS :-
---------------------------
1 procedures
2 functions
3 packages
Advantages :-
-------------------
1 modular programming :-
---------------------------------
=> with help of proc & func a big pl/sql program can be divided into small modules
2 reusability :-
-------------------
=> proc & func are stored in db , so applications which are connected to db
can reuse proc & func.
3 security :-
----------------
=> because proc & func are stored in db so they are secured and only
authorized users can execute the programs.
=> these programs can be called from front-end applications liike java/.net/python etc
5 improves performance :-
------------------------------------
=> proc & func improves performance because of one time compilation i.e.
when we create a procedure program is compiled and stored in db
and whenever we call procedure only execution is repeated but not
compilation ,so this improves performance.
procedures :-
------------------
=> procedures are created to perform one or more dmls operations on tables
SERVER
DATABASE
BATCH32
PROCEDURE
PACKAGE
PROCEDURE
standalone or stored procedures :-
-----------------------------------------------
parameters :-
------------------
X --------------------------------> A (IN)
Y <--------------------------------- B (OUT)
Execution :-
----------------
1 sql prompt
2 another pl/sql prog
3 front-end applications
EXECUTE procname(parameters);
ex :-
SQL>EXECUTE raise_salary ;
Execution :-
Execution :-
SQL>VARIABLE K NUMBER
SQL> EXECUTE RAISE_SALARY(7369,1000,:K);
SQL> PRINT :K
K
----------
4800
=> when parameters declared with default value then while calling procedure
use named association.
Execution :-
SQL>VARIABLE K NUMBER
SQL>EXECUTE raise_salary(peno=>7369,pnewsal=>:k);
SQL>PRINT :k
31-MAY-24
ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
101 S 20000
TRANSACTIONS
TRID TTYPETDATETAMT ACCNO
Execution :-
SQL>VARIABLE B NUMBER
SQL> EXECUTE DEBIT(100,5000,:B);
SQL> PRINT :B
=> a function is also a named PL/SQL block that accepts some input
performs some calculation and must return a value.
1 for calculations
2 to fetch data from table
CREATE OR REPLACE
FUNCTION <name>(parameters) RETURN <type>
IS
declaration-part;
BEGIN
statements;
RETURN expr;
END;
/
Example :-
Execution :-
1 SQL commands
2 another pl/sql prog
3 front-end
=> create a function that accept year and returns whether it is leap year or not ?
Execution :-
PROCEDURES FUNCTIONS
4 cannot be called from sql commands can be called from sql commands
USER_SOURCE :-
---------------------------
Droping :-
-----------
==========================================================
PACKAGES :-
------------------
1 package specification
2 package body
Advantages :-
1 easy to manage
2 supports overloading
3 supports hiding
package specification :-
----------------------------------
package body :-
-------------------
Example 1 :-
package specification :-
---------------------------------
CREATE OR REPLACE PACKAGE HR
AS
PROCEDURE HIRE(e NUMBER,n VARCHAR2,j VARCHAR2,s NUMBER,d NUMBER);
PROCEDURE FIRE(e NUMBER);
PROCEDURE RAISE_SALARY(E NUMBER,AMT NUMBER);
FUNCTION EXPR(E NUMBER) RETURN NUMBER;
END;
/
package body :-
----------------------
execution :-
SQL>EXECUTE HR.HIRE(333,'ABC','CLERK',4000,20);
SQL>EXECUTE HR.RAISE_SALARY(333,1000);
ACCOUNTS
ACCNO ACTYPE BAL
100 S 10000
101 S 20000
TRANSACTIONS
TRID TTYPETDATETAMT ACCNO
specification :-
-------------------
Body :-
----------
RETURN C1;
END GETSTMT;
FUNCTION GETSTMT(a NUMBER,n NUMBER) RETURN SYS_REFCURSOR
IS
C1 SYS_REFCURSOR;
BEGIN
OPEN C1 FOR SELECT *
FROM (SELECT *
FROM TRANSACTIONS
WHERE ACCNO = a
ORDER BY TDATE DESC)
WHERE ROWNUM <= n;
RETURN C1;
END GETSTMT;
END;
/
Droping :-
SQL>DROP PACKAGE BODY BANK ; => drops only package body but not specification
=============================================================
TRIGGERS :-
============
1 to control dmls
2 to enforce complex rules and validations
3 to audit day-to-day operations
BEFORE triggers :-
----------------------------
AFTER triggers :-
-----------------------
Ex :-
03-jun-24
Testing :-
------------
SQL>UPDATE EMP SET EMPNO = 9999 WHERE EMPNO = 7566 ; => ERROR
=> these two variables are called bind variables and rowtype variables.
=> record user is trying to insert is copied to :NEW variable.
=> record user is trying to delete is copied to :OLD variable.
=> record user is trying to update is copied to both :NEW & :OLD variables
UPDATE EMP SET SAL = 4000 WHERE EMPNO = 7839 ; => :OLD
:NEW
=> create trigger to insert details into emp_resign whenever employee resigns from organization
?
EMP_RESIGN
EMPNO ENAME HIREDATE JOB SAL DOR
VALUES(:OLD.EMPNO,:OLD.ENAME,:OLD.HIREDATE,:OLD.JOB,:OLD.SAL,SYSDATE);
END;
/
Testing :-
USER_TRIGGERS :-
------------------------------
SELECT TRIGGER_NAME,TRIGGER_TYPE,TRIGGERING_EVENT
FROM USER_TRIGGERS
WHERE TABLE_NAME='EMP' ;
Droping :-
---------------
SQL>DROP TRIGGER T1 ;
cursors
procedures
functions
packages
triggers
========================================================================
===
VIEWS :-
------------
=> a view is a virtual table because it doesn't store data and doesn't occupy memory
and it always derives data from base table.
=> with the help of view complex queries can be converted into simple queries
ex 1 :-
=> after creating view whenever user wants data from emp & dept tables then instead of
writing join query write the simple query
ex 2 :-
CREATE VIEW CV2
AS
SELECT d.dname,sum(e.sal) as totsal
FROM emp e INNER JOIN dept d
ON e.deptno = d.deptno
GROUP BY d.dname ;
=> after creating view whenever we want dept wise summary then execute the following query
SET OPERATORS :-
-----------------------------
UNION
UNION ALL
INTERSECT
MINUS
SELECT STATEMENTS 1
UNION / UNION ALL / INTERSECT / MINUS
SELECT STATEMENT 2 ;
CLERK
MANAGER
ANALYST
CLERK
ANALYST
JOB
---------
SALESMAN
SALESMAN
SALESMAN
MANAGER
SALESMAN
CLERK
UNION :-
-----------
ANALYST
CLERK
MANAGER
SALESMAN
UNION ALL :-
-------------------
CLERK
MANAGER
ANALYST
CLERK
ANALYST
SALESMAN
SALESMAN
SALESMAN
MANAGER
SALESMAN
CLERK
INTERSECT :-
--------------------
=> returns common values from the output of two select statements
SELECT JOB FROM EMP WHERE DEPTNO = 20
INTERSECT
SELECT JOB FROM EMP WHERE DEPTNO = 30 ;
CLERK
MANAGER
MINUS :-
------------
=> returns values present in 1st query output and not present in 2nd query output
CLERK
Question :-
T`1 T2
F1 C1
1 1
2 2
3 3
10 40
20 50
30 60
1 INNER JOIN
2 LEFT OUTER JOIN
3 RIGHT OUTER JOIN
4 FULL OUTER JOIN
5 UNION
6 UNION ALL
7 INTERSECT
8 MINUS
EMP_US
ENO ENAME SAL DNO
DEPT
EMP_IND DNO DNAME LOC
ENO ENAME SAL DNO
SELECT E.*,D.*
FROM EMP_US E INNER JOIN DEPT D
ON E.DNO = D.DNO ;
SELECT E.*,D.*
FROM EMP_US E INNER JOIN DEPT D
ON E.DNO = D.DNO
UNION
SELECT E.*,D.*
FROM EMP_IND E INNER JOIN DEPT D
ON E.DNO = D.DNO ;
SELECT E.*,D.*
FROM (SELECT * FROM EMP_US
UNION
SELECT * FROM EMP_IND) E INNER JOIN DEPT D
ON E.DNO = D.DNO ;