comple sql tables1
comple sql tables1
Syllabus
Friday, May 10, 2024 2:14 PM
ORACLE
SQL
TABLES
VIEWS
INDEXES
SEQUENCES
SYNONYMS
MATERIALIZED VIEWS
PL/SQL
ORACLE 2PM KPHB MAY 2024 Page 2
Cursors
Exception Handling
Collections
Stored procedures
Stored functions
Packages
Triggers
Dynamic SQL
ORACLE 2PM KPHB MAY 2024 Page 3
ORACLE
Thursday, May 9, 2024 2:12 PM
data store => is a location where data is stored database => is a location where
organization's business data stored permanently
DBMS => is a software => to create & maintain the database
RDBMS => is a software => to create & maintain DB in the form of tables metadata
BANK COLLEGE
Branches Courses
Customers Students
Transactions Fee
Products Marks
Employee
Goal:
Storing business data in computer permanently
int age; 18
age=18;
Emplyee e1 = new Employee(1234,"Raju");
1234 Raju
File:
• we can store data permanently
Database:
• we can store data permanently
File Database
Data Store:
• Data Store is a location where data is stored.
• Examples: File, Database
Database:
• Database is a kind of data store.
• It is a location where organization's business data stored permanently.
• Database is a collection of interrelated data in an organized form.
AMAZON DB Searching
for products products
Adding products to wish list wishlist
Placing order orders
payment payments
Products Marks
Employee
interrelated:
COLLEGE DB does not contain BANK related data BANK DB
does not contain college related data
organized:
arranged in specific way
DBMS:
• DBMS => database management system /software
• is a software
• used to create and maintain the database
introduced first RDBMS software => ORACLE in 1983 => company name
RDBMS:
• RDBMS => Relational Database Management System / Software.
• Relation => Table
• RDBMS is a software
• It is used to create and maintain the database in the form of tables
• RDBMS is one kind of DBMS
Examples:
ORACLE => ORACLE company
SQL SERVER => MICROSOFT company
MY SQL => SUN MICRO SYSTEMS
POSTGRE SQL => POSTGRE FORUM
DB2 => IBM
TABLE:
Example:
1235
1236
1237
Row:
Row is horizontal representation of data
Metadata:
Metadata is the data about the data.
Examples:
Column Names, Table Names, data types, field sizes
EMPLOYEE
Sai ERROR
12345 ERROR
BANK DB
BRANCHES Table
IFSCCODE CITY STATE
CUSTOMERS Table
CID CNAME CCITY MOBILE MAIL AADHAR PAN ACNO
TRANSACTIONS Table
TID T_DATE_TIME T_TYPE ACNO AMOUNT
EMPLOYEE Table
EMPNO ENAME SAL
ORACLE:
• ORACLE is a Relational DataBase Management Software [RDBMS]
BANK DB
BRANCHES Table
IFSCCODE CITY STATE
CUSTOMERS Table
CID CNAME CCITY MOBILE MAIL AADHAR PAN ACNO
TRANSACTIONS Table
TID T_DATE_TIME T_TYPE ACNO AMOUNT
EMPLOYEE Table
EMPNO ENAME SAL
• This software allows us to store, manipulate and retrieve the data of database.
Examples:
ORACLE [RDBMS]
queries
DATABASE
SQL TABLES
PL/SQL ROWS & COLUMNS
SQL:
• SQL => Structured Query Language.
• It is a query language.
• It is used to write queries.
TRUNCATE RENAME
TCL COMMIT
ROLLBACK
•TCL => Transaction Control Language SAVEPOINT
•It deals with transactions
DDL commands:
CREATE:
CREATE command is used to
create ORACLE DB Objects like
Tables, Views, ..etc.
ORACLE DATABSE OBJECTS:
TABLES
VIEWS
INDEXES
SEQUENCES
SYNONYMS
MATERIALIZED VIEWS
Stored Procedures
Stored Functions
Packages
Triggers
EMPLOYEE
EMPNO ENAME SAL
ALTER:
DROP
FLASHBACK [oracle 10g]
PURGE [oracle 10g]
EMPLOYEE
To Restore the table
FLASHBACK
Example:
DRL / DQL:
SELECT:
• it is used to retrieve the data from table
• retrieve => opening existing data
DML:
UPDATE:
used to modify table data
DELETE: used to delete the
records
TCL:
Transaction:
• Transaction is a series of actions [SQL Commands].
Examples:
Withdraw, Deposit, Fund Transfer, Placing Order
GRANT:
to give permission to other users we use GRANT
REVOKE:
to cancel the permissions we use REVOKE
SQL
DDL DRL DML TCL DCL
data definitions retrievals manipulations transactions accessibility
[metadata]
CREATE:
It is used to create the DB Objects like tables, views,
indexes …etc.
Note:
for WINDOWS OS, latest version is ORACLE 21C for LINUX
OS, latest version is ORACLE 23AI
Till ORACLE 21C, we can create max of 1000 columns only. From ORACLE
23AI, we can create max of 4096 columns.
Table / Relation /
Entity
EMPLOYEE
EMPID ENAME SAL
1234 Ravi 8000
column / field / property /
1235 Sai 10000 attribute
1236 Kiran 7000
16-MAY-24 2:49:15.123456 PM
Char(n):
• It is used to hold string values.
• n => max no of chars
• It is Fixed Length Data Type.
• extra memory will be filled with spaces.
• max size: 2000 Bytes [2000 chars]
• default size: 1
• to hold fixed length chars use CHAR(n)
Varchar2(n):
• It is used to hold string values.
• n => max no of chars • It is Variable Length Data Type.
• spaces will not be filled here.
• max size: 4000 Bytes [4000 chars]
• default size: no default size
• to hold variable length chars use VARCHAR2(n) Examples:
Note:
All character related data types can accept digits, letters and
special characters.
Note:
Varchar2 data type can hold max of 4000 chars only.
To hold more than 4000 chars we can use LONG or CLOB. CLOB is best ASCII:
one. • American
Standard Code for
Information
LONG:
• it is used to hold large amounts of chars.
nChar(n) •it is fixed length data type
• it has some restrictions:
•max size: 2000 Bytes [1000 chars]
○ A table can have only 1 column as LONG type.
•n => max no of chars
○ We cannot use built-in functions on LONG type.
• Max size: 2GB
nVarchar2(n) •it is variable length data type
•max size: 4000 Bytes [2000 chars]
CLOB: •n => max no of chars
• CLOB => Character Large Object
• it is used to hold large amounts of chars. Interchange
• A table can have multiple columns as CLOB type. • It is a coding
• We can use built-in functions on CLOB type column. system
• Max size: 4GB • 256 chars coded
• ranges from 0 to
255
• 255 => 1111
Examples: product_features
CLOB feedback CLOB 1111 => 8 bits [1
Byte]
• it supports to
ENGLISH language
only.
UNI:
• UNI =>
UNIVERSAL
In C:
Char(n) •ASCII code char data types
Varchar2(n) •Single Byte char data types
LONG •can hold ENGLISH language chars only
CLOB
n => national
• It is a coding system
• it is extension of ASCII
Note:
• 65536 chars coded
nVarchar2 data type can hold max of 2000 chars only.
• ranges from 0 to 65535
To hold more than 2000 chars use nCLOB. nCLOB can
• 65535 => 1111 1111 1111 1111 => 16 bits [2 Bytes]
hold upto 4GB.
• It supports to ENGLISH + Other Language Chars.
Integer Related data types:
NUMBER(p):
• It is used to hold integers.
• Integer => number without decimal places
• p => precision => max no of digits
• p valid range => 1 to 38
Examples:
Mobile_Number NUMBER(10)
Credit_Card_Number NUMBER(16)
Aadhar_Number NUMBER(12)
NUMBER(p,s):
• It is used to hold floating point values.
• number with decimal places is called "Floating point".
• p => precision => max no of digits
• s => scale => max no of decimal places
Examples:
-999.99 TO 999.99 Max Marks: 100
3 subjects
Avrg NUMBER(5,2) 300/3 = 100
----------
67.89
p=5 s=2
-999999.99 TO 999999.99
SALARY NUMBER(8,2)
---------------
35000
100000 100000.00
999999.99
1000000 ERROR
-------------
5.4 5.8
6.0 5.3
5.6
8.4 9.9
10 ERROR
6.3456789 => 6.3
6.3756789 => 6.4
DATE:
○ It is used to hold date values.
○ Default ORACLE date format: DD-MON-YY
○ Example: 18-MAY-24, 25-DEC-23
○ date also contains time value
○ it can hold date, month, year, hours, minutes and seconds.
○ By default it displays date only. ○ default time:
12:00:00 AM [mid night time] ○ fixed length data
type. ○ max size: 7 Bytes
Examples:
DOB DATE
DOJ DATE
Ordered_Date DATE Delivery_Date
DATE Timestamp:
• introduced in ORACLE 9i version.
• It is used to maintain date and time values.
• It is extension of DATE data type.
• It can hold fractional seconds also.
• It can hold date, month, year, hours, minutes, seconds and fractional
seconds.
• default time: 12:00:0.0 AM [mid night time]
• fixed length data type
• max size: 11 Bytes
Examples:
Transaction_date_time TIMESTAMP
----------------------------------
25-APR-24 10:30:0.0 AM
• it is used to hold date values • it is used to hold date and time values
Example: Example:
Date_Of_Joing DATE Transaction_date_time TIMESTAMP
Example:
EMPLOYEE
EMPNO ENAME STATE SAL Date_of_joining
BFILE:
• BFILE => Binary File Large object
• max size: 4 GB
• it is used to maintain multimedia objects like images, audios, videos,
animations and documents.
• it is used to maintain multimedia object's path.
• BFILE is pointer to multimedia object.
• It can be also called External Large Object. Because, Object will be
stored out of the database.
• It is not secured.
Database
EMP1 D:
EMPID ENAME EPHOTO [BFILE] Photos Folder
1001 Ravi D: \Photos \Ravi.jpg
Ravi.jpg
BLOB:
• BLOB => Binary Large Object
• max size: 4 GB
• It is secured.
Example:
Database
EMP2 D:
Photos Folder
EMPID ENAME EPHOTO [BLOB]
Fixed Length T1
Variable Length
F1 CHAR(10) F2 VARCHAR2(10)
RAJU6spaces RAJU
104
106 NARESH4spaces NARESH
103
SAI7spaces SAI
ORACLE 2PM KPHB MAY 2024 Page 26
Monday, May 20, 2024 2:10 PM
ORACLE:
• Server side software.
• the machine in which we install ORACLE software is called "ORACLE DB SERVER".
Note:
When we install ORACLE software, along with ORACLE, SQL PLUS
Software will be installed.
SQL PLUS:
• Client Side Software
• Using SQL PLUS software we can connect to ORACLE DB SERVER.
INSTANCE DB
SQL PLUS / connect query execution
Branches
services
Customers
SQL DEVELOPER /
Trans
TOAD
RAM Hard Disk
communicate
SQL => queries
PL/SQL => programs
Login as DBA:
username: system
password: nareshit [at the time of installation you have given password]
Note:
To implement database security DBA creates user. DBA provides
username and password to every SQL DEVELOPER.
Creating User:
Syntax:
Example:
Create a user with the name c##batch2pm and
username: system
password: nareshit [at the time of installation you have given password]
Output:
Grant succeeded.
Syntax:
CONN[ECT] <user_name>/<password>
Example:
SQL> CONN c##batch2pm/nareshit
Syntax:
Example:
Login as DBA:
as DBA:
Dropping user:
Syntax:
DROP USER <user_name> [CASCADE];
Note:
If USER [SCHEMA] is empty, no need to write CASCADE. If USER
is not empty, we must write CASCADE.
c##userAc##userB
T1
T2 empty
Syntax:
DESC[RIBE] <table_name>
all_users:
○ it is a system table / readymade table / built-in table
○ it maintains all users information
DESC all_users
CREATE:
• It is DDL command.
• It is used to create the DB objects like tables, views … etc.
INSERT:
• It is DML command.
• It is used to insert the records into table.
Syntax:
Example-1: p=5
s=2
STUDENT
SID SNAME AVRG
1235 XY 55.66
SID NUMBER(4)
SNAME VARCHAR2(10)
Inserting Records:
1234 ABC 67.89 COMMIT
1235 XY 55.66
INSERT INTO student VALUES(1234, 'ABC', 67.89);
ORACLE DB SERVER
CL[EAR] SCR[EEN]:
Syntax: CL[EAR]
SCR[EEN]
Example:
SQL> CL SCR
-- it clears the screen
Note:
Syntax to define parameter:
Example:
&sid
/
Output:
enter value for sid: 5002 enter
value for sname: CC enter value
for avrg: 34.23
/
enter value for sid: 5003 enter
value for sname: DD enter value
for avrg: 66.28
STUDENT
SID SNAME AVRG
7123 ZZZ
STUDENT
7124 89.23
COMMIT;
Example-2:
EMPLOYEE
empid NUMBER(4)
ename VARCHAR2(10)
state CHAR(2)
sal NUMBER(8,2)
doj DATE
Creating Table:
EMPLOYEE
DOJ DATE Implicit Conversion
----------
25-DEC-23 date
EMPLOYEE
DOJ DATE to_date()
-------------- Explicit Conversion
17-AUG-20 date
Note:
To insert the date value use to_date() function.
COMMIT;
Note: sysdate:
• it is a built-in function.
• it returns current system date.
Example:
SELECT sysdate FROM dual;
Example-3:
EMPLOYEE1
EMPID ENAME LOGIN_DATE_TIME
empid NUMBER(4)
ename VARCHAR2(10)
login_date_time TIMESTAMP
CREATE TABLE employee1
(
empid NUMBER(4), ename
VARCHAR2(10),
login_date_time TIMESTAMP
);
login_date_time timestampto_timestamp()
---------------------------explicit conversion 21-MAY-2024
2:30:0.0 PM timestamp
systimestamp:
• it is a built-in function.
• it returns current system date and time.
Example:
SELECT systimestamp FROM dual;
implicit conversion:
If conversion is done implicitly by ORACLE then it is
called "Implicit Conversion".
Example:
num num
100 + 200
Output: 300
explicit conversion:
If conversion is done using built-in function then it is
called "Explicit Conversion".
Example:
Conversion
number number
+
Output: 100 200
300
Note:
• Don't depend on Implicit Conversion.
• Implicit Conversion degrades the performance.
ORACLE 2PM KPHB MAY 2024 Page 41
PAGE
default PAGESIZE 14
default LINESIZE 80 abcd……………….. 80 chars
………….
………..
……….
14 lines
Syntax:
SET LINES[IZE] <size>
Example:
SET LINES 200
Syntax:
SET PAGES[IZE] <size>
Example:
SET PAGES 200
ORACLE 2PM KPHB MAY 2024 Page 42
show all
Output:
LINESIZE 300
PAGESIZE 300
ORACLE 2PM KPHB MAY 2024 Page 43
Column Alias
Thursday, May 23, 2024 3:14 PM
Column Alias:
• It is used to change column heading in output.
• It temporary name.
• Its scope is limited to that query only.
• To give column alias we use 'AS' keyword.
• Using 'AS' keyword is optional.
Example:
SELECT ename AS A, sal AS B FROM
emp;
Output:
A B
--------- -----------
SMITH 800
ALLEN 1600
ORACLE 2PM KPHB MAY 2024 Page 44
Editing Query
Friday, May 24, 2024 3:28 PM
SQL> ED
displays editor
SQL> /
ORACLE 2PM KPHB MAY 2024 Page 45
DRL
Wednesday, May 22, 2024 3:30 PM
DRL / DQL:
Server.
SELECT:
○ SELECT command is used to retrieve the data from table.
○ Using SELECT command we can select:
▪ all columns and all rows
▪ all columns and specific rows ▪ specific columns and all rows
▪ specific columns and specific rows Syntax of SELECT command:
* All Columns
Implicitly ORACLE replaces * with all column names.
SELECT empno, ename, job, mgr, hiredate, sal, comm, deptno FROM emp;
SELECT *
FROM emp
WHERE sal=3000;
OPERATOR:
• OPERATOR is a symbol that is used to perform operations like arithmetic or logical
operations.
Special / IN NOT IN
Comparison BETWEEN AND NOT BETWEEN AND
LIKE NOT LIKE
IS NULL IS NOT NULL
ANY
ALL
EXISTS
Concatenation ||
Arithmetic Operators:
Arithmetic Operators are used to perform arithmetic operations like addition, subtraction …
etc.
+ Addition In C/ Java:
5/2 = 2
- Subtraction 5%2 = 1
* Multiplication
In SQL:
/ Divison 5/2 = 2.5
Mod(5,2) = 1
Examples on Arithmetic Operators:
Output:
ENAME SAL SAL*12
-------------------------------------------------------
SMITH 800 9600
ALLEN 1600 19200
Output:
ENAME SAL ANNUAL_SAL
-------------------------------------------------------
SMITH 800 9600
ALLEN 1600 19200
Output:
ENAME SAL Annual Salary
-------------------------------------------------------
SMITH 800 9600
ALLEN 1600 19200
Calculate TA, HRA, TAX and GROSS salaries of all emps:
TA => 10% on sal
HRA => 20% on sal
TAX => 5% on sal
GROSS = sal+TA+HRA-TAX
Assignment: STUDENT
SID SNAME M1 M2 M3
1234 A 70 80 50
1235 B 44 66 55
calculate total marks and average marks of all students
Syntax:
<column> <relational_operator> <value>
Note:
SQL is not case sensitive language. But, String comparison is case sensitive.
Note:
Calendar Order is Ascending order.
1-JAN-1981
..
31-DEC-1981 joined after 1981
1-JAN-1982
. hiredate>'31-DEC-1981'
.
. . hiredate<'1-JAN-1981'
30-DEC-1980 31-
DEC-1980
1-JAN-1981
..
31-DEC-1981
Display the emp records whose annual salary is more than 30000:
Display the emp records who are having more than 42years experience:
• Logical Operators are used to perform logical operations like Logical AND, Logical OR,
Logical NOT operations.
c1 Condtion1
c2 Condition2
c1 c2 c1 c1
AND OR
c2 c2
T T T T
T F F T
F F F F
Examples on AND, OR:
job
--------
MANAGER
ANALYST CLERK
SALESMAN
Display the emp records who are working in deptno 10 and 20:
Display the emp reocrds whose empnos are: 7499, 7698, 7900:
SELECT *
FROM emp
WHERE empno=7499 OR empno=7698 OR empno=7900;
SELECT *
FROM emp
WHERE ename='BLAKE' OR ename='WARD' OR ename='MILLER';
Display all managers records whose salary is more than 2500 and who joined after april 1981:
Example:
STUDENT5
SID SNAME M1 M2 M3
1001 A 60 90 80
1002 B 70 30 60
CREATE TABLE student5
Display all salesmen and clerks records whose salaries are more than 1250:
NOT:
• it is used to perform logical NOT operations.
Truth Table:
F NOT(F) => T
Display all emp records except managers:
(or)
IN:
(or)
IN:
Syntax:
<column> IN(<values_list>)
Examples:
WHERE sal IN(1250,2450,3000)
SAL
----
1000 F
3000 T
Examples on IN:
JOB
--------------
MANAGER T
ANALYST F
CLERK T
SALESMAN F
SELECT *
FROM emp
WHERE empno IN(7499,7698,7900);
EMPNO
---------
7369 F
7499 T
7521 F
7698 T
7876 F
7900 T
Display the emp records who are working in deptno 10 and 30:
Display the emp records whose names are: SCOTT, MILLER and
JAMES
SELECT *
FROM emp
WHERE ename IN('SCOTT','MILLER','JAMES');
if JOB value NOT IN list, condn is TRUE if JOB value is IN list, condn is FALSE
JOB
----------
MANAGER F
SALESMAN T
CLERK F ANALYST T
BETWEEN AND:
• It is used to compare column value with a range of values.
Syntax:
<column> BETWEEN <lower> AND <upper>
Display the emp records whose salary is 2450 or more and 3000 or less [whose sal is b/w
2450 and 3000]:
SAL
---------
2800 T
5000 F
3000 T
1000 F
2450 T
1-JAN-1982 min
..
31-DEC-1982 max
SELECT ename, hiredate
FROM emp
WHERE hiredate>='1-JAN-1982' AND hiredate<='31-DEC-1982';
(or)
SELECT *
FROM emp
WHERE empno BETWEEN 7400 AND 7700;
(or)
Answer: C
LIKE:
• it is used to compare column value with text pattern.
Syntax:
<column> LIKE <text_pattern>
In windows os,
* replaces 0 or any
In SQL,
to specify text pattern it provides 2 wildcard characters. They are:
_ replaces 1 char
Display the emp records whose names are started with 'S' letter:
Display the emp records whose names are ended with RD:
Display the emp records whose names are started and ended with S:
Display the emp records whose names are not started with S letter:
IS NULL:
Syntax:
<column> IS NULL
Examples:
Concatenation Operator:
Syntax:
<string1> || <string2> Examples:
EMPLOYEE
EMPID FNAME MNAME LNAME
SELECT ename || ' works as ' || job || ' and joined on ' || hiredate
FROM emp;
NULL:
• NULL means empty or blank.
• It is not a value.
• When we don't know the value or when we are unable to insert
the value we insert NULL
Example:
SELECT 100+200 FROM dual; --300
Note:
We can insert NULL using 2 ways. They are:
• direct way: using NULL keyword
ORACLE 2PM KPHB MAY 2024 Page 72
Example:
EMPLOYEE
EMPNO ENAME SAL
CREATE TABLE employee
(
empno NUMBER(4), ename
VARCHAR2(10), sal
NUMBER(8,2)
);
1234 A
1st way: direct way => using null keyword
1236 C
2nd way: indirect way => insert limited column values
UPDATE:
• UPDATE command is used to modify table data.
UPDATE <table_name>
SET <column>=<new_value> [, <column>=<new_value> , …..]
[WHERE <condition>];
UPDATE emp
SET sal=sal+2000
WHERE empno=7698;
UPDATE emp
SET job='MANAGER', sal=6000 WHERE empno=7369;
UPDATE emp
SET sal=sal+sal*0.1
WHERE job='MANAGER';
UPDATE emp
SET sal=sal+1000;
UPDATE emp
SET deptno=20
WHERE deptno=10;
UPDATE emp
SET sal=sal+sal*0.1
WHERE hiredate BETWEEN '1-JAN-1982' AND '31-DEC-1982'; Increase 20% on
salary to the employees who are having more than 42years experience:
UPDATE emp
SET sal=sal+sal*0.2
WHERE TRUNC((sysdate-hiredate)/365)>42;
UPDATE emp
SET sal=sal+sal*0.1, comm=comm+comm*0.2
WHERE comm is not null;
Set comm as 900 to the emps who are not getting comm:
UPDATE emp
SET comm=900
WHERE comm is null;
Set comm as null to the emps whose empnos are 7499, 7521,
7698:
UPDATE emp
SET comm=null
WHERE empno IN(7499,7521,7698);
DELETE:
• DELETE command is used to delete the records from table.
Examples on DELETE:
delete the emp records who are working in deptno 10 and 30:
TCL:
• TCL => Transaction Control Language
ACCOUNTS
ACNO NAME BALANCE
Note:
Every transaction must be successfully finished or cancelled.
If transaction is successful, to save it use COMMIT
If transaction is unsuccessful, to cancel it use ROLLBACK
COMMIT [Save]:
• When COMMIT command is executed the data in INSTANCE [RAM] will be moved to
DATABASE [HARD DISK].
ORACLE DB SERVER
Client
INSTANCE DB
1001 => INSERT 1001 EMP
1002 1001
1002 => INSERT
1002
RAM Hard Disk
Syntax:
ROLLBACK [TO <savepoint_name>];
Note:
EMPLOYEE10
EMPNO ENAME SAL
CREATE TABLE employee10
(
empno NUMBER(4), ename
VARCHAR2(10), sal
NUMBER(8,2)
);
Output: empno
----------
1001 1002
1003
1004
Output: empno
----------
1001
1002
Syntax:
SAVEPOINT <savepoint_name>;
Example:
SAVEPOINT p1;
Note:
All DDL commands are auto committed.
All DML commands are not auto committed.
Example:
ALTER
Wednesday, May 29, 2024 3:12 PM
ALTER:
• ALTER => Change
Note:
• to modify table data we use UPDATE
• to modify table structure we use ALTER
Example:
Table
EMPLOYEE
EMPNO ENAME SAL Table Structure [columns]
1001 A 7000
1002 B 10000
1003 C 8000 Table data [rows]
1004 D 9000
Syntax:
Example on ALTER:
STUDENT
SID SNAME VARCHAR2(10)
CREATE TABLE student
(
sid NUMBER(4), sname
VARCHAR2(10)
);
Output:
Table created.
DESC student
Output:
NAME TYPE
------------------------------------
SID NUMBER(4)
SNAME VARCHAR2(10) M1 NUMBER(3)
M2 NUMBER(3)
SNAME
------------
SAI
NARESH => MAX STRING LENGTH => 6 RAVI
DROP
FLASHBACK
PURGE
Note:
RECYCLEBIN feature added in ORACLE 10g version.
DROP:
• DROP command is used to delete (drop) the table.
Syntax:
RECYCLEBIN
Example:
student
DROP TABLE student;
Output:
Table dropped.
TO see RECYCLEBIN:
SHOW RECYCLEBIN
Output:
ORIGINAL_NAME RECYCLEBIN_NAME
------------------------ -------------------------------
STUDENT ……..
FLASHBACK:
• FLASHBACK command introduced in ORACLE 10g version.
Example:
FLASHBACK TABLE student TO BEFORE DROP;
PURGE:
• PURGE command introduced in ORALCLE 10g version.
• It is used to delete the table from RECYCLEBIN. This table will be deleted permanently. Again we
cannot recollect it.
Syntax:
PURGE TABLE <table_name>;
Example:
PURGE TABLE student;
RECYCLEBIN
DROP TABLE student;
student
FLASHBACK RESTORE
PURGE
Example:
COMMIT;
TO see Recyclebin:
SHOW RECYCLEBIN
Output:
STUDENT5
SHOW RECYCLEBIN
CASE-1:
T1 => 3:22
T1 => 3:20
INSERT INTO t1
CREATE TABLE t1(f1 VARCHAR2(10)); VALUES('A');
Syntax:
FLASHABCK TABLE "<recyclebin_name>" TO BEFORE DROP;
Example:
FLASHBACK TABLE "BIN$+dM9bzlNS9mBqngd1+3j8g==$0" TO BEFORE DROP;
CASE-2:
FLASHBACK TABLE t2
TO BEFORE DROP;
Output: ERROR:
original name already used by existing object
FLASHBACK TABLE t2
TO BEFORE DROP RENAME TO
t2_old;
Emptying recyclebin:
PURGE RECYCLEBIN;
--it empties recyclebin
DCL / ACL:
• DCL => Data Control Language
• ACL => Accessing Control Language
GRANT:
• It is used to give permission on DB Objects to other users.
Syntax:
GRANT <privileges_list>
ON <DB_Object> TO <users_list>;
Examples:
USER c##batch2pm:
GRANT select
ON emp
TO c##userA; login as
c##userA:
GRANT all
ON emp
TO c##userA;
GRANT select
ON emp
TO c##userA, c##userB, c##userC;
GRANT select
ON emp
TO public;
REVOKE:
• REVOKE command is used to cancel the permissions.
Syntax:
Syntax:
REVOKE <privileges_list>
ON <DB_Object>
Examples:
REVOKE select
ON emp
FROM c##userA;
REVOKE all
ON emp
FROM c##userA;
REVOKE all
ON emp
FROM c#3userA, c#3userB, c##userC; Cancel all permissions on emp table from
all users:
REVOKE all
ON emp
FROM public;
Login as DBA:
T1
F1 F2
1 A
2 B
CREATE TABLE t1
(
f1 number(4), f2 varchar2(10)
);
UPDATE c##userA.t1
SET f2='SAI' WHERE f1=1;
Output:
ERROR: insufficient privileges
UPDATE c##userA.t1
SET f2='SAI'
WHERE f1=1;
Output: 1 row updated
COMMIT;
GRANT all
ON t1
TO c##userB;
DESC t1 Output:
F1
F2
F3
user_tab_privs_made:
• it is a system table / readymade table.
• it maintains all the permissions made by the GRANTOR.
DESC user_tab_privs_made
user_tab_privs_recd:
• it is a system table / readymade table.
• it maintains all the permissions received by the GRANTEE.
DESC user_tab_privs_recd
Copying table:
Syntax:
Example-1:
Create a new table with the name emp1 from existing table emp.
Create exact copy of emp:
exact copy
EMP EMP1
8 columns 8 columns 15 rows 15 rows
Create a new table with the name emp2 from existing table emp
with 4 columns empno, ename, job, sal and managers records:
Syntax: false_condition:
Example-1:
Create a new table with the name emp3 with emp table structure.
Don't copy the records:
EMP3
EMP 8 columns
8 columns no rows
15 rows
CREATE TABLE emp3
AS
SELECT * FROM emp WHERE 1=2;
Example-2:
Create a new table with the name emp4 from existing emp
with 4 columns empno, ename, job, sal and without rows:
Copying records:
Syntax:
Example:
Example-2:
INSERT ALL:
• Introduced in ORACLE 9i version.
• It is used to copy one table records to multiple tables.
• it avoids of writing multiple INSERT commands.
• it can be used to perform ETL operations
• E => Extract, T => Transfer, L => Load
Syntax:
INSERT ALL
INTO <table_name>[(<columns_list>)] VALUES(<values_list>)
EMP10
EMP
columns empno,ename,job,sal
columns copy
no
rows
15 rows copy
EMP11
15 rows
copy
EMP11
4 columns empno,ename,job,sal
copy no rows
create
EMP12
4 columns empn,ename,job,sal
no rows
emp10, emp11, emp12 from existing table emp with 4 columns empno,ename,job,sal
Copy emp table 4 columns empn,ename,job,sal all rows to emp10, emp11, emp12 tables:
INSERT ALL
INTO emp10 VALUES(empno, ename, job, sal)
INTO emp11 VALUES(empno, ename, job, sal)
INTO emp12 VALUES(empno, ename, job, sal) SELECT empno, ename,
job, sal FROM emp;
EMP EMP_MGR
8 columns 4 cols empno,ename,job,sal
INSERT ALL
WHEN <condition> THEN
INTO <table_name>[(<columns_list>)] VALUES(<values_list>) WHEN
<condition> THEN
INTO <table_name>[(<columns_list>)] VALUES(<values_list>) WHEN
<condition> THEN
INTO <table_name>[(<columns_list>)] VALUES(<values_list>)
.
.
[ELSE
INTO <table_name>[(<columns_list>)] VALUES(<values_list>)]
<SELECT QUERY>;
15 rows no rows
copy
MANAGER rows
CLERK rows copy EMP_CLERK
SALESMAN rows 4 cols empno,ename,job,sal
ANALYST rows no rows
PRESIDENT
copy
PRESIDENT
copy
EMP_OTHERS
4 cols empno,ename,job,sal
no rows
copy all managers recoords to emp_mgr all clerks records to emp_clerk other
than manager, clerk to emp_others:
INSERT ALL
WHEN job='MANAGER' THEN
INTO emp_mgr VALUES(empno,ename,job,sal)
WHEN job='CLERK' THEN
INTO emp_clerk VALUES(empno,ename,job,sal)
ELSE
INTO emp_others VALUES(empno,ename,job,sal) SELECT empno,ename,job,sal FROM emp;
S.cid = T.cid
Branch Office Head office
MERGE:
• introduced in ORACLE 9i version.
• It is used to apply one table changes to it's replica.
• MERGE = UPSERT + INSERT
• MERGE is a combination of UPDATE and INSERT commands.
• It can be also called as UPSERT command.
• It avoids of writing a separate PL/SQL program.
Syntax:
Example on MERGE:
1003 C DLH
1003 C DLH
1004 D CHN
1005 E HYD
CREATE TABLE customer1
(
cid NUMBER(4), cname
VARCHAR2(10), ccity
CHAR(3)
);
1005 E HYD
INSERT INTO customer1 VALUES(1004,'D','CHN');
INSERT INTO customer1 VALUES(1005,'E','HYD');
COMMIT;
Output:
5 rows merged.
TRUNCATE:
• It is used to delete all rows from table with good performance.
Example:
Table
CUSTOMER1 S
CID CNAME CCITY Table Structure [columns]
1001 ABC BLR
+
1002 B MUM
1003 C DLH Table Data [rows]
1004 D CHN
1005 E HYD
Syntax:
TRUNCATE TABLE <table_name>;
Example:
TRUNCATE TABLE customer1;
TRUNCATE DELETE
• faster
DATABASE
SEGMENT
EXTENT [64KB]
--records --records
--records --records
--records --records
--records --records
DATABASE
TABLESPACES
SEGMENTS
EXTENTS
BLOCKS
RECORDS
RENAME:
• It is used to rename the table.
Syntax:
RENAME <old_name> TO <new_name>;
Example:
RENAME emp TO e;
ORACLE 2PM KPHB MAY 2024 Page 117
DUAL
Tuesday, June 4, 2024 2:42 PM
DUAL:
• DUAL is a system table / readymade table / dummy table.
• It has 1 column and 1 row.
Example:
SQL> DESC dual Output:
NAME TYPE
--------------------------------
DUMMY VARCHAR2(1)
300
300
300
..
String Functions:
Lpad()
Substr() Instr() Rpad()
lower() upper()
initcap() Replace()
Ltrim()
Rtrim() Translate()
length() concat()
Trim()
lower():
• It is used to convert the string to lower case.
Syntax:
lower(<string>)
Examples:
lower('RAJU') raju
Display all emp names and salaries. display emp names in lower case:
UPDATE emp
SET ename=initcap(ename);
Display the emp record whose name is BLAKE when we don't know exact case:
Syntax: length(<string>)
Examples:
length('RAJU') 4
length('RAVI TEJA') 9
Examples:
(or)
Display the emp records whose names are having 6 or more letters:
Concat():
• Concat => Concatenate / combine
• It is used to combine 2 strings
Syntax:
Concat(<string1>, <string2>)
Examples:
EMPLOYEE
EMPID FNAME MNAME LNAME
SELECT fname || ' ' || mname || ' ' || lname FROM employee;
Substr():
• It is used to get sub string from the string.
• sub string => part of the string.
Examples:
1 2 3 4 5 6 7 8 9
R A V I T E J A
Substr('RAVI TEJA',3,4) VI T
2nd argument can be negative.
+ve from left side position number
(or)
Display the emp records whose names are started with VOWEL:
(or)
Display the emp records whose names are started and ended with same letter:
Display the emp records whose names are started and ended with
VOWEL:
SELECT ename,sal
FROM emp
WHERE substr(ename,1,1) IN('A','E','I','O','U') AND substr(ename,-1,1)
IN('A','E','I','O','U');
generate mail ids to all emps by taking emp name's first 3 chars and
empno's last 3 chars as username for the domain 'wipro.com':
7369 SMITH
7499 ALLEN
Add mail id column:
UPDATE emp
SET mail_id = Substr(ename,1,3) ||
Substr(empno,-3,3) || '@wipro.com';
Instr():
• it is used to check whether the sub string is existed in string or not.
• If sub string is existed, it returns position number.
• If sub string is not existed, it returns 0.
Syntax:
Instr('SAI KRISHNA','KRISH') 5
Instr('SAI KRISHNA','RAMU') 0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
T H I S I S H I S W I S H
Example:
UPDATE employee17
SET fname=Substr(ename,1,Instr(ename,' ')-1),
lname=Substr(ename,Instr(ename,' ')+1);
Lpad():
it is used to fill specified character set at left side
Syntax:
Lpad(<string>, <size> [, <char_set>]) char_set => char / chars
3rd arg default char => space
Rpad():
it is used to fill specified character set at right side
Rpad('RAJU',10,'*') RAJU******
Lpad('SAI',10,'@$') @$@$@$@SAI
Lpad('raju',8) 4spacesraju
Rpad('raju',8) raju4spaces
Lpad('A',6,'A') AAAAAA
Lpad('X',8,'X') XXXXXXXX
Example:
Display message as following:
amount debited from acno XXXXXX7890 acno => 1234567890
Ltrim():
• it is used to remove unwanted characters from left side.
Syntax:
Ltrim(<string> [, <char/chars>])
2nd arg default char => space
Rtrim():
• it is used to remove unwanted characters from right side.
Syntax:
Rtrim(<string> [, <char/chars>])
2nd arg default char => space
Examples:
Ltrim('@@@RAJU@@@','@') RAJU@@@
Syntax:
Trim(Leading/Trailing/Both <char> FROM <string>) Examples:
Trim(Leading '*' FROM '***RAJU***') RAJU***
Replace():
• It is used to replace search string with replace string.
Syntax:
Replace(<string>, <search_string>, <replace_string>) Examples:
Replace('RAVI TEJA', 'TEJA', 'KUMAR') RAVI KUMAR
Replace('RAVI TEJA RAVI TEJA RAVI','RAVI','SAI') SAI TEJA SAI TEJA SAI
Translate():
• it is used replace search char with corresponding char in replace char set.
Syntax:
Translate(<string>, <search_char_set>, <replace_char_set>) Examples:
REPLACE('SAI KRISHNA','SAI','XYZ') XYZ KRISHNA
S => X
A => Y
I => Z
hello @ZQQ$
hello
encryption
@ Z W # $ Q ^ * B Y
SELECT ename,
translate(sal, '0123456789','@ZW#$Q^*BY') AS sal FROM emp;
Note:
There are 2 types of conversions. They are:
• Implicit Conversion
• Explicit Conversion
Implicit Conversion:
• If conversion is done implicitly by ORACLE then it is called "Implicit Conversion".
Example:
SELECT '100' + '200' FROM dual;
string string
implicit conversion
100 + 200 num num
Output:
300
Explicit Conversion:
• If conversion is done using built-in function then it is called "Explicit Conversion".
Conversion Functions:
• to_number()
to_char()
to_char()
to_date() to_number()
• to change date formats or to extract part of the date we need to convert date to char
[string].
Syntax:
To_Char(<date>, <format>)
1 => sun 2
=> mon
.
.
7 => sat
31+29+31+30+31+7 = 159
DY short weekday name to_char(sysdate,'DY') FRI
SUN
SUNDAY
1 => jan-mar
2 => apr-jun
3 => jul-sep
4 =>oct-dec
MI minutes part
FF fractional seconds
from sysdate:
Display all emp names and hiredates. Display hiredates in INDIA date format:
Display all emp names and hiredates. Display hiredates in US date format:
(or)
Display the emp records who joined in 1st and 4th quarters:
SELECT ename, hiredate
FROM emp
WHERE to_char(hiredate,'Q') IN(1,4);
D, DY, DAY
(or)
SELECT ename, hiredate
FROM emp
WHERE to_char(hiredate,'DY')='SUN'; ----displays who joined on SUNDAY
SUNDAY3spaces
MONDAY3spaces
TUESDAY2spaces
WEDNESDAY max string length => 9
THURSDAY1space
FRIDAY3spaces
SATURDAY1space
(or)
SELECT ename, hiredate
FROM emp
WHERE to_char(hiredate,'DAY')='SUNDAY ';
SUNDAY3spaces = SUNDAY3spaces T
• to apply currency symbol, thousand separator, decimal point, decimal places we need to
convert number to char.
Syntax:
To_Char(<number> [, <format>, <NLS_PARAMETERS>])
FORMAT PURPOSE
L currency symbol
default currency symbol is: $
C currency name
default currency name is: USD
9 Digit
To_Char(123.45) '123.45'
To_char(5000,'C9999.99') USD5000.00
Display all emp names and salaries.
Apply currency symbol $, thousand separator and 2 decimal places to all salaries:
Note:
NLS_CURRENCY $
NLS_ISO_CURRENCY AMERICA
Display all emp names and salaries.
Apply currency symbol ¥, thousand separator and 2 decimal places to all salaries:
To_Date():
Syntax:
To_Date(<string> [, <format>]) Examples:
To_Date('25-DEC-2023') 25-DEC-23
To_Date('25/12/2023') ERROR
TO_Date('25/12/2023','DD/MM/YYYY') 25-DEC-23
Example:
F1 DATEimplicit conversion
---------
F1 DATEimplicit conversion
---------
25-DEC-23 date
F1 DATE
--------------- to_date()
17-AUG-22 date explicit
conversion
/
enter value for d: .. enter value for m:..
enter value for y:.. to_char(sysdate, 'YYYY') => 2024
date
Find the weekday on which SACHIN born if SACHIN DOB is: 24-APR-1973?
Syntax:
To_Number(<string> [, <format>])
Examples:
To_Number('123') 123
To_Number('123.45') 123.45
To_Number('$5,000.00') ERROR
To_Number('$5,000.00','L9,999.99') 5000
To_Number('USD5000.00','C9999.99') 5000
Aggregate Functions / Group Functions / Multi Row Functions:
sum(f1) 10+20+30 = 60
F1
----- avg(f1) 60/3 = 20
10
max(f1) 30
20
30 min(f1) 10
count(f1) 3
sum():
• it is used to find sum of a set of values.
Syntax: sum(<column>)
Examples:
find sum of salaries of all emps: SELECT sum(sal) FROM emp;
avg():
• it is used to find average of a set of values.
Examples:
find avrg salary of all emps
SELECT avg(sal) FROM emp;
max():
• it is used to find max value in a set of values.
Syntax: max(<column>)
Examples:
find max salary in all emps:
SELECT max(sal) FROM emp;
min():
• it is used to find min value in a set of values.
Syntax: min(<column>)
Examples:
find min salary in all emps:
SELECT min(sal) FROM emp;
count():
• it is used to find number of records or number of column values.
Syntax:
find how many emps are getting commission: SELECT count(comm) FROM emp;
Note:
When we use GROUP FUNCTION, SELECT clause allows either group functions or group
columns
Example:
SELECT ename, max(sal) FROM emp; Output:
ERROR
Date Functions:
sysdate:
• it returns current system date
Example:
Display current system date:
SELECT sysdate FROM dual;
systimestamp:
• it returns current system date and time
Example:
Display current system date and time: SELECT systimestamp FROM dual;
Add_Months():
• it is used to add months to specific date.
• it can be also used to subtract months from date.
Syntax:
Add_Months(<date>, <number_of_months>)
Examples:
Add 2 days to today's date:
SELECT sysdate+2 FROM dual;
TS RR 10-DEC-23 Add_Months(startdate,5*12)
EMP
EMPID ENAME DOB DOR
Note: to remove time value from date and time we use TRUNC() function.
Example:
SELECT systimestamp FROM dual; Output:
10-JUN24 3:41:15.123456 PM
Display the emp records who joined 1 month ago from today:
Display the emp records who joined 1 year ago from today:
Assignment:
GOLDRATES
2-JAN-2020 51000
..
..
SALES
11-JUN-2024 69000
DATEID AMOUNT find today's sales? find
yesterday's sales? find 1 month ago sales? find 1 year
1-JAN-2020 70000
ago sales?
Last_day(): 2-JAN-2020 90000
• it is used to get last date in the month.
..
Syntax:
..
Last_day(<date>)
Examples:
11-JUN-2024 86000
Last_Day(sysdate) 30-JUN-24
Last_Day('25-FEB-2023') 28-FEB-23
Last_Day('17-FEB-2024') 29-FEB-24
Find next month first date:
Next_day():
• it is next date based on weekday.
• for example, to find coming Sunday date, coming Friday date
Syntax:
Next_day(<date>, <week_day>)
Examples:
Months_Between():
• it is used to find difference between 2 date values.
• it returns no of months.
Syntax:
Months_Between(<date1>, <date2>)
Examples:
SELECT Months_Between('11-JUN-2024','11-JUN-2023') FROM dual; Output:
12
(or)
SELECT
TRUNC(months_between(sysdate,'24-APR-1973')/12) AS age FROM dual;
RANK()
DENSE_RANK()
ROW_NUMBER()
RANK():
• it is used to apply ranks to records according to specific column order.
Syntax:
RANK() OVER([PARTITION BY <column>] ORDER BY <column>
ASC/DESC)
DENSE_RANK():
• it is used to apply ranks to records according to specific column order.
Syntax:
DENSE_RANK() OVER([PARTITION BY <column>]
ORDER BY <column> ASC/DESC)
ORDER BY marks DESC
MARKS MARKS RANK DENSE_RANK
780 950 1 1
950 840 3 2
840 840 3 2
400 780 5 3
950 780 5 3
780 780 5 3
840 600 8 4
600 560 9 5
780 400 10 6
difference b/w RANK() and DENSE_RANK():
RANK() does not follow sequence in ranking if multiple values are same. gaps may be
there in ranking.
DENSE_RANK() always follows sequence in ranking even if multiple values are same. gaps
will not be there in ranking
Examples:
(or)
Apply ranks to all emp records according to salary descending order. if salary is same don't
apply same rank. if salary is same apply rank according to seniority:
Apply ranks to emp records according to salary descending order with in dept:
SELECT ename,deptno,sal,
dense_rank() over(partition by deptno order by sal desc) as rank FROM emp;
clear breaks
PARTITION BY clause:
it is used to group the records according to specific column.
ORDER BY clause:
it is used to arrange the records in ascending or descending order.
Apply ranks to emp records according to salary descending order with in job:
clear breaks
Syntax:
Row_Number() OVER(PARTITION BY <column> ORDER BY <column>
ASC/DESC)
Examples:
Display all empnos, emp names and salaries.
Apply row numbers to them according to empno ascending order:
power() mod()
sqrt()
abs() ceil() sign() floor()
trunc() round()
power():
• it is used to find power value
power(5,2) 25
sqrt():
• it is used to find square root value
sqrt(25) 5
abs():
• it is used to get absolute value
• absolute value => non-negative value Syntax: abs(<number>) Examples:
abs(25) 25
abs(-25) 25
sign():
• it is used to check whether the given number is +ve or -ve or 0.
sign(-20) -1
sign(0) 0
Mod():
• it is used to get remainder value
Syntax:
Mod(<number>, <divisor>) Examples:
Mod(5,2) 1
Mod(10,7) 3
ceil():
• it is used to get round up value
Syntax: ceil(<number>)
floor():
• it is used to get round down value
Syntax: floor(<number>) Examples:
ceil(456.789) 457
floor(456.789) 456
Trunc():
• it is used to remove the decimal places
Syntax:
Trunc(<number> [, <no_of_decimal_places>]) Examples:
Trunc(123.6789, 1) 123.6
Trunc(123.6789, 2) 123.67
Trunc(123.6789, 3) 123.678
2nd argument can be -ve. if 2nd argument is -ve, it does not give decimal places.
-1 rounds in 10s 10 20 30 40 …. 100, 110, 120, ….
Syntax:
Round(<number> [, <no_of_decimal_places>]) Examples:
TRUNC(123.6789,1) 123.6
ROUND(123.6789,1) 123.7
TRUNC(123.6789,2) 123.67
ROUND(123.6789,2) 123.68
TRUNC(123.6749,2) 123.67
ROUND(123.6749,2) 123.67
2nd argument can be -ve. if 2nd arg is -ve, it does not give decimal places.
-1 rounds in 10s
-2 rounds in 100s
-3 rounds in
1000s
TRUNC(157.6789,- 150
1) and
160
150
USER UID
NVL()
NVL2()
GREATEST()
LEAST()
DECODE()
USER:
• it returns current user name.
NVL():
• NVL() function is used to replace null with other value.
• If arg1 is not null, it returns arg1
• If arg1 is null, it returns arg2
Examples:
NVL(100,200) 100
NVL(null,200) 200
Calculate total salary of all emps:
Assignment:
1001 A 70
1002 B NVL(to_char(m1),'ABSENT')
1003 C 66
1004 D 50
1005 E
1006 F 0
Note:
NVL() can replace nulls only. it cannot replace not nulls.
NVL2():
• NVL2() function can replace nulls and not nulls.
• if arg1 is not null, returns arg2.
• if arg1 is null, it returns arg3.
Syntax:
NVL2(<arg1>, <arg2>, <arg3>)
Examples:
NVL2(100,200,300) 200
NVL2(null,200,300) 300
Differences b/w NVL() and NVL2():
NVL() •it can replace nulls only
•it can take 2 arguments
UPDATE emp
SET comm=NVL2(comm, comm+1000, 800);
Syntax: max(<column>)
Greatest():
• It is used to find max value in horizontal values.
Syntax:
Greatest(<value1>, <v2>, …………)
Examples:
Greatest(10,20,30) 30
Greatest(1,5,9,2,4,3) 9
Example:
T1
max is multi row function
F1 F2 F3
45 78 66
34 29 92 max(f3) => 92
71 50 81
Max() Greatest()
Least():
• it is used to find minimum value in horizontal values.
Syntax:
Least(<value1>, <v2>, ……..)
Examples:
Least(10,20,30) 10
Least(1,6,5,8,7,2,3) 1
T1
F1 F2 F3
45 78 66
34 29 92
71 50 81
min(f3)
T1
Least(f1,f2,f3)
F1 F2 F3
------------------------
45 78 66 45
29
34 29 92
50
71 50 81
DECODE():
• it is used to implement "if" control structure in SQL.
• it can check equality condition only.
Syntax:
DECODE(<column>,
<value1>, <return_expression1>, <value2>, <return_Expression2>,
Example:
SELECT ename,
DECODE(JOB,
'PRESIDENT','BIG BOSS',
'MANAGER', 'BOSS', 'EMPLOYEE') AS job, sal
FROM emp;
String lower() upper() initcap()
Substr() Instr() Lpad()
Rpad()
Ltrim() Rtrim() Trim() length()
concat()
Multi Row
Single Row
Functions
Functions
aggregate functions
String
Number
Analytic
Date
.
.
ENAME LOWER(ENAME)
---------------- ------------------------
SMITH LOWER('SMITH') => smith
ALLEN LOWER('ALLEN') => allen
WARD LOWER('WARD') => ward
SAL MAX(SAL)
--------
5000 9000
9000
8000
CLAUSES:
SQL ENGLISH
QUERIES SENTENCES CLAUSES WORDS
CLAUSE:
• CLAUSE is a part of query.
• Every query is made up of with clauses.
• Every clause has specific purpose.
• SELECT
• FROM
• WHERE
• ORDER BY
• GROUP BY
• HAVING
• OFFSET
• FETCH
• DISTINCT
Display the emp names and salaries of the emps whose salary is more than 2500:
ORDER BY clause:
• It is used to arrange the records in ascending or descending order.
• default order is: ASC
Syntax:
ORDER BY <column> ASC/DESC [, <column> ASC/DESC, …]
Example:
ORDER BY sal DESC
Display all emp names and salaries. arrange them in descending order
according to salary:
Display all emp names and salaries. arrange them in alphabetical order
according to emp names:
CASE-1: deptnos are different if deptnos are different it will not check salary
20 10
10 20
CASE-2: deptnos are same if deptnos are same then only it checks salary
10 3000 10 4000
10 4000 10 3000
GROUP BY clause:
• It is used to group the records according to specific column or columns.
• On group of records we apply aggregate function.
• It is used to get summarized data from detailed data.
• It can be used for data analysis.
1004 D 10000 30
1005 E 30000 10
1005 F 20000 10
Examples on GROUP BY:
10 ?
20 ?
30 ?
SELECT deptno, sum(sal) AS sum_of_sal
FROM emp
GROUP BY deptno
ORDER BY deptno ASC;
10 ? ?
20 ? ?
30 ? ?
SELECT deptno, max(Sal) AS max_sal, min(Sal) AS min_sal
FROM emp
GROUP BY deptno ORDER BY 1;
10 ?
20 ?
30 ?
SELECT deptno, avg(sal) AS avrg_sal
FROM emp
GROUP BY deptno ORDER BY 1;
10 ?
30 ?
SELECT deptno, count(*) AS no_of_emps
FROM emp
GROUP BY deptno ORDER BY 1;
• FROM
• WHERE
• GROUP BY
• HAVING
• SELECT
• DISTINCT
• ORDER BY
• OFFSET
• FETCH
Find dept wise sum of salaries. find it for deptno 10 and 20 only:
DEPTNO SUM_OF_SAL
10 ?
20 ?
SELECT deptno, sum(sal) AS sum_of_sal
FROM emp
WHERE deptno IN(10,20)
GROUP BY deptno
ORDER BY deptno ASC;
EMP
EMPNO ENAME SAL DEPTNO
1001 A 10000 20
1002 B 20000 20
1003 C 5000 30
1004 D 10000 30
1005 E 30000 10
1005 F 20000 10
FROM emp:
it selects entire table
EMP
1001 A 10000 20
1002 B 20000 20
1003 C 5000 30
1004 D 10000 30
1005 E 30000 10
1005 F 20000 10
WHERE deptno IN(10,20): it filters the rows
EMPNO ENAME SAL DEPTNO
1001 A 10000 20
1002 B 20000 20
1005 E 30000 10
1005 F 20000 10
GROUP BY deptno:
it groups the records according to specific column.
on these groups aggregate function will be applied,
1002 B 20000 20
1005 E 30000 10
20 30000
10 50000
ORDER BY deptno ASC:
it arranges result in the specified order
DEPTNO SUM_OF_SAL
10 50000
20 30000
Find year wise no of emps joined in organization:
YEAR NO_OF_EMPS
1981 ?
1982 ?
1983 ?
SELECT to_char(hiredate,'YYYY') AS year, count(*) AS no_of_emps FROM emp
GROUP BY to_char(hiredate,'YYYY') ORDER BY 1 ASC;
1 ?
2 ?
3 ?
4 ?
SELECT to_char(hiredate,'Q') AS QUARTER, count(*) AS no_of_emps
FROM emp
GROUP BY to_char(hiredate,'Q') ORDER BY 1;
CLERK ?
MANAGER ?
ANALYST ?
SALESMAN ?
PRESIDENT ?
SELECT job, sum(Sal) AS sum_of_sal
FROM emp
GROUP BY job;
Assignment:
Find job wise max sal and min sal
10 MANAGER ?
10 CLERK ?
20 MANAGER ?
20 CLERK ?
SELECT deptno, job, count(*) AS no_of_emps
FROM emp
GROUP BY deptno, job ORDER BY 1;
Rollup():
Syntax:
GROUP BY Rollup(<grouping_columns_list>)
Example:
GROUP BY Rollup(deptno, job) it calculates dept wise sub totals and grand total
Syntax:
GROUP BY Cube(<grouping_columns_list>)
Example:
GROUP BY Cube(deptno, job)
it calculates dept wise sub totals, job wise sub totals and grand total
MANAGER ?
20 CLERK ?
20 MANAGER ?
GRAND TOTAL ?
10 CLERK ?
MANAGER ?
20 CLERK ?
20 MANAGER ?
CLERK subtotal ?
GRAND TOTAL ?
1980 1 ?
2 ?
4 ?
1981 1 ?
2 ?
3 ?
4 ?
Find year wise, quarter wise no of emps. calculate sub totals according to year.
[Rollup()]
YEAR QUARTER NO_OF_EMPS
1980 1 ?
2 ?
3 ?
4 ?
1981 1 ?
2 ?
3 ?
4 ?
GRAND TOTAL ?
1980 1 ?
2 ?
3 ?
4 ?
1981 1 ?
2 ?
3 ?
4 ?
GRAND TOTAL ?
Assignment:
SALES
DATEID AMOUNT
1-JAN-2020 50000
2-JAN-2020 70000
..
15-JUN-2024 80000
calculate year wise, quarter wise sales:
2 ?
3 ?
4 ?
2021 1 ?
2 ?
3 ?
calculate year wise, quarter wise sales.
4 ? Also calculate sub totals according to year.
2020 1 ?
2 ?
3 ?
4 ?
2021 1 ?
2 ?
3 ?
4 ?
GRAND TOTAL ?
3 ?
4 ?
2021 1 ?
2 ?
3 ?
4 ?
GRAND TOTAL ?
HAVING:
• HAVING clause is used to write the condition on groups.
• This condition will be applied on result of GROUP BY.
• It cannot be used without GROUP BY.
Syntax:
HAVING <condition>
Display the depts which are spending more than 10000 rupees on their emps:
WHERE HAVING
OFFSET:
• introduced in ORACLE 12C version.
• OFFSET clause is used to specify no of rows to be skipped.
Syntax:
OFFSET <number> ROW/ROWS
FETCH:
• introduced in ORACLE 12C version.
• FETCH clause is used to specify no of rows to be displayed.
Syntax:
FETCH FIRST/NEXT <number> ROW/ROWS ONLY
DISTINCT:
• It is used to eliminate the duplicate records.
Syntax:
SELECT DISTINCT <columns_list>
Examples:
DEPTNO
SELECT DISTINCT deptno FROM emp
---------------
ORDER BY deptno;
20
30
DEPTNO
30
-------------
10
10
20
20
20
30
10 10
30
JOB
--------
JOB MANAGER
---------
CLERK
MANAGER
CLERK
CLERK
MANAGER
SALESMAN
SALESMAN
SALESMAN
MANAGER
CLERK
20 ANALYST
10 CLERK
20 ANALYST
20 ANALYST
20 CLERK
20 CLERK
20 CLERK
10 CLERK
10 CLERK
Execution Order:
WHERE job='MANAGER'
WHERE deptno=30
WHERE sal>2500
Note:
We cannot use column aliases in GROUP BY, HAVING and WHERE. Because, all these 3 gets executed before
SELECT.
Can we use column alias in ORDER BY?
Yes.
because of execution order of clauses.
ORDER BY gets executed after SELECT.
NOTE:
JOINS:
GOAL:
JOINS concept is used to retrieve the data from multiple tables.
Example:
COLLEGE DB
STUDENT
MARKS
FEE
EMP
STUDENT S MARKS M
SID SNAME SCITY SID MATHS PHY CHE
1001 A HYD 1001 70 50 65
1002 B MUM 1002 66 77 45
1003 C BLR 1003 88 90 60
1004 D HYD
JOINS
JOINS:
• JOIN is an operation like filtering, sorting.
• In JOIN Operation one table record will be combined with another table record based on some condition. This condition is called "Join
Condition".
• JOIN CONDITION decides which record in one table should be joined with which record in another table.
Types of Joins:
Equi Join:
• If Join Operation is performed based on equality condition then it is called "Equi Join".
Examples:
WHERE S.SID = M.SID
STUDENT.SID = MARKS.SID
STUDENT S
SID SNAME SCITY MARKS M
SID MATHS PHY CHE
1001 A HYD
Display 1001 70 50 65 student details along with maths subject marks:
1002 B MUM
SID SNAME MATHS
1002 66 77 45
1003 C BLR STUDENT S MARKS M
1003 88 90 60
1004 D HYD
Above query degrades the performance. TO improve the performance of above query prefix every column name with table
name.
above query improves the performance. To make table name short use table alias.
NOTE:
• From ORACLE 9i version onwards, we can write a join query in 2 styles.
They are:
○ ORACLE STYLE / NATIVE STYLE
○ ANSI STYLE => best way => portable
we can run
portability
JOIN QUERY JOIN QUERY
[ ANSI STYLE ] [ ANSI STYLE ]
NOTE:
• In ORACLE STYLE, to separate 2 table names we use , [comma].
• In ANSI STYLE, to separate 2 table names we use keyword.
• In ORACLE STYLE, we write join condition in WHERE clause.
• In ANSI STYLE, we write join condition in ON clause.
Example:
e.deptno = d.deptno
ORACLE STYLE:
NEW YORK
NOTE:
• ON clause is used to specify Join Condition.
• WHERE clause is used to specify filter condition.
e.deptno=d.deptno
EMP e DEPT d
EMPNO ENAME SAL DEPTNO DEPTNO DNAME LOC
7369 SMITH 800 20 10 ACCOUNTS NEW YORK
7499 ALLEN 1600 30 20 RESEARCH DALLAS
7521 WARD 1250 30 30 SALES CHICAGO
7566 JONES 2975 20 40 OPERATIONS BOSTON
7782 CLARK 2450 10
7934 MILLER 1300 10
1001 A 1800
1002 B 2000
SALES
EMP DEPT
EMPNO ENAME SAL DEPTNO DEPTNO DNAME LOC
7369 SMITH 800 20 10 ACCOUNTS NEW YORK
7499 ALLEN 1600 30 20 RESEARCH DALLAS
7521 WARD 1250 30 30 SALES CHICAGO
7566 JONES 2975 20 40 OPERATIONS BOSTON
7782 CLARK 2450 10
7934 MILLER 1300 10
1001 A 1800
1002 B 2000
ALLEN
EMP e DEPT d
ORACLE STYLE:
Example:
WHERE e.deptno = d.deptno
Non-Equi Join:
• If Join operation is performed based on other than equality condition then it is called "Non-Equi Join".
Examples:
Example:
WHERE e.deptno > d.deptno
WHERE e.deptno < d.deptno
WHERE e.deptno != d.deptno
ORACLE STYLE:
• Outer Join can give matched records and unmatched records also.
• Inner Join = matched records
• Outer Join = matched + unmatched records
Note:
• In ORACLE STYLE, based on join condition we can tell left table and right table.
Examples:
WHERE e.deptno = d.deptno
emp e left table
Examples:
FROM emp e JOIN dept d
emp e Left table
• Left Outer Join can give matched records and unmatched records from left table.
• In ORACLE STYLE, for left outer join write (+) symbol at right side.
• Right Outer Join can give matched records and unmatched records from right table.
ORACLE STYLE:
• Full Outer Join = matched + unmatched from left and right tables
• Full Outer Join can give matched records, unmatched records from left table and
right table.
In ORACLE STYLE:
A = {1,2,3,4,5} B = {4,5,6,7,8}
Left Outer Join WHERE e.deptno = d.deptno(+)
ORACLE STYLE:
Left Outer Join + Condition = unmatched records from left table Example:
A ..
B ..
ORACLE STYLE:
Right Outer Join + Condition = unmatched records from right table Example:
OPERATIONS BOSTON
ORACLE STYLE:
Full Outer Join + Conditions = unmatched from left + unmatched from right Example:
A ..
B ..
OPERATIONS BOSTON
ORACLE STYLE:
• In Self Join, one record in a table will be joined with another record in same table.
Example:
e.mgr = m.empno
EMP e EMP m
EMPNO ENAME JOB SAL MGR EMPNO ENAME JOB SAL MGR
1002 B CLERK 10000 1001 1002 B CLERK 10000 1001 1003 C ANALYST 8000 1001 1003 C ANALYST 8000 1001 1004 D MANAGER
Display the emp records who are earning more than their manager:
ORACLE STYLE:
ORACLE STYLE:
GROUPA x GROUPA y
CID CNAME CID CNAME
10 IND 10 IND
20 AUS 20 AUS
30 WIN 30 WIN
20 AUS 20 AUS
30 WIN 30 WIN
IND VS AUS
IND VS WIN AUS VS WIN
insert into groupa values(10,'IND'); insert into groupa values(20,'AUS'); insert into groupa values(30,'WIN'); commit;
ORACLE STYLE:
A = {1,2,3}
B = {4,5}
AXB = { (1,4)(1,5) (2,4) (2,5) (3,4) (3,5) }
A B
1
4
2
5
3
• In Cross Join, each record in one table will be joined with every record in another table.
10 IND 40 ENG
20 AUS 50 SL
30 WIN 60 NZ
create table groupa
(
cid number(2), cname varchar2(10)
);
insert into groupa values(10,'IND'); insert into groupa values(20,'AUS'); insert into groupa values(30,'WIN'); commit;
insert into groupb values(40,'ENG'); insert into groupb values(50,'SL'); insert into groupb values(60,'NZ'); commit; CROSS JOIN:
ORACLE STYLE:
IND VS ENG
IND VS SL
IND VS NZ
AUS VS ENG
AUS VS SL
AUS VS NZ
WIN VS ENG
WIN VS SL
WIN VS NZ
JOINS:
• used to retrieve the data from multiple tables
Types Of Joins:
Inner Join matched records only
Equi based on =
location1
ORACLE STYLE:
EMP DEPT
1001 A 1800
1002 B 2000
ORACLE 2PM KPHB MAY 2024 Page 209
Assignment
Wednesday, May 29, 2024 7:18 PM
Assignment:
EMPLOYEE e PROJECT p
display the employees who are on bench. display the projects which are
not assigned to any employee
empid ename pname
full outer join + conditions
Display emp details along with project details. also display the employees
who are on bench. also display the projects which are not assigned to any
employee
empid ename pname
full outer join
ORACLE 2PM KPHB MAY 2024 Page 211
SUB QUERIES
Friday, June 21, 2024 2:31 PM
SELECT <columns_list>
FROM <table_name>
WHERE <column_name> <operator> (< SELECT QUERY >) ;
• When we don't know filter condition value, to find it we write Sub Query.
• First Inner query gets executed. Then outer query gets executed. Result of
inner query will become input for Outer query.
2 types:
• Non-Correlated Sub Query INNER => OUTER
○ Single Row Sub Query
○ Multi Row Sub Query
○ Inline View / Inline Sub Query
○ Scalar Sub Query
• Correlated Sub Query OUTER => INNER
<=
Display the emp records who are earning more than BLAKE:
salary:
SELECT max(Sal)
FROM emp
WHERE sal<(SELECT max(Sal) FROM emp);
SAL
--------- SELECT max(sal) FROM emp
3000 WHERE sal<(find 2nd max sal);
2500 6000
4000max sal => 4000
3000
50003rd max sal
2500
4000
SELECT ename
FROM emp
WHERE sal=(find max sal);
SELECT ename
FROM emp
WHERE sal=(SELECT max(sal) FROM emp);
SELECT ename
FROM emp
WHERE sal=(find 2nd max sal);
SELECT ename
FROM emp
WHERE sal=(SELECT max(sal) FROM emp
WHERE sal<(SELECT max(sal) FROM emp));
Assignment:
• find the emp name who is earning 3rd max sal
• find the emp name who is earning min sal
SELECT deptno
FROM emp
GROUP BY deptno
HAVING sum(Sal)=(find max amount in all depts sum of salaries);
SELECT deptno
FROM emp
GROUP BY deptno
HAVING sum(Sal)=(SELECT max(sum(sal)) FROM emp
GROUP BY deptno);
Find the dept name which is spending max amount on their emps:
UPDATE emp
SET sal=(find 30th dept's max sal) WHERE
empno=7900;
UPDATE emp
SET sal=(SELECT max(sal) FROM emp WHERE deptno=30) WHERE empno=7900;
• For multi row sub query we use operators such as IN, ANY, ALL.
find BLAKE and SMITH job titles: SELECT job FROM emp
WHERE ename IN('BLAKE','SMITH');
ALL:
Syntax:
<column> <relational_operator>ALL(<values_list>)
sal>2000 AND sal>3000 sal>ALL(2000,3000)
ANY:
Syntax:
<column> <relational_operator>ANY(<values_list>)
2500 F T
5000 T T
2800 F T
1000 F F
(or)
Display the emp records who are earning more than any one of the managers:
ROWNUM ROWID
ROWNUM:
• It is a pseudo column.
• It is used to apply row numbers to records.
• On select query result row numbers will be applied.
Examples on rownum:
SELECT *
FROM (SELECT rownum as rn, empno, ename, sal
FROM emp)
WHERE rn=3;
Display 3rd row, 7th row and 11th row from emp table:
SELECT *
FROM (SELECT rownum as rn, empno, ename, sal
FROM emp)
WHERE rn IN(3,7,11);
SELECT *
FROM (SELECT rownum as rn, empno, ename, sal
FROM emp)
WHERE rn BETWEEN 6 AND 10;
SELECT *
FROM (SELECT rownum as rn, empno, ename, sal
FROM emp)
WHERE MOD(rn,2)=0;
ROWID:
• it is used to get address of the row.
Example:
EMPLOYEE
EMPID ENAME SAL ROWID
Output:
Execution process:
1. Outer query gets executed. it selects a row.
2. Outer query passes value to inner query.
3. Inner query gets executed.
4. Inner query passes value to Outer query.
5. Outer query condition will be tested. If condition is TRUE selects the row.
Above 5 steps will be executed repeatedly for every row selected by outer query.
selects a row 3
2 passes value
OUTER INNER
4 passes value
A 10 20000
C 30 15000
E 20 40000
Example:
Find the emps who are earning max sal in each dept:
min hiredate
EXISTS:
• it returns boolean value [true or false].
DEPT d EMP e
1004 D 10 10000
ACCOUNTS
1005 E 20 40000
RESEARCH SALES
1006 F 30 5000
Syntax:
NOT EXISTS(<sub query>)
2 Types:
SELECT unlimited
0 TO 100
1001 A 56
CONSTRAINTS:
• Constraint is a rule that is applied on column.
• Constraint => restrict
• CONSTRAINT is used to restrict the user from entering invalid data.
• Using CONSTRAINT, we can maintain accurate and quality data.
• Maintaining accurate and quality data is called "Data Integrity".
• To implement data integrity feature we use CONSTRAINTS.
PRIMARY KEY:
EMPLOYEE
PK
EMPID ENAME JOB SAL
T1
PK
F1
------
1234
1235
CREATE TABLE t1
(
f1 NUMBER(4) PRIMARY KEY
);
Example:
CUSTOMER
UNIQUE
CID CNAME MOBILE_NUMBER
1234 A 9123456789
1235 B
1236 C 8987654321
1237 D
NOT NULL:
• It does not accept nulls.
• It accepts duplicates.
• When value is MANDATORY and it can be duplicated then use NOT NULL.
Example:
EMPLOYEE
NOT NULL
EMPNO ENAME SAL
1234 A 6000
1235 B 8000
1236 B 7000
PRIMARY KEY NO NO
UNIQUE NO YES
PK = no dups + no nulls
Example:
STUDENT CHECK(gender IN('M','F'))
SID SNAME GENDER
1001 ABC M
1002 XYZ F
1003 AA Z ERROR
Default:
• To apply default value to column we use DEFAULT.
Example:
STUDENT
DEFAULT 'NARESH' DEFAULT 'HYD' DEFAULT 20000
SID SNAME CNAME CCITY FEE
Example:
COURSE STUDENT FK
PK REFERENCES COURSE(CID)
CID CNAME SID SNAME CID
10 JAVA 1234 A 20
20 PYTHON 1235 B 10
30 HTML 1236 C 10
1237 D
1238 E 90 ERROR
STUDENT
SID SNAME M1
SID don't PK
accept
dups
and
nulls
SNAME don't NOT
accept NULL
nulls
m1 b/w 0 CHECK
to 100
CREATE TABLE student
(
sid NUMBER(4) PRIMARY KEY, sname VARCHAR2(10) NOT NULL,
m1 NUMBER(3) CHECK(m1 BETWEEN 0 AND 100)
);
Example:
USERS_LIST
USERID UNAME PWD
Example:
EMPLOYEE11
Example:
DEPT1 EMPLOYEE1
PK [parent key] FK [child key]
DEPTNO DNAME REFERENCES dept1(Deptno)
10 HR EMPNO ENAME DEPTNO
20 SALES 1001 A 30
30 ACCOUNTS 1002 B 30
1003 C 10
master table / 1004 D 10
parent table
1005 E
1006 F 80 ERROR
detailed table /
DEPT1 child table
PK
DEPTNO DNAME
EMPLOYEE1
FK
PK REFERENCES dept1(Deptno)
EMPNO ENAME DEPTNO
CREATE TABLE employee1
(
empno NUMBER(4) PRIMARY KEY, ename VARCHAR2(10),
deptno NUMBER(2) REFERENCES dept1(deptno)
);
Naming Constraints:
• We can give names to constraints.
• To identify constraint uniquely in database we use constraint name.
• When we define constraint it's better to give constraint name. If we don't
give constraint name implicitly ORACLE defines a constraint name.
• ORACLE DEFINED NAME IS: a six digit random number will be prefixed with
SYS_C Example: SYS_C002748
STUDENT1
SID SNAME M1
don’t
accept
dups and
SID nulls PK c1
M1 0 t0 100 CHECK c2
CREATE TABLE student1
(
sid NUMBER(4) CONSTRAINT c1 PRIMARY KEY, sname VARCHAR2(10),
Note:
• We cannot give constraint name to DEFAULT constraint.
Example:
STUDENT2
SID SNAME M1
PK CHECK
Example:
STUDENT3
SID SNAME M1
PK CHECK
CREATE TABLE student3
(
sid NUMBER(4), sname
VARCHAR2(10), m1 NUMBER(3),
CONSTRAINT c5 PRIMARY KEY(sid),
CONSTRAINT c6 CHECK(m1 BETWEEN 0 AND 100)
);
Note:
Example:
COURSE1 STUDENT1
PK (c10) FK (c11)
CID CNAME references course1(Cid)
SID SNAME CID
10 JAVA
20 C# 1001 A 20
2 reasons:
STUDENT
PK(SID, SUBJECT) => composite primary key
SID SNAME SUBJECT MARKS
1001 A M1 70
1001 A M2 66
1001 A M3 70
1002 B M1 66
1002 B M2 50
1002 B M3 80
1001 M1 ERROR: duplicate
null ERROR
null ERROR
Composite primary key:
• If we set combination of columns as PK then it is called "Composite
Primary Key".
• It can be applied at table level only.
STUDENT
PK(SID, SUBJECT) => composite primary key
SID SNAME SUBJECT MARKS
CREATE TABLE student
(
sid NUMBER(4), sname
VARCHAR2(10), subject CHAR(2),
marks NUMBER(3),
CONSTRAINT c20 PRIMARY KEY(sid, subject)
);
PRODUCTS
PID PNAME MANUFACTURED_DATE EXPIRY_DATE
1001 A 27-JUN-24 25-DEC-23 ERROR
CREATE TABLE products
(
pid NUMBER(4), pname
VARCHAR2(10), manufactured_date
DATE,
expiry_date DATE,
CONSTRAINT c21 CHECK(expiry_Date>manufactured_date)
);
ALTER:
Syntax:
Example:
STUDENT
SID SNAME M1
CREATE TABLE student
(
sid NUMBER(4), sname
VARCHAR2(10), m1
NUMBER(3)
);
Note:
Add PK to sid:
ALTER TABLE student ADD CONSTRAINT c30 PRIMARY KEY(sid);
(or)
ALTER TABLE student MODIFY sid CONSTRAINT c30 PRIMARY KEY;
user_constraints:
• it is a system table / built-in table / readymade table. • It maintains all
format a15
SET OPERATORS
Thursday, June 27, 2024 3:29 PM
A = {1,2,3,4,5}
B = {4,5,6,7,8}
A U B = {1,2,3,4,5,6,7,8} = B U A
A UA B = {1,2,3,4,5,4,5,6,7,8} = B UA A
A I B = {4,5} = B I A
SET OPERATORS:
Syntax:
<SELECT QUERY>
<SET OPERATOR>
<SELECT QUERY>;
UNION:
It combines result of 2 select queries without duplicates.
UNION ALL:
It combines result of 2 select queries including duplicates.
INTERSECT:
It gives common records from result of 2 select queries.
MINUS:
It gives specific records from first select query result.
Example:
CRICKET FOOTBALL
Example:
SELECT sid FROM cricket
UNION
SELECT sid, sname FROM football; Output:
ERROR
Example:
deptno 10 deptno 20
deptno 10 deptno 20
CLERK CLERK
MANAGER MANAGER
PRESIDENT ANALYST
Display the job titles offered by 10 and 20 depts:
CLERK
MANAGER
PRESIDENT ANALYST
CLERK
MANAGER
Display the job titles offered by deptno 10 only and those should not be
offered by deptno 20:
PRESIDENT
Display the job titles offered by deptno 20 only and those should not be
offered by deptno 10:
ANALYST
Example:
EMP_IND EMP_US
5002 D
Differences b/w Joins and UNION:
JOINS •combines the columns
•it is used for vertical merging
•it is applied on dissimilar structures
UNION •combines the rows
•it is used for horizontal merging
•it is applied on similar structures
EMP DEPT
EMPNO ENAME DEPTNO DEPTNO DNAME
ENAME DNAME
JOINS
EMP_IND EMP_US
EMPID ENAME EMPID ENAME
1001 A 5001 C
1002 B 5002 D
UNION
EMPID ENAME
1001 A
1002 B
5001 C
5002 D
TABLES
alter merge
drop
flashback
purge
truncate
rename
Built-In Functions:
Clauses:
FROM emp
WHERE sal>3000
GROUP BY deptno
HAVING count(*)>5
SELECT ename, sal
DISTINCT job
ORDER BY sal DESC
OFFSET 4 ROWS
FETCH FIRST 4 row only
Joins:
Outer Join
Left outer = matched + um from L
Right outer = matched + um from R
Full outer = matched + um from L & R
Sub Queries:
2 types:
Constraints:
PK
UNIQUE
SET OPERATORS:
UNION
UNION ALL
INTERSECT
MINUS