Notes Link: Akhil (Admin) Mobile: 9154156192 (Only Whatsapp)
Notes Link: Akhil (Admin) Mobile: 9154156192 (Only Whatsapp)
ORACLE_6PM_APR_2024 Page 1
ORACLE
Thursday, April 18, 2024 6:18 PM
Data Store:
• The location where data is stored
• Examples: BOOK, FILE, DATABASE
Before 1960s
BANK business data in books
ORACLE_6PM_APR_2024 Page 2
In Java:
x => variable
int x=25;
25
1001 RAJU
File Database
• no security • security
BANK DB COLLEGE DB
Branches Courses
Customers Students
Transactions Fee
ORACLE_6PM_APR_2024 Page 3
Branches Courses
Customers Students
Transactions Fee
Products Marks
Employees Library
. .
. .
DB SERVER
searching for products
adding to wishlist
amazon DB
placing order
online payment
products
wishlists
customers
orders
payments
interrelated =>
BANK DB contains BANK related data only
It does not contain COLLEGE related data.
organized =>
arranging in specific way
DBMS:
• DataBase Management System/Software
DBMS
H DBMS => nodes
RDBMS: N DBMS => nodes
R DBMS => tables
• RDBMS is a kind of DBMS.
BANK DB
ORACLE_6PM_APR_2024 Page 5
BANK DB
BRANCHES Table
IFSC_CODE CITY STATE COUNTRY
CUSTOMERS Table
CUSTID CNAME CCITY MOBILE AADHAR PAN IFSC_CODE
TRANSACTIONS table
T_ID T_DATE_TIME T_TYPE ACNO AMOUNT CID
.
.
• Examples:
ORACLE, SQL SERVER, DB2, MY SQL, POSTGRE SQL
TABLE:
• table is a collection of columns and rows.
• A Table can be also called as Relation / Entity
Example:
ORACLE_6PM_APR_2024 Page 6
Column:
Vertical representation of data is called "Column"
Row:
Horizontal representation of data is called "Row".
Metadata:
• Metadata is the data about the data.
• It can be also called as Data Definition.
Examples:
Field names => sid, sname, fee
Table name => student
Example:
STUDENT
SID SNAME FEE
1001 Kiran 6000
ORACLE_6PM_APR_2024 Page 7
Thursday, April 18, 2024 7:03 PM
BANK DB
BRANCHES
IFSC_CODE CITY STATE COUNTRY
CUSTOMERS
CUSTID CNAME CCITY MOBILE AADHAR PAN IFSC_CODE
TRANSACTIONS
T_ID T_DATE_TIME T_TYPE ACNO AMOUNT CID
.
.
ORACLE_6PM_APR_2024 Page 8
ORACLE
Friday, April 19, 2024 6:41 PM
ORACLE:
checking balance
transactions statement
searching for products
SQL:
• SQL => Structured Query Language
• It is a Query Language
• It is used to write the queries C, Java, C#:
PL/SQL:
• PL => Procedural Language
• SQL => Structured Query Language
• It is a Programming Language.
ORACLE_6PM_APR_2024 Page 10
• PL/SQL = SQL + Programming
ORACLE_6PM_APR_2024 Page 11
Saturday, April 20, 2024 6:16 PM
In C:
SQL: Function:
• SQL => Structured Query Language. is a set of statements
STUDENT COURSE
ORACLE_6PM_APR_2024 Page 12
• SQL provides JOINS concept to retrieve data from multiple
tables.
STUDENT COURSE
SID SNAME CID CID CNAME
1001 A 30 10 JAVA
1002 B 10 20 PYTHON
1003 C 10 30 C#
1004 D 20
JOINS
SNAME CNAME
student course
• DDL
• DRL / DQL
• DML
• TCL
• DCL / ACL
DDL: create
• Data Definition Language alter
• Data Definition => metadata
drop
• it deals with metadata flashback [oracle 10g]
purge [oracle 10g]
truncate
rename
ORACLE_6PM_APR_2024 Page 13
• Data Retrieval Language
• Data Query Language
DML insert
• Data Manipulation Language update
delete
• manipulation => 3 actions
insert/update/delete insert all [oracle 9i]
merge [oracle 9i]
TCL: commit
• Transaction Control Language rollback
savepoint
• It deals with transactions
DDL:
create
alter
drop
flashback
purge
truncate
rename
alter:
• alter => change
• used to change structure of the table.
• using this, we can add the columns. rename the
columns or drop the columns.
drop
flashback [oracle 10g]
purge [oracle 10g]
RECYCLEBIN
drop
EMPLOYEE employee
EMPNO ENAME SAL
truncate:
EMPLOYEE
EMPNO ENAME SAL structure [columns]
1001 A 6000
1002 B 5000 data [rows]
1003 C 8000
rename:
ORACLE_6PM_APR_2024 Page 15
rename:
to change table name we use it
ORACLE_6PM_APR_2024 Page 16
SYLLABUS
Monday, April 22, 2024 6:14 PM
ORACLE
SQL
1 SQL Commands DDL, DRL, DML, TCL, DCL
2 Built-In Functions
3 CLAUSES GROUP BY, HAVING
4 JOINS
TABLES
5 SUB QUERIES
6 CONSTRAINTS
7 VIEWS
8 INDEXES
9 SEQUENCES
10 SYNONYMS
11 MATERIALIZED
VIEWS
PL/SQL
PL/SQL Basics data types, declare, assign, print, read
Control Structures
CURSORS
COLLECTIONS
EXCEPTION HANDLING
STORED PROCEDURES
STORED FUNCTIONS
PACKAGES
TRIGGERS
ORACLE_6PM_APR_2024 Page 17
TRIGGERS
WORKING WITH LOBs
DYNAMIC SQL
ORACLE_6PM_APR_2024 Page 18
SQL
Monday, April 22, 2024 6:26 PM
DDL:
CREATE:
used to create the tables.
Syntax:
ORACLE_6PM_APR_2024 Page 19
Binary Related BFILE
BLOB
Examples:
images, audios, videos,
documents … etc
Char(n):
• n => max no of chars
• it is used to hold string values.
• It is Fixed Length Data Type.
• max size: 2000 Bytes [2000 chars]
• default size: 1
• to hold fixed length chars use "CHAR"
Varchar2(n):
• n => max no of chars
• it is used to hold string values.
• It is Variable Length Data Type.
• max size: 4000 Bytes [4000 chars]
• default size: no default size
• to hold variable length chars use "VARCHAR2".
Note:
All Character related data types can accept
letters, digits and special chars.
LONG:
• is used to hold large amounts of chars
• LONG data type has some restrictions:
○ a table can have only one column as LONG type
○ we cannot use built-in functions on LONG type
max size: 2GB
ORACLE_6PM_APR_2024 Page 20
• max size: 2GB
CLOB:
• CLOB => Character Large Object
• is used to hold large amounts of chars
• A table can have any number of columns as CLOB type.
• We can use built-in functions on CLOB type
• max size: 4 GB
Examples:
feedback CLOB
complaints CLOB
product_features CLOB
NUMBER(p):
• is used to hold integers.
• p => precision => max no of digits
• p valid range => 1 to 38
Examples:
ORACLE_6PM_APR_2024 Page 21
1236
5678
67
9999
10000 => ERROR
Aadhar_number NUMBER(12)
Mobile_number NUMBER(10)
Credit_Card_number NUMBER(16)
Note:
What are the differences between Number(38), integer
and int?
NUMBER(p,s):
○ It is used to hold floating point values.
○ p => precision => max no of digits
○ s => scale => max no of decimal places
Example:
100.00
s=2
p=5
ORACLE_6PM_APR_2024 Page 22
123.453789 => 123.45
max sal:
00000.00
height NUMBER(2,1)
-9.9 TO 9.9
-----------
5.3
5.0
5.8
5.9
Date:
• it is used to hold date values.
• it can hold date, month, year, hours, minutes and
seconds.
• default date format is: 'DD-MON-YY'
• Example: 23-APR-24
• date also contains time value. But, by default it will not
be displayed.
• default time: 12:00:00 AM [mid night time]
• it is fixed length data type
• size: 7 Bytes
Examples:
Transaction_date DATE
date_of_birth DATE
ordered_date DATE
Timestamp:
• Introduced in ORACLE 9i
• Used to hold date and time values.
• it can hold date, month, year, hours, minutes, seconds
and fractional seconds.
• it is fixed length data type.
• size: 11 Bytes
• default time: 12:00:0.0 AM [mid night time]
• format: DD-MON-YY HH:MI:SS.FF AM
Examples:
Transaction_date_time TIMESTAMP
ordered_date_time TIMESTAMP
delivered_date_time TIMESTAMP
login_date_time TIMESTAMP
ORACLE_6PM_APR_2024 Page 23
DATE TIMESTAMP
Example: Example:
transaction_date DATE trans_date_time TIMESTAMP
ORACLE_6PM_APR_2024 Page 24
Monday, April 22, 2024 7:07 PM
ORACLE_6PM_APR_2024 Page 25
Wednesday, April 24, 2024 6:42 PM
ORACLE DB SERVER
Client
ORACLE
SQL PLUS / request
SQL DEVELOPER / INSTANCE DB
TOAD
response query custs
execution trans
branches
runs services
RAM Hard Disk
Note:
When we install ORACLE software, along with it
also installs SQL PLUS.
Creating User:
Note:
DBA creates the user
Login as DBA:
username: system
password: naresh
Output:
user created.
Output:
Grant Succeeded
to clear screen:
SQL> cl scr
Note:
CL[EAR] SCR[EEN]
Syntax:
conn[ect] <username>/<password>
Example:
SQL> conn c##batch6pm/nareshit
Syntax:
ORACLE_6PM_APR_2024 Page 28
Syntax:
Example:
ALTER USER c##batch6pm
IDENTIFIED BY naresh;
Dropping User:
Syntax:
Example:
DROP USER c##abcd CASCADE;
ORACLE_6PM_APR_2024 Page 29
Wednesday, April 24, 2024 7:45 PM
Creating user:
username: c##abcd
password: abcd
ORACLE_6PM_APR_2024 Page 30
Thursday, April 25, 2024 6:39 PM
SQL Commands:
truncate
rename
CREATE:
• it is DDL command.
• it is used to create the tables.
INSERT:
• it is DML command.
• it is used to insert the records.
Syntax:
Note:
SQL is not case sensitive language
select = SELECT = SELecT
STUDENT
SID SNAME AVRG
1001 AA 67.89
1002 ABC 56.23
SID NUMBER(4)
SNAME VARCHAR2(10)
AVRG NUMBER(5,2)
creating table:
ORACLE_6PM_APR_2024 Page 32
creating table:
inserting records:
1001 AA 67.89
1002 ABC 56.23
Example:
INSERT INTO student VALUES(&sid,'&sname',&avrg);
Output:
enter value for sid: 1003
enter value for sname: XYZ
enter value for avrg: 78.54
INSERT INTO student VALUES(&sid,'&sname',&avrg)
INSERT INTO student VALUES(1003,'XYZ',78.54)
1 row created
/
Output:
enter value for sid: 1004
enter value for sname: A
enter value for avrg: 55.66
/
Output:
enter value for sid: 1005
enter value for sname: B
enter value for avrg: 44.45
Note:
/ is used to run recent command in memory
it means, / runs above query [recent query]
/ R[UN]
ORACLE_6PM_APR_2024 Page 34
INSERT INTO student VALUES(&sid,&sname,&avrg);
Output:
…..
…enter value for sname: 'RAJU'
STUDENT
SID SNAME AVRG
2001 AA
STUDENT
SID SNAME AVRG
2002 52.82
STUDENT
SID SNAME AVRG
2003 XYZ
ORACLE_6PM_APR_2024 Page 35
Example-2:
EMPLOYEE
EMPNO ENAME STATE SAL DOJ 100000.00
1234 ABC TS 12000 25-DEC-23
1235 AB AP 15000 17-AUG-21
empno NUMBER(4)
ename VARCHAR2(10)
state CHAR(2)
sal NUMBER(8,2)
doj DATE
creating table:
EMPLOYEE
EMPNO ENAME STATE SAL DOJ
DOJ DATE
INSERT INTO employee
---------
VALUES(1234,'ABC','TS',12000,'25-DEC-2023');
25-DEC-23 DATE
string
INSERT INTO employee
VALUES(1235,'AB','AP',15000,'17-AUG-2021');
ORACLE_6PM_APR_2024 Page 36
25-DEC-23 DATE
string
INSERT INTO employee
VALUES(1235,'AB','AP',15000,'17-AUG-2021');
implicit conversion
COMMIT;
Note:
• implicit conversion degrades the performance.
• to improve performance, do explicit conversion.
• for explicit conversion we use Built-In Functions.
to_date()
explicit conversion
DOJ
----------
25-SEP-23 date
sysdate:
it is a built-in function.
ORACLE_6PM_APR_2024 Page 37
• it is a built-in function.
• it is used to get current system date.
Example-3:
EMP1
EMPNO ENAME LOGIN_DATE_TIME
1001 A 25-APR-24 10:30:0.0 AM
1002 B 25-APR-24 2:30:0.0 PM
creating table:
inserting records:
ORACLE_6PM_APR_2024 Page 38
INSERT INTO emp1 VALUES(1001,'A','25-APR-2024 10:30:0.0 AM');
output: string
1 row created.
implicit conversion
login_date_time
----------------
25-APR-24 10:30:0.0 AM timestamp
string
to_timestamp()
explicit conversion
login_date_time
------------------------
25-APR-2024 2:30:0.0 PM timestamp
1003 C systimestamp
systimestamp:
• it is a built-in function
• it is used to get current system date and time
Note:
To see table strcture:
ORACLE_6PM_APR_2024 Page 39
DESC[RIBE]:
it is used to see table structure
Syntax:
DESC[RIBE] <table_name>
Example:
DESC student
Output:
NAME TYPE
----------------------------------------
SID NUMBER(4)
SNAME VARCHAR2(10)
AVRG NUMBER(5,2)
user_tables:
• it is a built-in table / system table / readymade table
• it maintains all tables information
DESC user_tables
ORACLE_6PM_APR_2024 Page 40
Saturday, April 27, 2024 6:49 PM
ORACLE PAGE
default PAGESIZE is 14
default LINESIZE is 80 ---------------------------------- 80 chars
---------------------------------- linesize 80
to see all parameters list: ----------------------------------
.
SQL> SHOW ALL .
.
Output: .
LINESIZE 80 ----------------------------------
PAGESIZE 14
14 lines
PAGESIZE 14
ORACLE_6PM_APR_2024 Page 41
Column Alias
Monday, April 29, 2024 6:23 PM
Column Alias:
• Column alias => another name or alternative name for column
Example:
SELECT ename AS A, sal AS B
FROM emp;
(or)
SELECT ename A, sal B
FROM emp;
Output:
A B
-----------------------------
SMITH 800
ALLEN 1600
ORACLE_6PM_APR_2024 Page 42
DRL
Friday, April 26, 2024 7:34 PM
DRL / DQL:
• DRL => Data Retrieval Language
• DQL => Data Query language
SELECT:
• SELECT command is used to retrieve [select] the data
from table.
SELECT * / <columns_list>
FROM <table_name>
[WHERE <condition>];
SQL ENGLISH
QUERIES SENTENCES
CLAUSES WORDS
ORACLE_6PM_APR_2024 Page 43
every CLAUSE has specific purpose
every QUERY is made up of with CLAUSES.
* All Columns
note:
SELECT * FROM emp;
above query will be rewritten by oracle as following:
SELECT empno,ename,job,mgr,hiredate,sal,comm,deptno
FROM emp;
* empno,ename,job,mgr,hiredate,sal,comm,deptno
OPERATOR:
• OPERATOR is a symbol that is used to perform
operations like arithmetic or logical operations.
Arithmetic + - * /
Special / IN NOT IN
ORACLE_6PM_APR_2024 Page 45
Special / IN NOT IN
Comparison BETWEEN AND NOT BETWEEN AND
LIKE NOT LIKE
IS NULL IS NOT NULL
Exists
Any
All
Set UNION
UNION ALL
INTERSECT
MINUS
Concatenation ||
Arithmetic operators:
Arithmetic operators are used to perform Arithmetic operations
like addition , subtraction … etc.
+ Addition In C/Java:
- Subtraction 5/2 = 2
* Multiplication int/int = int
/ Divison
5%2 = 1
In ORACLE SQL:
5/2 = 2.5
NUMBER/NUMBER = NUMBER
MOD(5,2) = 1
ORACLE_6PM_APR_2024 Page 46
Examples on Arithmetic Operators:
Output:
ENAME SAL ANNUAL_SAL
------------------------------------------------------
SMITH 800 9600
ALLEN 1600 19200
Output:
ENAME SAL Annual Salary
------------------------------------------------------
SMITH 800 9600
ALLEN 1600 19200
ORACLE_6PM_APR_2024 Page 47
Example:
ORACLE_6PM_APR_2024 Page 48
Assignment:
STUDENT
SID SNAME M1 M2 M3
1001 A 70 90 80
1002 B 44 78 39
calculate total and average marks of all students.
PLAYER
PID PNAME runs balls
1001 A 20 10
1002 B 30 20
calculate strike rate of each player
<
sal>3000 valid
>
sal>3000,4000 invalid
>=
<= sal=3000 valid
= equals sal=3000,4000 invalid
ORACLE_6PM_APR_2024 Page 49
sal>3000,4000 invalid
>=
<= sal=3000 valid
= equals sal=3000,4000 invalid
!= / <> / ^= not equals
emp
empno ename sal SELECT ename, sal
1001 A 5000 FROM emp
1002 B 3000 WHERE sal>3000;
ORACLE_6PM_APR_2024 Page 50
empno ename sal SELECT ename, sal
1001 A 5000 FROM emp
1002 B 3000 WHERE sal>3000;
1003 C 8000
1004 D 1000 Execution Order:
FROM
WHERE
SELECT
FROM emp:
entire emp table will be selected.
FROM clause selects entire table.
WHERE sal>3000:
WHERE condition will be applied on every row.
WHERE clause filters the rows.
ORACLE_6PM_APR_2024 Page 51
SELECT ename, sal :
• it selects ename and sal columns.
• SELECT clause selects specified columns.
ename sal
A 5000
C 8000
Note:
CALENDAR order is ASCENDING ORDER [small to big]
2023 calendar
after 2023:
31-DEC-2023
1-JAN-2024 hiredate>'31-DEC-2023'
10-FEB-2024
before 2023:
17-AUG-2022
hiredate < '1-JAN-2023'
31-DEC-2022
1-JAN-2023
31-DEC-1981
1-JAN-1982
2-JAN-1982 hiredate > '31-DEC-1981'
.
.
SELECT ename,job,sal
FROM emp
WHERE job='manager';
Output:
no rows selected
WHERE job='manager'
empno ename job ------------------------------------
1001 A CLERK CLERK=manager F
1002 B MANAGER MANAGER=manager F
ORACLE_6PM_APR_2024 Page 53
when all conditions are FALSE, we get output as
"no rows selected".
Note:
SQL is not case sensitive language. But,
string comparison is case sensitive.
Logical operators:
ORACLE_6PM_APR_2024 Page 54
Logical operators:
• Logical operators are used to perform logical
operations like logical AND, logical OR, logical NOT.
Truth Table:
c1 => condition1
c2 => condition2
c1 c2 c1 AND c2 c1 OR c2
T T T T
T F F T
F T F T
F F F F
ORACLE_6PM_APR_2024 Page 55
Display the emp records whose empnos are:
7521, 7698, 7900
SELECT *
FROM emp
WHERE empno=7521 OR empno=7698 OR empno=7900;
Display the emp records who are working in deptno 10 and 30:
Display the managers records who are earning more than 2500:
SELECT ename,sal
FROM emp
WHERE job='MANAGER' AND sal>2500;
SELECT ename,job,sal,hiredate
FROM emp
WHERE job='MANAGER' AND hiredate>'30-APR-1981';
SELECT ename,sal
FROM emp
WHERE ename='SMITH' OR ename='BLAKE' OR ename='SCOTT';
Online Shopping
FILTER
WHERE cname='DELL'
NOT:
It is used to perform logical NOT operations.
ORACLE_6PM_APR_2024 Page 57
It is used to perform logical NOT operations.
Truth Table:
condn NOT(codn)
T NOT(T) => F
F NOT(F) => T
Example:
STUDENT1
SID SNAME M1 M2 M3
1001 A 70 90 80
1002 B 80 30 60
SELECT *
FROM student1
WHERE m1>=40 AND m2>=40 AND m3>=40;
SELECT *
FROM student1
WHERE m1<40 OR m2<40 OR m3<40;
Special Operators:
• Special operators can be also called as Comparison
Operators.
IN:
Syntax:
<column> IN(<values_list>)
examples on IN operator:
ORACLE_6PM_APR_2024 Page 59
Display the emp records whose salary is 1250 or 3000:
SELECT ename,sal
FROM emp
WHERE sal IN(1250,3000);
(or)
SELECT ename,sal
FROM emp
WHERE sal=1250 OR sal=3000;
SELECT *
FROM emp
WHERE empno IN(7521,7698,7900);
SELECT ename,job,sal
FROM emp
WHERE job IN('MANAGER','CLERK');
SELECT ename,sal,deptno
FROM emp
WHERE deptno NOT IN(10,30);
BETWEEN .. AND:
Syntax:
Display the emp records whose salary is 2000 or more and 3000
or less [whose sal b/w 2000 and 3000]:
SELECT ename,sal
FROM emp
WHERE sal BETWEEN 2000 AND 3000;
ORACLE_6PM_APR_2024 Page 61
WHERE sal BETWEEN 2000 AND 3000;
Answer: B
LIKE:
Syntax:
Examples on LIKE:
Display the emp records whose names are started with 'S':
SELECT ename,sal
FROM emp
WHERE ename LIKE '%S';
ORACLE_6PM_APR_2024 Page 63
SELECT ename, sal
FROM emp
WHERE ename LIKE '%M%';
IS NULL:
it is used for null comparison.
ORACLE_6PM_APR_2024 Page 64
• it is used for null comparison.
Syntax:
<column> IS null
Examples:
Concatenation Operator:
• Symbol: ||
• It is used to combine 2 strings.
EMP1
FNAME LNAME
------------------------
RAJ KUMAR
SAI TEJA
Example:
Display output as following:
SMITH works as CLERK
ALLEN works as SALESMAN
BLAKE works as MANAGER
ORACLE_6PM_APR_2024 Page 66
NULL
Wednesday, May 1, 2024 7:26 PM
NULL:
• NULL means empty / blank
Example:
Example:
EMPLOYEE1
EMPNO ENAME SAL
ORACLE_6PM_APR_2024 Page 67
EMPNO ENAME SAL
1001 A 7000
INSERT INTO employee1 VALUES(1001,'A',7000);
1002 B
direct way: using NULL keyword:
INSERT INTO employee1 VALUES(1002,'B',null);
1003 8000
direct way: using NULL keyword:
INSERT INTO employee1 VALUES(1003,null,8000);
1004 D
indirect way: insert limited column values
INSERT INTO employee1(empno,ename) VALUES(1004,'D');
ORACLE_6PM_APR_2024 Page 68
Wednesday, May 1, 2024 7:27 PM
STUDENT
SID SNAME M1 NUMBER(3)
1001 A 70
1002 B 80
1003 C 0
1004 D 55
null
1005 E we are unable to insert
ABSENT
EMPLOYEE
EMPNo ENAME SAL
1001 A 6000
1002 B 8000 null
1003 C salary is unknown
1005 D 7000
ORACLE_6PM_APR_2024 Page 69
UPDATE
Thursday, May 2, 2024 6:53 PM
UPDATE:
• UPDATE command is used to modify table data.
Syntax:
UPDATE <table_name>
SET <column>=<new_value> [, <column>=<new_value> , ….]
[WHERE <condition>];
Examples on UPDATE:
UPDATE emp
SET sal=sal+2000
WHERE empno=7521;
UPDATE emp
ORACLE_6PM_APR_2024 Page 70
UPDATE emp
SET job='MANAGER', sal=6000
WHERE empno=7369;
UPDATE emp
SET sal=sal+sal*0.2
WHERE job='MANAGER';
UPDATE emp
SET sal=sal+1000;
UPDATE emp
SET deptno=20
WHERE deptno=10;
UPDATE emp
SET sal=sal+sal*0.2, comm=comm+comm*0.1
WHERE comm is not null;
ORACLE_6PM_APR_2024 Page 71
set comm as null to the emp whose empno is 7499:
UPDATE emp
SET comm=null
WHERE empno=7499;
Note:
For null comparison we cannot use =
For null assignment we use =
UPDATE emp
SET comm=900
WHERE comm IS NULL;
UPDATE emp
SET sal=sal+sal*0.2
WHERE TRUNC((sysdate-hiredate)/365)>42;
Example:
EMPLOYEE5
EMPNO ENAME SAL TA HRA TAX GROSS
1001 A 8000
1002 B 6000
Calculate TA, HRA, TAX and GROSS salary:
ORACLE_6PM_APR_2024 Page 72
Calculate TA, HRA, TAX and GROSS salary:
COMMIT;
UPDATE employee5
SET TA=SAL*0.1, HRA=SAL*0.2, TAX=SAL*0.05;
UPDATE employee5
SET gross = sal+ta+hra-tax;
COMMIT;
ORACLE_6PM_APR_2024 Page 73
ASSIGNMENT:
STUDENT
SID SNAME M1 M2 M3 TOTAL AVRG
1001 A 70 90 50
1002 B 50 30 74
calculate total and avrg
ORACLE_6PM_APR_2024 Page 74
DELETE
Friday, May 3, 2024 6:30 PM
DELETE:
• It is used to delete the records.
Syntax:
COMMIT;
Examples on DELETE:
ORACLE_6PM_APR_2024 Page 77
TCL
Friday, May 3, 2024 6:49 PM
TCL:
• TCL => Transaction Control Language
• It deals with transactions.
• Transaction:
○ Transaction is a series of actions [SQL commands].
○ Examples: withdraw, deposit, fund transfer, placing order
Example:
ACCOUNTS
ACNO NAME BALANCE
1001 A 80000-10000 = 70000
1002 B 40000+10000 = 50000
ORACLE_6PM_APR_2024 Page 78
ORACLE SQL provides 3 TCL commands. They are:
• COMMIT
• ROLLBACK
• SAVEPOINT
COMMIT [save]:
• It is used to save the transaction.
• When COMMIT command is executed the changes in
INSTANCE [RAM] will be applied to DATABASE [HARD DISK].
• It makes the changes permanent.
Syntax: COMMIT
COMMIT;
ORACLE DB SERVER
Client
INSTANCE DB
INSERT => 1001
1001 emp
INSERT => 1002
1002 1001
COMMIT
1002
ROLLBACK :
• ROLLBACK is used to cancel the transaction.
ORACLE_6PM_APR_2024 Page 79
• It cancels all uncommitted actions.
Syntax:
ROLLBACK [TO <savepoint_name>];
STUDENT5
SID SNAME
ROLLBACK;
SAVEPOINT:
• It is used to set margin [specific point] for rollback.
Syntax:
SAVEPOINT <savepoint_name>;
Example:
ORACLE_6PM_APR_2024 Page 81
Note:
All DDL commands are auto committed.
All DML commands are not auto committed.
Example:
ORACLE_6PM_APR_2024 Page 82
ALTER
Saturday, May 4, 2024 6:12 PM
Table
EMPLOYEE
EMPNO ENAME SAL Table Structure [columns]
1001 A 8000
1002 B 6000 Table Data [rows]
Note:
• DDL commands deal with metadata
• DML commands deal with data
ALTER:
• ALTER => Change
Syntax:
Example on ALTER:
STUDENT
SID SNAME
DESC student
Output:
NAME TYPE
------------------------------------------
SID NUMBER(4)
SNAME VARCHAR2(10)
DESC student
Output:
NAME TYPE
------------------------------------------
SID NUMBER(4)
SNAME VARCHAR2(10)
M1 NUMBER(3)
ORACLE_6PM_APR_2024 Page 84
Adding multiple columns [m2, m3]:
DESC student
Output:
NAME TYPE
------------------------------------------
SID NUMBER(4)
SNAME VARCHAR2(10)
M1 NUMBER(3)
M2 NUMBER(3)
M3 NUMBER(3)
DESC student
Output:
NAME TYPE
------------------------------------------
SID NUMBER(4)
SNAME VARCHAR2(10)
M1 NUMBER(3)
M2 NUMBER(3)
MATHS NUMBER(3)
Note:
using RENAME COLUMN, we can rename one column only
DESC student
Output:
NAME TYPE
------------------------------------------
SID NUMBER(4)
SNAME VARCHAR2(10)
M1 NUMBER(3)
M2 NUMBER(3)
DESC student
Output:
NAME TYPE
------------------------------------------
SID NUMBER(4)
SNAME VARCHAR2(10)
DESC student
Output:
NAME TYPE
------------------------------------------
SID NUMBER(4)
SNAME VARCHAR2(20)
SNAME VARCHAR2(20)
---------
SAI
ORACLE_6PM_APR_2024 Page 86
SAI
NARESH => max string length 6. we can decrease up to 6
KIRAN
RAJU
Modifying data type [modify data type sid from number to char]:
DESC student
Output:
NAME TYPE
------------------------------------------
SID CHAR(8)
SNAME VARCHAR2(20)
Note:
To modify data type column must be empty
ORACLE_6PM_APR_2024 Page 87
DROP, FLASHBACK, PURGE
Saturday, May 4, 2024 7:04 PM
DROP:
• DROP command is used to drop [delete] entire
table.
Syntax:
DROP TABLE <table_name> [PURGE];
Example:
RECYCLEBIN
DROP TABLE employee;
employee
Note:
• RECYCLEBIN feature added in ORACLE 10g version
FLASHBACK:
• introduced in ORACLE 10g version.
• it is used to restore the dropped table.
Syntax:
FLASHBACK TABLE <table_name>
TO BEFORE DROP
[RENAME TO <new_name>];
ORACLE_6PM_APR_2024 Page 88
Example:
FLASHBACK TABLE employee
TO BEFORE DROP;
PURGE:
• introduced in ORACLE 10g version.
• It is used to delete the table from RECYCLEBIN.
Syntax:
PURGE TABLE <table_name>;
Example:
PURGE TABLE employee;
--employee table will be deleted from recyclebin
--employee table deleted permanently
to see recyclebin:
SHOW RECYCLEBIN
--displays dropped tables
to empty rcyclebin:
PURGE RECYCLEBIN;
--empties recyclebin
Note:
login as USER and practice DROP, FLASHBACK and PURGE
ORACLE_6PM_APR_2024 Page 89
RECYCLEBIN will not work for SYSTEM user
FLASHBACK emp
restore it
delete it
PURGE
(or)
CASE-1:
ORACLE_6PM_APR_2024 Page 90
INSERT INTO t1 VALUES(1);
INSERT INTO t1 VALUES(2);
COMMIT;
RECYCLEBIN
CASE-2:
ORACLE_6PM_APR_2024 Page 91
INSERT INTO t2 VALUES('A');
INSERT INTO t2 VALUES('B');
COMMIT;
FLASHBACK TABLE t2
TO BEOFRE DROP;
Output:
ERROR: original name used by
existing object
c##batch6pm
FLASHBACK TABLE t2 T2
TO BEFORE DROP T2_old
RENAME TO t2_old;
ORACLE_6PM_APR_2024 Page 92
TRUNCATE, RENAME
Monday, May 6, 2024 6:47 PM
TRUNCATE:
• it is used to delete all rows with good performance.
Syntax:
TRUNCATE TABLE <table_name>;
Example:
TRUNCATE TABLE employee;
EMPLOYEE Table
EMPNO ENAME SAL structure
1001 A 6000
1002 B 9000
1003 C 8000
data
1004 D 7000
1005 E 4000
TRUNCATE
DELETE TRUNCATE
• it is slower • it is faster
TABLESPACE
ORACLE_6PM_APR_2024 Page 93
SEGMENT SEGMENT
EXTENT
EXTENT
Block Block
-records -records
8KB 8KB
Block Block
-records -records
8KB 8KB
Block Block
-records -records
8KB 8KB
TABLESPACE
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_6PM_APR_2024 Page 94
Monday, May 6, 2024 6:59 PM
Note:
• All DDL commands are auto committed
• All DML commands are not auto committed
ORACLE_6PM_APR_2024 Page 95
Monday, May 6, 2024 7:28 PM
TRUNCATE
RENAME
ORACLE_6PM_APR_2024 Page 96
DCL
Monday, May 6, 2024 7:34 PM
DCL / ACL:
• DCL => Data Control Language
• ACL => Accessing Control Language
GRANT:
• it is used to give permission to other users
on DB Objects like tables, views.
Syntax:
GRANT <privileges_list>
ON <DB_Object_name>
TO <users_list>;
Examples:
c##batch6pm OWNER
TABLE EMP
login as c##batch6pm:
GRANT select
ON emp
TO c##userA;
login as c##userA:
ORACLE_6PM_APR_2024 Page 97
login as c##userA:
login as c##batch6pm:
login as c##userA:
login as c##batch6pm:
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:
ORACLE_6PM_APR_2024 Page 98
REVOKE:
• It is used to cancel the permissions.
Syntax:
REVOKE <privileges_list>
ON <DB_Object_Name>
FROM <users_list>;
Examples:
REVOKE all
ON emp
FROM c##userA;
Login as DBA:
T1
F1 F2
1 A
2 B
CREATE TABLE t1
(
f1 NUMBER(4),
f2 VARCHAR2(10)
);
GRANT select
ON t1
TO c##userB;
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;
COMMIT;
GRANT all
ON t1
TO c##userB;
DESC t1
Output:
F1
F2
F3
REVOKE insert,update,delete
ON t1
FROM c##userb;
SELECT *
FROM c#3userA.t1;
--displays data
REVOKE all
ON t1
FROM c##userb;
c##userB:
SELECT grantor, privilege, table_name
FROM user_tab_privs_recd;
c##userA:
SELECT
INSERT
DELETE
UPDATE
ALTER
FLASHBACK
INDEX
REFERENCES
ON COMMIT REFRESH
READ
QUERY REWRITE
DEBUG
Copying Table:
• Copying Table means, creating new table from existing
table.
• With SELECT query result a new table will be created here.
Syntax:
Example-1:
Example-2:
Syntax:
false condition:
CREATE TABLE <name> WHERE 1=2
AS WHERE 'A'='B'
SELECT <columns_list> WHERE 500=600
FROM <table_name>
WHERE <false_condition>;
Example:
Create a new table emp3 with emp table structure
without rows:
Syntax:
Example:
EMP EMP4
8 columns 8 columns
13 rows no rows
copy to emp4
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
Example:
EMP5
EMP
4 cols empno,ename,job,sal
8 cols copy no rows
13 rows
copy
EMP6
4 cols empno,ename,job,sal
copy no rows
EMP7
4 cols empno,ename,job,sal
no rows
Syntax:
INSERT ALL
INTO <table_name>[(<columns_list>)] VALUES(<values_list>)
INTO <table_name>[(<columns_list>)] VALUES(<values_list>)
.
ORACLE_6PM_APR_2024 Page 108
INTO <table_name>[(<columns_list>)] VALUES(<values_list>)
INTO <table_name>[(<columns_list>)] VALUES(<values_list>)
.
.
<SELECT query>;
EMP EMP5
8 cols copy 4 cols empno,ename,job,sal
13 rows no rows
copy
copy EMP6
4 cols empno,ename,job,sal
no rows
EMP7
4 cols empno,ename,job,sal
no rows
INSERT ALL
INTO emp5 VALUES(empno,ename,job,sal)
INTO emp6 VALUES(empno,ename,job,sal)
INTO emp7 VALUES(empno,ename,job,sal)
SELECT empno,ename,job,sal FROM emp;
Syntax:
INSERT ALL
WHEN <condition1> THEN
INTO <table_name>[(<columns_list>)] VALUES(<values_list>)
WHEN <condition2> THEN
INTO <table_name>[(<columns_list>)] VALUES(<values_list>)
.
.
ELSE
INTO <table_name>[(<columns_list>)] VALUES(<values_list>)
<SELECT query>;
EMP_MGR
EMP
4 cols empno,ename,job,sal
8 cols
no rows
13 rows copy
MANAGER
EMP_CLERK
CLERK copy
4 cols empno,ename,job,sal
ANALYST
no rows
SALESMAN
copy
PRESIDENT
EMP_OTHERS
4 cols empno,ename,job,sal
no rows
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;
Assignment:
EMP dept10
8 cols 3 cols empno ename deptno
13 rows no rows
copy
deptno 10
deptno 20
deptno 30 copy dept20
3 cols empno ename deptno
no rows
copy
dept30
3 cols empno ename deptno
no rows
MERGE:
CUSTOMER2
CUSTOMER1 [Replica => duplicate copy]
1004 D HYD
1005 E VZG
MERGE:
• MERGE command introduced in ORACLE 9i version.
Example on MERGE:
s.cid = t.cid
CUSTOMER1 s CUSTOMER2 t
CID CNAME CCITY
CID CNAME CCITY
1001 A HYD
1001 A HYD
1002 B DLH
1002 B DLH
1003 C MUM
1003 C MUM
1001 A HYD
1004 D HYD
1005 E VZG
COMMIT;
s.cid = t.cid
CUSTOMER1 s CUSTOMER2 t => replica
matched CID CNAME CCITY
CID CNAME CCITY
1001 A HYD
1001 A AB HYD BLR
update 1002 B DLH
1002 B DLH
1003 C MUM
1003 C MUM not matched
DUAL:
desc dual
• DUAL is a readymade table
• It has 1 column, 1 row
select * from dual;
DUAL
DUMMY
X
Example:
SELECT 100+200 FROM dual;
Output:
300
SELECT 100+200;
Output:
300
Built-In Functions:
String Functions:
lower():
• it is used to convert the string to lower case.
Syntax:
lower(<string>)
Examples:
lower('RAJU') raju
lower('RAJ KUMAR') raj kumar
Syntax:
upper(<string>)
Examples:
upper('raju') RAJU
Syntax:
initcap(<string>)
Examples:
initcap('RAJU') Raju
initcap('RAJ KUMAR VARMA') Raj Kumar Varma
UPDATE emp
ename=initcap(ename);
ENAME lower(ename)='blake'
-------------- -------------------------------------
SMITH lower('SMITH') smith = blake F
ALLEN lower('ALLEN') allen = blake F
WARD lower('WARD') ward = blake F
ORACLE_6PM_APR_2024 Page 120
-------------- -------------------------------------
SMITH lower('SMITH') smith = blake F
ALLEN lower('ALLEN') allen = blake F
WARD lower('WARD') ward = blake F
BLAKE lower('BLAKE') blake = blake T
WHERE lower(ename)='blake';
(or)
WHERE upper(ename)='BLAKE';
(or)
WHERE initcap(ename) ='Blake';
length():
• it is used to find length of the string.
• length of the string => no of chars in string
Syntax:
length(<string>)
Examples:
length('RAJU') 4
length('RAVI TEJA') 9
Example:
(or)
Concat():
• concatenate => combine
• it is used to combine 2 strings.
Syntax:
concat(<string1>, <string2>)
Examples:
concat('RAJ','KUMAR') RAJKUMAR
concat('RAJ','KUMAR','VARMA') ERROR
concat(concat('RAJ','KUMAR'),'VARMA') RAJKUMARVARMA
(or)
EMPLOYEE
ENAME
EMPNO FNAME LNAME
-------------
1001 RAJ KUMAR Raj Kumar
1002 SAI KRISHNA Sai Krishna
1003 RAVI TEJA Ravi Teja
UPDATE employee
SET ename=initcap(fname || ' ' || lname);
COMMIT;
Substr():
• it is used to get sub string from the string.
Syntax:
Substr(<string>, <position> [, <no_of_chars>])
Examples:
1 2 3 4 5 6 7 8 9
R A V I T E J A
1 2 3 4 5 6 7 8 9
R A J K U M A R
R A J K U M A R
-9 -8 -7 -6 -5 -4 -3 -2 -1
Examples:
UPDATE emp
SET mail_id=Substr(ename,1,3) || Substr(empno,-3,3) || '@wipro.com';
Display the emp records whose names are started with 'S':
SELECT ename,sal
FROM emp
WHERE substr(ename,-1,1)='S';
(or)
SELECT ename,sal
FROM emp
WHERE ename LIKE '%S';
Instr():
• it is used to check whether sub string is existed in string or not.
Syntax:
Instr(<string>, <sub_string> [, <search_position>, <occurrence>])
Example:
1 2 3 4 5 6 7 8 9
R A V I T E J A
1 2 3 4 5 6 11 16
R A V I T E J A R A V I T E J A
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
-16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Examples on INSTR:
(or)
(or)
(or)
(or)
Example:
EMPLOYEE
ORACLE_6PM_APR_2024 Page 127
EMPLOYEE
EMPNO ENAME FNAME LNAME
1001 SAI KRISHNA SAI KRISHNA
1002 RAVI TEJA RAVI TEJA
1003 KIRAN KUMAR KIRAN KUMAR
UPDATE employee
SET fname=Substr(ename,1,Instr(ename,' ')-1),
Lname=Substr(ename,Instr(ename, ' ')+1);
COMMIT;
Lpad():
• it is used to fill specified char set at left side.
Syntax:
Lpad(<string>, <size> [, <char/chars>])
Syntax:
Rpad(<string>, <size> [, <char/chars>])
Examples:
Lpad('RAJU',10,'*') ******RAJU
Rpad('RAJU',8,'@') RAJU@@@@
Lpad('SAI',10,'$#') $#$#$#$SAI
Lpad('A',6,'A') AAAAAA
Lpad('X',8,'X') XXXXXXXX
Ltrim():
• it is used to remove unwanted characters from left side
Syntax:
Ltrim(<string> [, <char/chars>])
Rtrim():
• it is used to remove unwanted characters from right side
Syntax:
Rtrim(<string> [, <char/chars>])
Trim():
• using it, we can remove unwanted chars from left side or
right side or both sides.
Syntax:
Trim(LEADING/TRAILING/BOTH <char> FROM <string>)
Examples:
Ltrim('***RAJU***','*') RAJU***
Rtrim('***RAJU***','*') ***RAJU
Replace():
• it is used to replace search string with replace string.
Syntax:
Replace(<string>, <search string>, <replace string>)
ORACLE_6PM_APR_2024 Page 130
Replace(<string>, <search string>, <replace string>)
Examples:
Replace('SAI KRISHNA', 'SAI', 'RAMA') RAMA KRISHNA
Replace('SAI TEJA SAI KRISHNA', 'SAI', 'RAVI') RAVI TEJA RAVI KRISHNA
Translate():
○ it is used to replace search with corresponding char in replace char set.
Syntax:
Translate(<string>, <search_char_set>, <replace_char_set>)
Examples:
s => X
a => Y
i => Z
Replace('abcabcaabbccabc','abc','XYZ') XYZXYZaabbccXYZ
Translate('abcabcaabbccabc','abc','XYZ') XYZXYZXXYYZZXYZ
Note:
Translate() can be used to encrypt or decrypt the data.
encrypt decrypt
zq^^w hello
hello
Reverse():
it is used to get reverse string
Syntax:
Reverse(<string>)
Example:
Reverse('ramu') umar
ASCII():
it returns ASCII value of specified char
Examples:
ASCII('A') 65
ASCII('a') 97
Chr():
it returns char of specified ASCII value
Examples:
Chr(65) A
Chr(97) a
Soundex():
• it is used to retrieve data based on sounds.
• when we don't know exact spelling then it is useful.
Syntax:
Soundex(<string1>) = Soundex(<string2>)
Example:
Conversion Functions:
Implicit Conversion:
• if conversion is done implicitly by ORACLE then it is
called "Implicit Conversion".
Example:
Note:
• Don't depend on Implicit Conversion
for 2 reasons:
○ Implicit conversion degrades the performance.
Explicit Conversion:
if conversion is done using built-in function then it is
ORACLE_6PM_APR_2024 Page 133
• if conversion is done using built-in function then it is
called "Explicit Conversion".
to_char() to_char()
to_date() to_number()
Syntax:
To_Char(<date>, <format>)
Note:
sysdate function is used to get today's date
JAN, FEB
JANUARY
sun => 1
mon => 2
.
.
MI minutes part
SS seconds part
FF fractional seconds
AM / PM AM or PM
(or)
(or)
Display the emp records who joined in 1st and 4th quarter:
(or)
(or)
SUNDAY3spaces
MONDAY3spaces
to_char(hiredate,'DAY')='SUNDAY' TUESDAY2spaces
SUNDAY3spaces = SUNDAY FALSE WEDNESDAY 9
THURSDAY1space
FRIDAY3spaces
SATURDAY1space
(or)
SUNDAY3spaces
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(5000,'L9999.99') $5000.00
to_char(5000,'C9,999.99) USD5,000.00
select ename,
to_char(sal,'L99,999.99') AS sal
FROM emp;
Note:
login as DBA:
username: system
password: nareshit
NLS_CURRENCY $
NLS_ISO_CURRENCY AMERICA
SELECT ename,
to_char(sal,'L99999.99','NLS_CURRENCY=¥') AS sal
FROM emp;
SELECT ename,
to_char(sal,'C99999.99','NLS_ISO_CURRENCY=INDIA') AS sal
FROM emp;
to_date():
• it is used to convert string to date.
Syntax:
to_date(<string>, <format>)
Example:
EMP1
EMPNO ENAME HIREDATE
HIREDATE
Implicit Conversion
-------------
27-DEC-23 DATE
/
Output:
enter .. d: 15
enter .. m: 8
enter .. y: 2018
to_date('25-dec-2023') 25-DEC-23
to_date('25 DECEMBER 2023') 25-DEC-23
to_date('DECEMBER 25 2023') ERROR
to_date('DECEMBER 25 2023','MONTH DD YYYY') 25-DEC-23
to_date('25/12/2023') ERROR
to_date('25/12/2023','DD/MM/YYYY') 25-DEC-23
SELECT to_char(to_date('15-AUG-1947'),'DAY')
FROM dual; date
SELECT to_char(to_Date('24-APR-1973'),'DAY')
FROM dual;
To_Number():
• It is used to convert string to number.
• String must be numeric string only.
Syntax:
to_number(<string> [, <format>])
Examples:
to_number('123') 123
to_number('123.67') 123.67
to_number('$5000.00') ERROR
to_number('$5000.00','L9999.99') 5000
to_number('USD5,000.00') ERROR
to_number('USD5,000.00','C9,999.99') 5000
to_number('ABC') ERROR
sum()
sum():
is used to find sum of a set of values
Syntax:
sum(<column>)
Examples:
Avg():
it is used to find average of a set of values.
Syntax:
Avg(<column>)
Examples:
Min():
It is used to find minimum value in a set of values
Syntax:
Min(<column>)
ORACLE_6PM_APR_2024 Page 144
Min(<column>)
Examples:
Max():
it is used to find max value in a set of values.
Syntax:
max(<column>)
Examples:
count():
it is used to find number of records or number of
column values.
Syntax:
count(* / <column>)
Examples:
Number Functions:
sqrt() ceil()
power() floor()
sign() trunc()
abs() round()
mod()
sqrt():
• it us sued to find square root value
Syntax:
sqrt(<number>)
Examples:
sqrt(100) 10
sqrt(81) 9
power():
• it is used to find power values
Syntax:
power(<number>, <power>)
Examples:
power(5,3) 125
power(2,4) 16
sign():
• it is used to check whether the number is +ve or -ve or 0.
• if number is +ve, it returns 1
• if number is -ve, it returns -1
• if number is 0, it returns 0
Syntax:
sign(<number>)
Examples:
sign(25) 1
sign(-25) -1
sign(0) 0
abs():
• it is used to get absolute value.
• absolute value => non-negative
Syntax:
abs(<number>)
Examples:
abs(25) 25
abs(-25) 25
Mod():
it is used to get remainder value
Syntax:
Mod(<number>, <divisor>)
ORACLE_6PM_APR_2024 Page 147
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:
round(<number>)
Examples:
ceil(123.6789) 123 and 124
124
floor(123.6789) 123
Trunc():
• it is used to remove decimal places.
Syntax:
Trunc(<number> [, <no_of_decimal_places>])
Examples:
Trunc(123.45678) 123
Trunc(123.45678,1) 123.4
Trunc(123.45678,2) 123.45
Trunc(123.45678,3) 123.456
Round():
• if value is avrg or above avrg then it gives upper value
• if value is below avrg, it gives lower value
Syntax:
Round(<number>, <no_of_decimal_places>)
Examples:
TRUNC(123.678) 123
123+124 = 247
ROUND(123.678) 123 and 124
247/2 = 123.5
avrg: 123.5
124
TRUNC(123.478) 123
ROUND(123.478) 123 and 124
avrg: 123.5
123
Round(123.5) 123 and 124
avrg: 123.5
124
Trunc(123.5) 123
Trunc(123.6789,2) 123.67
Round(123.6789,2) 123.68
Trunc(567.45678,3) 567.456
Round(567.45678,3) 567.457
Round(567.45648,3) 567.456
120+130 = 250
250/2 = 125
ROUND(127.5678,-1) 120 and 130
avrg: 125
130
TRUNC(127.5678,-1) 120
Date Functions:
Add_Months()
Months_Between()
Last_day()
Next_day()
sysdate:
it returns current system date
systimestamp:
it returns current system date and time
Examples:
display current system date:
Add_Months():
• it is used to add months to specific date.
• it can be also used to subtract the months from specific date.
Syntax:
Add_Months(<date>, <no_of_months>)
Examples:
Examples:
ORDERS
ORDER_ID CID PID QTY PRICE Ordered_Date Delivery_Date
123456 .. .. .. .. sysdate sysdate+5
PRODUCTS
PID PNAME MANUFACTURED_DATE EXPIRY_DATE
1234 XYZ sysdate Add_Months(sysdate,3)
EMPLOYEE
EMPID ENAME DOBirth DORetirement
1234 ABC 25-DEC-2000 Add_Months(DOBirth,60*12)
CMS_LIST
STATE_CODE CM_NAME START_DATE END_DATE
TS RR 9-DEC-2023 Add_Months(start_date,5*12)
Output:
no rows selected.
hiredate = sysdate
20-MAY-24 6:18 PM = 20-MAY-24 6:26 PM FALSE
TRUNC(hiredate) = TRUNC(sysdate)
TRUNC(20-MAY-24 6:18 PM) = TRUNC(20-MAY-24 6:26 PM)
20-MAY-24 = 20-MAY-24 TRUE
(or)
Assignment:
Assignment:
GOLD_RATE
Months_Between():
• it is used to find difference between 2 date values.
• it returns number of months.
Syntax:
Months_Between(<date1>, <date2>)
Example:
ORACLE_6PM_APR_2024 Page 154
Example:
Months_Between('20-MAY-2024','20-MAY-2023') 12
Months_Between('20-MAY-2024','20-MAY-2023')/12 1
(or)
months
year
Mod(15,12) 3
15 months trunc(15/12) 1
Mod(30,12) 6
30 months trunc(30/12) 2
Last_day():
it is used to get last date in the month.
Syntax:
Last_day(<date>)
Examples:
Last_day(sysdate) 31-MAY-24
Last_day('17-FEB-2024') 29-FEB-24
Last_day('17-FEB-2023') 28-FEB-23
SELECT
Last_day(Add_Months(sysdate,-1))+1 FROM dual;
Last_day(20-APR-24)
30-APR-24+1
Next_day():
it is used to get next date based on the weekday.
example: find next Friday date, find next sunday date
Syntax:
Next_day(<date>, <weekday>)
Examples:
find next Friday date:
Rank()
Dense_Rank()
Row_Number()
dense = no gaps
Rank():
• it is used to apply ranks to records according to specific column order.
• it does not follow sequence in ranking if multiple values are same. it means, gaps will
be there in ranking.
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.
• it follows sequence in ranking even if multiple values are same. it means, no gaps will
be there in ranking.
Syntax:
DENSE_RANK() OVER([PARTITION BY <column>] ORDER BY <column> ASC/DESC)
Examples:
ORACLE_6PM_APR_2024 Page 157
Examples:
(or)
ORDER BY clause:
• it is used to arrange the records in ascending or descending
order.
Syntax:
ORDER BY <column> ASC/DESC, <column> ASC/DESC, …
PARTITION BY clause:
• it us used to group the records according to particular column
Syntax:
deptno
----------
10 10
10
10
20
20 20
20
30
30
30
30
clear breaks
clear breaks
Row_Number():
Syntax:
Row_Number() OVER(PARTITION BY <column>
ORDER BY <column> ASC/DESC)
Examples:
Apply row numbers to all emp records:
Apply row numbers to all emp records whose salaries are more
than 2500:
Other Functions:
NVL()
NVL2()
Greatest()
Least()
User
UID
DECODE()
NVL():
• It is used to replace the nulls.
Syntax:
NVL(<arg1>, <arg2>)
Examples:
NVL(10,20) 10
NVL(null,20) 20
Example:
STUDENT
SID SNAME M1 [number]
replace nulls with ABSENT
1234 A 78
1235 B
nvl(to_char(m1),'ABSENT')
1236 C 0
1237 D 66
1238 E
1239 F
1240 G 44
ORACLE_6PM_APR_2024 Page 161
1240 G 44
Note:
NVL() function can replace nulls only
NVL2():
• NVL2() function can replace nulls and not nulls.
Syntax:
NVL2(<arg1>, <arg2>, <arg3>)
Examples:
NVL2(10,20,30) 20
NVL2(null,20,30) 30
Example:
set comm as 700 to the emps who are not getting commission.
increase 1000 rupees comm to the emps who are getting comm:
UPDATE emp
SET comm=NVL2(comm,comm+1000,700);
Max():
it is used to find max value in vertical values [column]
Syntax:
Max(<column>)
Greatest():
it is used to find max value in horizontal values [row]
Syntax:
greatest(<value1>, <v2>, …………………….)
Examples:
T1
SELECT max(f1) FROM t1;
F1
Output:
-------
90
10
90
20
Min():
it is used to find min value in vertical values
Syntax:
Min(<column>)
ORACLE_6PM_APR_2024 Page 163
Min(<column>)
Least():
it is used to find min value in horizontal values
Syntax:
Least(<value1>, <v2>, ……………..)
Examples:
T1
SELECT min(f1) FROM t1;
F1
Output:
-------
10
10
90
20
User:
it returns current user name
UID:
it returns current user id
Example:
SELECT user, uid FROM dual;
Decode():
• It is used to implement "IF .. THEN .. ELSIF" in SQL.
• it can check equality condition only.
Syntax:
Decode(<column>,
<value1>,<return_expression1>,
<value2>,<return_expression2>,
.
.
<else_return_expression>)
Example:
SELECT ename,
Decode(Job,
'PRESIDENT', 'BIG BOSS',
'MANAGER','BOSS',
'EMPLOYEE') AS job,
sal FROM emp;
Example:
Increase salary of all emps as following:
deptno 10 => increase 10% on sal
deptno 20 => increase 20% on sal
others => increase 5% on sal
UPDATE emp
SET sal=
decode(deptno,
10,sal+sal*0.1,
20,sal+sal*0.2,
ORACLE_6PM_APR_2024 Page 165
20,sal+sal*0.2,
sal+sal*0.05);
Built-In Functions:
Date add_months()
sysdate
sytimestamp
next_day()
last_day()
Analytic rank()
dense_rank()
row_number()
ENGLISH
SQL
SENTENCES
QUERIES
WORDS
CLAUSES
• SELECT
• FROM
• WHERE
• ORDER BY
• GROUP BY
• HAVING
• DISTINCT
• OFFSET
• FETCH
ORDER BY:
• ORDER BY clause is used to arrange the records in
ascending or descending order according to specific
column(s).
• default order is: ASC
Syntax:
ORDER BY <column> ASC/DESC, <column> ASC/DESC, ….
NUMBER CHAR
Note:
Calendar order is ASCENDING ORDER.
ASC DESC
1-Jan-23 31-DEC-23
2-JAN-23 30-DEC-23
3-JAN-23 .
. .
. 1-JAN-23
31-DEC-23
(or)
(or)
SELECT *
FROM emp
ORDER BY 6 DESC;
(or)
(or)
20 10
10 20
10 6000 10 8000
10 8000 10 6000
Note:
In ASCENDING ORDER, nulls will be displayed at last.
In DESCENDING ORDER, nulls will be given first.
GROUP BY:
• GROUP BY is used to group the records according
to particular column(s).
• On these groups, we apply aggregate functions.
• It is mainly used for data analysis.
• It gives summarized data from detailed data
Syntax:
GROUP BY <grouping_columns_list>
Example:
GROUP BY deptno
DEPTNO SUM_OF_SAL
10 ?
20 ?
30 ?
DEPTNo SUM_OF_SAL
10 ..
20 ..
Execution order:
SELECT deptno, sum(Sal) AS sum_of_Sal --------------------------
FROM emp FROM
WHERE deptno IN(10,20) WHERE
GROUP BY deptno GROUP BY
ORDER BY deptno ASC; HAVING
ORACLE_6PM_APR_2024 Page 173
FROM emp
WHERE deptno IN(10,20) WHERE
GROUP BY deptno GROUP BY
ORDER BY deptno ASC; HAVING
SELECT
DISTINCT
emp ORDER BY
OFFSET
EMPNO ENAME SAL DEPTNO
FETCH
1004 D 8000 20
1005 E 12000 20
1006 F 10000 30
1007 G 11000 30
1001 A 6000 10
1002 B 5000 10
1003 C 9000 10
FROM emp:
it selects entire table
emp
EMPNO ENAME SAL DEPTNO
1004 D 8000 20
1005 E 12000 20
1006 F 10000 30
1007 G 11000 30
1001 A 6000 10
1002 B 5000 10
1003 C 9000 10
GROUP BY deptno:
it groups the records according to specified column
1004 D 8000 20
sum(sal) => 20000
1005 E 12000 20
1001 A 6000 10
1002 B 5000 10 sum(sal) => 20000
1003 C 9000 10
DEPTNO Sum_OF_SAL
20 20000
10 20000
DEPTNO Sum_OF_SAL
10 20000
20 20000
YEAR NO_OF_EMPS
1980 ?
1981 ?
1982 ?
1983 ?
QUARTER NO_OF_EMPS
1 ?
2 ?
3 ?
4 ?
Assignment:
Find month wise no of emps joined in organization
GROUP BY to_char(hiredate,'MM') MM/MON/MONTH
JOB SUM_OF_SAL
MANAGER ?
CLERK ?
ANALYST ?
Syntax:
GROUP BY Rollup(grouping_columns_list)
Example:
GROUP BY Rollup(deptno, job)
Syntax:
GROUP BY Cube(grouping_columns_list)
Example:
GROUP BY Cube(deptno, job)
Assignment:
SALES
DATEID AMOUNT find year wise, quarter wise sales.
ORACLE_6PM_APR_2024 Page 183
SALES
DATEID AMOUNT find year wise, quarter wise sales.
1-JAN-2020 50000 calculate sub totals and grand total
2-JAN-2020 75000 according to year and quarter [cube()]
..
.. 2020 1 ?
.. 2 ?
24-MAY-2024 60000 3 ?
4 ?
2020 sales ?
2021 1 ?
2 ?
3 ?
4 ?
2021 sales ?
1st qrtr sales ?
2nd
3rd
4th
GRAND TOTAL
Note:
WHERE clause is used to specify condition on rows
HAVING:
• It is used to specify conditions on groups.
• it filters the groups.
• It will be applied on result of GROUP BY.
• It cannot be used without GROUP BY.
Syntax:
HAVING <group_condition>
Examples on HAVING:
Output:
ERROR: YEAR invalid identifier
Note:
In ORACLE 23AI version,
we can use column alias in GROUP BY
Note:
Till ORACLE 21C, we cannot use column alias in GROUP BY, HAVING,
WHERE.
DISTINCT:
• It is used to eliminate the duplicate records.
Syntax:
Examples on DISTINCT:
JOB
----------- JOB
CLERK -----------
SALESMAN CLERK
SALESMAN SALESMAN
ANALYST ANALYST
MANAGER MANAGER
ANALYST
MANAGER
MANAGER
CLERK
CLERK
30 CLERK
30 MANAGER 30 CLERK
30 SALESMAN 30 MANAGER
30 SALESMAN 30 SALESMAN
30 SALESMAN
30 SALESMAN
OFFSET:
• introduced in ORACLE 12c
• it is used to specify number of rows to be skipped.
Syntax:
OFFSER <number> ROW/ROWS
FETCH:
• introduced in ORACLE 12c
• it is used to specify number of rows to be fetched [selected]
Examples:
Display all emp table rows except first 5 rows:
SELECT / SELECT ALL used to specify columns list SELECT ename, sal
Goal:
COLLEGE Database
Course
Student
Marks
Fee
Staff
S.SID = M.SID
STUDENT S MARKS M
SID SNAME SCITY SID Maths Phy Che
1001 A HYD 1001 70 90 60
1002 B BLR 1002 55 67 39
1003 C MUM 1003 48 72 81
JOINS
JOINS:
• JOIN => connect / combine
• JOIN is an operation.
Types of Joins:
Inner Join:
2 Types:
○ Equi Join
○ Non-Equi Join
Equi Join:
If join operation is performed based on equality
condition then it is called "Equi Join".
Example:
WHERE S.SID = M.SID
STUDENT S MARKS M
SID SNAME SCITY SID Maths Phy Che
1001 A HYD 1001 70 90 60
1002 B BLR 1002 55 67 39
1003 C MUM 1003 48 72 81
Note:
For ORACLE 9i version, we can write Join Query in
2 styles. They are:
• ORACLE STYLE / NATIVE STYLE
• ANSI STYLE => Best way => portable
SQL SERVER
ORACLE
we can run
Note:
• In ORACLE STYLE, to separate 2 table names we use , [comma].
• In ANSI STYLE, to separate 2 table names we use keyword
ORACLE STYLE:
ANSI STYLE:
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
unmatched record from dept
1001 A 1800
1002 B 2000 unmatched records from emp
ORACLE STYLE:
ANSI STYLE:
ORACLE STYLE:
ANSI STYLE:
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
Note:
First filter condition will be executed.
Then join operation will be performed.
ANSI STYLE:
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
ORACLE STYLE:
ANSI STYLE:
Example:
Retrieving data from 4 tables:
ORACLE STYLE:
ANSI STYLE:
EMP1 DEPT1
EMPNO ENAME DEPTNO DEPTNO DNAME LOCID
1001 A 10 10 SALES 100
LOCATION1 COUNTRY1
LOCID LNAME CID CID CNAME
100 HYD 123456 123456 INDIA
Equi Join:
If join operation is performed based on equality condition
then it is called "Equi Join".
Examples:
WHERE s.sid = m.sid
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:
WHERE e.deptno > d.deptno
WHERE e.deptno < d.deptno
WHERE e.deptno != d.deptno
Example:
e.sal BETWEEN s.losal AND s.hisal
EMP e SALGRADE s
EMPNO ENAME SAL GRADE LOSAL HISAL
1001 A 1300 1 700 1200
1002 B 7000 2 1201 1400
1003 C 6000 3 1401 2000
1004 D 1000 4 2001 3000
1005 E 2500 5 3001 9999
ORACLE STYLE:
ANSI STYLE:
Outer Join:
• INNER JOIN can give matched records only.
To get unmatched records also we use OUTER JOIN.
Note:
• In ORACLE STYLE,
based on JOIN CONDITION we can decide left table and right
table
Example:
WHERE e.deptno = d.deptno
• In ANSI STYLE,
based on keyword we can decide left table and right table
Example:
FROM emp e INNER JOIN dept d
• Left Outer join can give matched records and unmatched records
from left table.
ORACLE STYLE:
ANSI STYLE:
• Right Outer Join can give matched records and unmatched records
from right table.
ORACLE STYLE:
ANSI STYLE:
• Full outer join = matched + unmatched from left and right tables
ORACLE STYLE:
ANSI STYLE:
ORACLE STYLE:
ANSI STYLE:
ORACLE STYLE:
ANSI STYLE:
Full Outer Join = matched + unmatched from left and right tables
Full Outer Join + Conditions = unmatched from left and right tables
ORACLE STYLE:
ANSI STYLE:
Self Join:
• If a table is joined to itself then it is called
"Self Join".
Example:
e.mgr = m.empno
EMP e EMP m
EMPNO ENAME JOB SAL MGR EMPNO ENAME JOB SAL MGR
1001 A MANAGER 30000 1001 A MANAGER 30000
1002 B CLERK 10000 1001 1002 B CLERK 10000 1001
1003 C ANALYST 8000 1001 1003 C ANALYST 8000 1001
1004 D MANAGER 25000 1004 D MANAGER 25000
1005 E SALESMAN 12000 1004 1005 E SALESMAN 12000 1004
1006 F CLERK 11000 1004 1006 F CLERK 11000 1004
ORACLE STYLE:
ANSI STYLE:
Display the emp records who are earning more than their
managers:
emp_name emp_Sal mgr_name mgr_sal
ORACLE STYLE:
ANSI STYLE:
ORACLE STYLE:
ANSI STYLE:
Example:
x.cid < y.cid
GROUPA x GROUPA y
CID CNAME CID CNAME
10 IND 10 IND
20 AUS 20 AUS
30 WIN 30 WIN
IND VS AUS
IND VS WIN
AUS VS WIN
ORACLE STYLE:
ANSI STYLE:
A B
A = {1,2,3} 1
4
B = {4,5}
2
5
AXB = ?
3
AXB = (1,4)(1,5)
3 * 2 =6
(2,4)(2,5)
(3,4)(3,5)
GROUPA a GROUPB b
CID CNAME CID CNAME
10 IND 40 ENG
20 AUS 50 SL
30 WIN 60 NZ
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
ORACLE STYLE:
ANSI STYLE:
JOINS:
GOAL:
it is used to retrieve the data from multiple tables.
Types of joins:
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
Assignment:
EMPLOYEE e PROJECT p
EMPID ENAME PID PID PNAME
1001 A 30 10 X
1002 B 30 20 Y
1003 C 10 30 Z
1004 D 10
1005 E
1006 F
Display emp details along with project details => [Equi Join]
empid ename pname
SYNTAX:
SELECT <columns_list> / *
FROM <table_name>
WHERE <column> <operator> (<SELECT QUERY>);
Examples:
Note:
When we use Aggregate Function [group function],
SELECT clause allows group function or group by
column only.
UPDATE emp
SET sal=(find deptno 30's max sal)
WHERE ename='JAMES';
UPDATE emp
SET sal=(SELECT max(sal) FROM emp WHERE deptno=30)
WHERE ename='JAMES';
Find the dept name which is spending max amount on their emps:
ALL:
• it is used to compare column value with multiple values.
Syntax:
<column> <relational_operator> ALL(<values_list>)
Example:
Display the emp records whose salary is more than 2000 and 3000:
SAL
---------
5000 T
4000 T
2500 F
1000 F
1800 F
sal<ALL(2000,3000) sal<2000 AND sal<3000
SAL
---------
5000 F
4000 F
2500 F
1000 T
1800 T
ANY:
it is used to compare column value with multiple values.
Syntax:
<column> <relational_operator> ANY(<values_list>)
Example:
Display the emp records whose salary is more than 2000 or 3000:
SAL
---------
5000 T
4000 T
2500 T
1000 F
1800 F
sal<ANY(2000,3000) sal<2000 OR sal<3000
SAL
---------
5000 F
4000 F
2500 T
1000 T
1800 T
(or)
Display the emp records who are earning more than any one
of managers:
(or)
Inline View:
Syntax:
SELECT <columns_list>
FROM (<SUB QUERY>)
WHERE <condition>;
Output:
enter … n: 3
gives 3rd max sal
/
enter … n: 5
gives 5th max sal
SELECT *
FROM (SELECT ename, sal,
dense_rank() over(order by sal desc) as rank
FROM emp)
WHERE rank<=3;
SELECT *
FROM (SELECT ename, sal,
dense_rank() over(order by sal desc) as rank
FROM emp)
WHERE rank<=5;
SELECT *
FROM (SELECT ename, sal,
dense_rank() over(order by sal desc) as rank
FROM emp)
WHERE rank<=&n;
• ROWNUM
ROWNUM:
• ROWNUM is a pseudo column.
It is used to apply row numbers to records.
Examples on ROWNUM:
SELECT *
FROM (SELECT rownum as rn, empno, ename, sal
FROM emp)
WHERE rn=3;
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 5 AND 10;
SELECT *
ORACLE_6PM_APR_2024 Page 222
SELECT *
FROM (SELECT rownum as rn, empno, ename, sal
FROM emp)
WHERE MOD(rn,2)=0;
Output:
EMP DEPT
---------- ------------
13 4
3
1. selects a row
2. passes value
INNER
OUTER
4. passes value
Example:
Display the emp records who are earning more than their
dept's avrg sal:
EMP e
DEPTNO AVG(SAL)
ORACLE_6PM_APR_2024 Page 224
dept's avrg sal:
EMP e
DEPTNO AVG(SAL)
EMPNO ENAME DEPTNO SAL
10 15000
1001 A 10 20000
20 25000
1002 B 20 10000
30 10000
1003 C 30 15000
1004 D 10 10000
1005 E 20 40000
1006 F 30 5000
Output:
ENAME DEPTNO SAL
A 10 20000
C 30 15000
E 20 40000
EMP e
EMPNO ENAME DEPTNO SAL
1001 A 10 20000
1002 B 20 10000
1003 C 30 15000
1004 D 10 10000
1005 E 20 40000
1006 F 30 5000
Sub Query:
A query which is written in another query
Display the emp records who are earning more than BLAKE:
ROWID:
• it is a pseudo column.
• it is used to get address of row.
Example:
STUDENT
SID SNAME SCITY
1001 A HYD AAAStWAAHAAAAF7AAB
1001 A HYD AAAStWAAHAAAAF7AAC
Constraint:
• Constraint => restrict / control / limit
• Constraint is a rule that is applied on column.
• Constraint is used to restrict the user from entering invalid data.
• Constraint is used to maintain quality and accurate data.
• Maintaining quality data and accurate data is called "Data Integrity".
• To implement data integrity feature we use CONSTRAINTS.
Examples:
Max marks: 100
0 TO 100
STUDENT
CHECK(m1 BETWEEN 0 AND 100)
SID SNAME M1
1234 A 78
1235 B 66
1236 C 567 ERROR
CHECK(gender IN('M','F'))
GENDER
-------------
M
F
F
M
Z ERROR
Example:
EMPLOYEE
PK
EMPNO ENAME JOB SAL
1001 SAI CLERK 8000
1002 KIRAN CLERK 7000
1003 SAI SALESMAN 8000
1001 ERROR: duplicate AMAR MANAGER 15000
ERROR: null RAMESH ANALYST 6000
Example:
CREATE TABLE t1
(
f1 INT PRIMARY KEY
);
NOT NULL:
• it does not accept nulls.
• it accepts duplicates.
• When value is mandatory and it can be duplicated then use NOT
NULL.
ORACLE_6PM_APR_2024 Page 231
NULL.
Example:
EMPLOYEE
NOT NULL
EMPNO ENAME SAL
1234 Raju 8000
1235 Kiran 10000
1236 Raju 6000
1237 ERROR: null 9000
Example:
CREATE TABLE t2
(
f1 INT NOT NULL
);
UNIQUE:
• it does not accept duplicates.
• it accepts nulls.
• when value is optional and that should not be
duplicated then use UNIQUE.
Example:
CUSTOMER
UNIQUE
CID CNAME MOBILE
1234 A 9123456789
1235 B 8976543211
1236 C
1237 D 9123456789 ERROR
ORACLE_6PM_APR_2024 Page 232
1237 D 9123456789 ERROR
1238 E
Example:
CREATE TABLE t3
(
f1 INT UNIQUE
);
CHECK:
• It is used to apply our own condition on column.
Example:
STUDENT
DEFAULT 'NARESH' DEFAULT 'HYD' DEFAULT 20000
SID SNAME CNAME CCITY FEE
1234 A NARESH HYD 20000
1235 B NARESH HYD 20000
1236 C NARESH HYD 20000
1237 D NARESH HYD 20000
1238 E NARESH HYD 10000
Example:
COURSE STUDENT
PK FK
CID CNAME REFERENCES COURSE(CID)
10 JAVA SID SNAME CID
20 PYTHON 1001 A 10
30 HTML 1002 B 10
1003 C 30
1004 D 20
1005 E 80 ERROR
1006 F 90 ERROR
1007 G
Example:
ORACLE_6PM_APR_2024 Page 234
Example:
EMPLOYEE
EMPID ENAME GENDER SAL
Example:
STUDENT
SID SNAME M1
Example:
users_list
userid uname pwd
ORACLE_6PM_APR_2024 Page 235
userid uname pwd
Example:
STUDENT18
SID SNAME CNAME CCITY FEE
SID PK
SNAME NOT NULL
CNAME DEFAULT 'NARESH'
CCITY DEFAULT 'HYD'
FEE DEFAULT 20000
DEPT1 EMP1
PK FK
DEPTNO DNAME PK REFERENCES dept1(deptno)
10 HR EMPNO ENAME DEPTNO
20 SALES 1001 A 20
30 ACCOUNTS 1002 B 20
1003 C 10
1004 D 90 ERROR
Note:
PK and FK columns data types must be same
Naming Constraints:
user_constraints:
• it is a system table / readymade table
• it maintains all constraints information
Example:
Note:
we cannot give constraint name to DEFAULT
STUDENT21
Example:
COURSE30 STUDENT30
PK c5 FK c6
CID CNAME references course30(cid)
10 JAVA SID SNAME CID
20 HTML 1001 A 20
30 C# 1002 B 30
1003 C 70 ERROR
2 reasons:
Example:
apply combination of columns as PK:
STUDENT31
PK(SID,SUBJECT)
SID SNAME SUBJECT MARKS
1001 A M1 70
1001 A M2 80
1001 A M3 70
1002 B M1 66
1002 B M2 59
1002 B M3 80
1001 M1 ERROR
null ERROR
null ERROR
Example:
PRODUCTS CHECK(expiry_date>manufactured_date)
PID PNAME MANUFACTURED_DATE EXPIRY_DATE
1001 ABC 5-JUN-24 25-DEC-22 ERROR
ALTER:
Using ALTER command we can,
• add the columns
• drop the columns
• rename the columns
• modify the data types
• modify the field sizes
Syntax:
Example:
STUDENT32
SID SNAME M1
Note:
• we can add the constraint using ADD CONSTRAINT or MODIFY
• using ADD CONSTRAINT, we can add table level constraints only.
using MODIFY, all 6 constraints can be added.
Add PK to sid:
Disabling PK:
Enabling PK:
Dropping PK:
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 => common elements
SET OPERATORS:
• SET OPERATOR is used to combine result of 2 select
queries.
Syntax:
<SELECT QUERY>
<SET OPERATOR>
<SELECT QUERY>;
UNION:
it combines result of 2 select queries without
duplicates
UNION ALL:
ORACLE_6PM_APR_2024 Page 245
UNION ALL:
it combines result of 2 select queries including
duplicates
INTERSECT:
it gives common records from the result of 2 select
queries.
MINUS:
it gives specific records from select query.
Example:
FOOTBALL CRICKET
SID SNAME SID SNAME
1001 A 5001 D
1002 B 1002 B
1003 C 5002 E
SID SNAME
1001 A
1002 B
1003 C
5001 D
5002 E
Output:
SID SNAME
ORACLE_6PM_APR_2024 Page 247
SID SNAME
1001 A
1002 B
1003 C
5001 D
1002 B
5002 E
Example:
DEPTNO 10 DEPTNO 20
MANAGER MANAGER
CLERK CLERK
PRESIDENT ANALYST
MANAGER
CLERK
PRESIDENT
ANALYST
MANAGER
CLERK
PRESIDENT
ANALYST
Example:
SELECT sid, sname FROM football
UNION
SELECY sid FROM cricket;
Output:
ERROR
Example:
SELECT sid, sname FROM football
UNION
SELECT sname, sid FROM cricket;
Output:
ERROR
• slower • faster
EMP DEPT
EMPNO ENAME DEPTNO DEPTNO DNAME
EMP_IND EMP_US
EMPNO ENAME EMPNO ENAME
1001 A 5001 C
1002 B 5002 D
UNION
EMPNO ENAME
1001 A
1002 B
5001 C
5002 D
truncate
rename
Built-In Functions:
conversion to_char()
ORACLE_6PM_APR_2024 Page 254
conversion to_char()
to_date()
to_number()
aggregate / max() min() count()
group avg() sum()
date add_months()
sysdate
systimestamp
last_day()
next_day()
Clauses:
FROM
WHERE
GROUP BY
HAVING
SELECT
DISTINCT
ORDER BY
OFFSET
FETCH
Joins:
cross join
Sub Queries:
a query which is written in another query
Types:
Constraints:
ORACLE_6PM_APR_2024 Page 256
Constraints:
PK
NOT NULL
UNIQUE
CHECK
DEFAULT
FK
SET OPERATORS:
UNION
UNION ALL
INTERSECT
MINUS