SQL
SQL
Akhil (Admin)
Notes link:
Mobile: 9154156192 (Only Whatsapp)
bit.ly/oracledbnotes
SQL:
TABLES
SQL Commands DDL, DRL, DML, TCL, DCL
Built-In Functions max() min() lower() upper() …
Clauses Group By, Having, Order By …
Joins Inner join, Outer join …..
Sub Queries Non-correlated, correlated
Set operators union, union all, intersect …
Constraints Primary key, foreign key, check ….
VIEWS
SEQUENCES
INDEXES
MATERIALIZED VIEWS
SYNONYMS
PL/SQL:
Metadata
BANK
customer is depositing amount
Branches customer is withdrawing amount
Customers opening account
Transactions closing account
Products
Employee
2020 ?
2021 ?
.
.
2024 ?
Amazon
searching for products
placing orders
Products
adding items to wishlist
Customers
Orders
Payments
Wishlist 2020 ?
Sellers 2021 ?
Suppliers .
.
Goal:
Storing organization's business data permanently
in computer
Variable: empno
• Variable is temporary.
1234
int empno;
e1
Sal
9000
File:
File is permanent
Database:
Database is permanent
Data Store:
• is a location where data is stored.
Example:
File, Database
Database:
• is a kind of data store.
• Database is a location where organization's business
data stored permanently.
Example:
BANK DB COLLEGE DB
Branches COURSES
Customers STUDENTS
Transactions FEE
Products MARKS
Employee STAFF
interrelated =>
BANK DB contains bank related data. not college
ORACLE 730AM JUNE 2024 Page 6
BANK DB contains bank related data. not college
related data
DBMS:
• DBMS => Database Management System / Software
Evoluation of DBMSs:
Examples:
ORACLE, SQL SERVER, MY SQL, DB2, Postgre SQL
Table:
• Table is a collection of rows and columns
• row is horizontal representation of data
• column is vertical representation of data
Example:
Table / Relation / Entity
EMPLOYEE
EMPID ENAME SAL
Column / Attribute / Property / Field
1234 Kiran 12000
1235 Vijay 15000
Examples:
Column name, Table name, Data Type, Field size
Example:
ORACLE:
• is a Relational Database Management Software [RDBMS]
Evaluation of DBMSs:
Examples of RDBMS:
SQL:
SQL => Structured Query Language.
• It is a query language.
• In this we write queries to communicate with ORACLE DB.
Example:
SELECT ename, sal FROM emp; => QUERY
BANK DB SERVER
Client
QUERY DB
request
ACCOUNTS
SELECT balance
response ACNO NAME BALANCE
FROM accounts
1234 A 50000
WHERE acno=1234;
Output: 1235 B 80000
50000
In PL/SQL:
ORACLE SQL SERVER MY SQL Procedure:
DATABASE DATABASE DATABASE a set of statements
TABLES TABLES TABLES Sub program
DEPT EMP
DEPTID DNAME EMPID ENAME SAL DEPTID
10 HR 1234 A 12000 20
20 SALES 1235 B 20000 10
JOINS
ENAME DNAME
EMP DEPT
PL/SQL:
• PL => Procedural Language
• SQL => Structured Query Language
• It is programming language.
BANK DB
Branches table
IFSC_Code City State Country
Customers
Custid CNAME AADHARNUM PAN_NUM ACNO
Transactions
Acno date_time ttype amount
Employee
EMPNO ENAME SAL
truncate
rename
DML: insert
• Data Manipulation Language. update
• It deals with data manipulations. delete
insert all
merge
TCL: commit
• Transaction Control Language rollback
• It deals with transactions. savepoint
DDL:
• DDL => Data Definition Language SALARY => metadata
• Data Definition => metadata. ----------
• It deals with metadata 6000 => data
• metadata is the data about the data
ORACLE DB OBJECTS:
Table
View
Index
Materialized View
Sequence
Synonym
Procedure
Function
Package
Trigger
Create:
• Create command is used to create the ORACLE DB
OBJECTS like tables, view, indexes … etc.
Varchar2(n):
• n => max no of chars
• It is used to hold strings.
• It is variable length data type.
• it is used to hold variable length chars.
• max size: 4000 Bytes [4000 chars]
• default size: there is no default size
Note:
character related data types can hold letters,
digits and special symbols.
Note:
VARCHAR2 data type can hold max of 4000 chars only.
To hold more than 4000 chars we use LONG or CLOB.
LONG has some restrictions. That is why it's better to se
CLOB.
LONG:
• it is used to hold large amounts of chars.
• it 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
CLOB:
• CLOB => Character Large Object
• it is used to hold large amounts of chars.
• A table can have multiple columns as CLOB type.
• we can use built-in functions on CLOB type.
• max size: 4 GB
Example:
Feedback CLOB
Product_Features CLOB
NUMBER(p):
• it is used to hold integers.
• p => precision => max no of digits
• p valid range is: 1 to 38
Examples:
AGE NUMBER(2)
MOBILE_NUMBER NUMBER(10)
AADHAR_NUMBER NUMBER(12)
CREDIT_CARD_NUMBER NUMBER(16)
Note:
integer and int are alias names of number(38)
Number(p,s):
• p => precision => max no of digits
• s => scale => max no of decimal places
• it is used to hold float values.
SALARY NUMBER(8,2)
------------
25000.00
100000.00
900000.00
1000000.00 ERROR
DATE:
• It is used to hold date values.
• it can hold date, month, year, hours, minutes and seconds.
• it cannot hold fractional seconds.
• by default it will not display time.
• Default oracle date format: DD-MON-YY.
• default time: 12:00:00 AM [mid night time]
• it is fixed length data type.
• max size: 7 bytes.
Examples:
Date_Of_Birth DATE
Date_Of_retirement DATE
Ordered_Date DATE
Delivery_Date DATE
Timestamp:
• introduced in ORACLE 9i version.
• It is used to hold date and time.
• it can hold date, month, year, hours, minutes, seconds
and fractional seconds.
• It is extension of DATE type.
• by default it displays time.
• default format: DD-MON-YY HH:MI:SS:FF AM
• it is fixed length data type.
• max size: 11 Bytes
Examples:
Transaction_date_time TIMESTAMP
login_date_time TIMESTAMP
manufactured_Date_time TIMESTAMP
T1
fixed length F1 CHAR(10) F2 VARCHAR2(10) variable length
RAJU6spaces RAJU
10 4
10 NARESH4spaces NARESH 6
10 SAI7spaces SAI 3
DB SERVER = INSTANCE + DB
ORACLE:
• is a server side software.
• it is used to maintain the database in the form of tables.
DB SERVER = INSTANCE + DB
SQL PLUS:
Client side software.
ORACLE 730AM JUNE 2024 Page 24
• Client side software.
• Using this software, we can connect and communicate
with ORACLE DB.
Note:
When we install ORACLE software, along with it SQL PLUS
software will be installed.
to login as DBA:
• username: system
• password: naresh [at the time of ORACLE installation you have
given password in 4th step]
Creating User:
Syntax:
Example:
Login as DBA:
username: system
password: naresh
ORACLE 730AM JUNE 2024 Page 25
password: naresh
connect • is a privilege.
• is a permission for login
resource • is a privilege.
• is a permission to create database
resources like tables, indexes,
procedures, functions, packages,
triggers.
unlimited • is a privilege
tablespace • is a permission to insert the records
Syntax:
CONN[ECT] <username>/<password>
Example:
CONN c##batch730am/nareshit
Output:
Connected.
Changing password:
Syntax:
ALTER USER <user_name>
IDENTIFIED BY <new_password>;
Login as DBA:
username: system
password: naresh
Note:
Username is not case sensitive
C##BATCH730AM = c##batch730am = C##BatCH730aM
Dropping User:
Syntax:
DROP USER <username> [CASCADE];
Example:
DROP USER c##vijay CASCADE;
Note:
If user is empty no need to write CASCADE.
If user is not empty we must write CASCADE.
ORACLE 730AM JUNE 2024 Page 29
If user is not empty we must write CASCADE.
To clear screen:
Syntax:
CL[EAR] SCR[EEN]
Example:
SQL> CLEAR SCREEN
(or)
SQL> CL SCR
Example-1:
STUDENT
SID SNAME AVRG AVRG: 100.00
1234 Kiran 56.78
1235 Sai 78.92
SID NUMBER(4)
SNAME VARCHAR2(10)
AVRG NUMBER(5,2)
Creating table:
ORACLE 730AM JUNE 2024 Page 32
Creating table:
Inserting records:
COMMIT
ORACLE DB SERVER
INSTANCE DB
INSERT 1234
student
1235 1234
1235
INSERT
ORACLE 730AM JUNE 2024 Page 33
1235 1234
1235
INSERT
RAM HARD DISK
Note:
SQL is not case sensitive.
CREATE = create = CReaTe => all are same
/
Output:
Enter value for sid: 2003
Enter value for sname: C
Enter value for avrg: 52.89
/
Output:
Enter value for sid: 2004
Enter value for sname: D
ORACLE 730AM JUNE 2024 Page 34
Enter value for sname: D
Enter value for avrg: 88.99
Note:
• Parameter Concept is used to read the values at run time.
Syntax:
&<text>
Example:
&sid
Output:
Enter value for sid:
• / = RUN = R
It runs recent query in memory. It means, it runs above query
STUDENT
SID SNAME AVRG
5001 ABC
Example-2:
EMPLOYEE
EMPID ENAME GENDER SAL DOJ
1001 AA M 12000 25-DEC-23
1002 BB F 15000 17-AUG-20
100000.00
empid NUMBER(4)
ename VARCHAR2(10)
gender CHAR(1)
sal NUMBER(8,2)
doj DATE
Syntax:
ORACLE 730AM JUNE 2024 Page 36
Syntax:
DESC[RIBE] <table_name>
Example:
DESC employee
Output:
NAME TYPE
----------------------------------------------
EMPID NUMBER(4)
ENAME VARCHAR2(10)
.. ..
User_Tables:
• it is a system table / built-in table / readymade table.
• It maintains all tables information which are created by a
user.
DESC user_tables
Output:
NAME
-----------------
TABLE_NAME
..
..
Note:
• To_Date() function is used to convert string to date.
Note:
sysdate:
○ is a built-in function.
○ it returns current system date.
NOTE:
For every data type default value is NULL.
1005 13000
COMMIT;
Example-3:
EMPLOYEE1
EMPID ENAME LOGIN_DATE_TIME
5001 A 18-JUN-24 10:30.0.0 AM
5002 B 18-JUN-24 2:30.0.0 PM
5003 C current sys date and time
Note:
default time: 12:00:00.00 AM
COMMIT;
Types of Conversions:
2 Types:
• 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
Output: implicit conversion
300
num num
100 + 200
300 => num
Explicit Conversion:
• if conversion is done using built-in function then
it is called "Explicit Conversion".
Example:
SELECT to_number('100') FROM dual;
string
ORACLE 730AM JUNE 2024 Page 42
string
to_number()
explicit conversion
num
100
Note:
Implicit Conversion degrades the performance.
that is why always do explicit conversion. For explicit
conversion we use built-in functions like to_number(),
to_date(), to_char().
Output:
LINESIZE 80
PAGESIZE 14
Note:
default page size is 14
default line size is 80
Setting pagesize:
Syntax:
SET PAGES[IZE] <value>
Example:
SQL> SET PAGES 200
Setting linesize:
Syntax:
SET LINES[IZE] <value>
Example:
SQL> SET LINES 200
COLUMN ALIAS:
• we can give temporary name to the column. this is called
column alias.
• alias => another name / alternative name
• To change the column headings in output we use column
alias.
• AS keyword is used to give column alias.
• Using AS keyword is optional.
• To give column alias in multiple words or to maintain the
case we must enclose column alias in double quotes.
Example:
SELECT ename, sal FROM emp
Output:
ENAME SAL
-------------------------------
(or)
Output:
A B
-------------------------------
DRL / DQL:
• DRL => Data Retrieval Language
• DQL => Data Query Language
checking balance
searching for products
transaction statement
SELECT:
• It us used to retrieve (fetch / select) the data from table.
Syntax:
SELECT <columns_list>
FROM <tables_list>
WHERE <condition>;
SQL ENGLISH
QUERIES SENTENCES
CLAUSES WORDS
Syntax:
SELECT <columns_list>
Example:
SELECT sname, avrg
FROM clause:
• it is used to specify tables list
Syntax:
FROM <tables_list>
Examples:
FROM student
FROM student, marks
WHERE clause:
• it is used to specify filter condition.
• it filters the rows.
• WHERE condition will be applied on every row.
Syntax:
WHERE <condition>
Example:
WHERE sid=1234
WHERE avrg>=60
* All Columns
Note:
SELECT * FROM emp
* empno,ename,job,mgr,hiredate,sal,comm,deptno
SELECT empno,ename,job,mgr,hiredate,sal,comm,deptno
FROM emp
SELECT *
FROM emp
WHERE sal=3000;
Execution Order:
FROM
WHERE
SELECT
FROM emp
EMP
WHERE sal=3000
EMPNO ENAME SAL
2500=3000 F
1001 A 2500 3000=3000 T
1002 B 3000 5000=3000 F
1003 C 5000 3000=3000 T
1004 D 3000
EMPNO ENAME SAL
ORACLE 730AM JUNE 2024 Page 50
EMPNO ENAME SAL
1002 B 3000
1004 D 3000
SELECT *
* = empno, ename, sal
Arithmetic + - * /
Special / IN NOT IN
Comparison BETWEEN AND NOT BETWEEN AND
LIKE NOT LIKE
IS NULL IS NOT NULL
ALL
ANY
EXISTS
Set UNION
UNION ALL
INTERSECT
MINUS
Concatenation ||
Arithmetic Operators:
Arithmetic operators are used to perform arithmetic
operations.
+ Addition
ORACLE 730AM JUNE 2024 Page 52
+ Addition In C or Java:
- Subtraction 5/2 = 2
* Multiplication int/int = int
/ Divison 5%2 = 1
In SQL:
5/2 = 2.5
MOD(5,2) => 1
Assignment:
STUDENT
SID SNAME M1 M2 M3 m1+m2+m3 (m1+m2+m3)/3
1001 A 66 78 46 66+78+46 = 190 190/3
1002 B 78 34 92 78+34+92 = 204 204/3
Syntax:
<column> <relational_operator> <value>
Examples:
sal=3000
sal>3000
sal<3000
sal>=3000
sal<=3000
sal!=3000
Note:
• SQL is not case sensitive language. But, string
comparison is case sensitive.
Note:
CALENDAR order is ASCENDING ORDER [small to big]
1-JAN-1981
2-JAN-1981
.
.
31-DEC-1981
1-JAN-1982
. > '31-DEC-1981'
.
31-DEC-1982
.
.
.
.
31-DEC-1980 < '1-JAN-1981'
1-JAN-1981
CLERK!=MANAGER T
MANAGER!=MANAGER F
ANALYST!=MANAGER T
Logical Operators:
• Logical Operators are used to perform logical operations like
logical AND, logical OR, logical NOT.
AND:
• it is used to perform logical AND operations.
• it is used to separate multiple conditions.
• If all conditions are satisfied then that whole condition is TRUE.
Syntax:
<condition1> AND <condition2>
Syntax:
<condition1> OR <condition2>
Note:
AND All conditions should be satisfied
OR At least one condition should be satisfied
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
SAL
---------
5000
2500
1000
3000
2450
1-JAN-1981
2-JAN-1981
.
.
30-DEC-1981
31-DEC-1981
Display the emp records whose names are: ALLEN, MILLER, SCOTT:
STUDENT
SID SNAME M1 M2 M3
1001 A 70 90 80
1002 B 50 30 60
Truth table:
condn NOT(condn)
T NOT(T) => F
F NOT(F) => T
JOB NOT(job='MANAGER')
------------- ------------------------------
MANAGER MANAGER = MANAGER => NOT(T) => F
CLERK CLERK = MANAGER => NOT(F) => T
ANALYST ANALYST = MANAGER => NOT(F) => T
IN:
○ It is used to compare column value with a list of values.
○ It avoids of writing multi equality conditions using OR.
Syntax:
<column> IN(<values_list>)
Example:
sal IN(3000,800)
Examples on IN:
(or)
sal
----------
2500 not in list F
800 is in list T
4000 not in list F
3000 is in list T
JOB
----------
MANAGER T
ANALYST F
ORACLE 730AM JUNE 2024 Page 64
ANALYST F
CLERK T
SALESMAN F
SELECT *
FROM emp
WHERE empno IN(7499,7698,7900);
EMPNO
------------
7698 T
7800 F
ANALYST T
MANAGER F
BETWEEN AND:
• It is used to compare column value with range of values.
Syntax:
<column> BETWEEN <lower> AND <upper>
Example:
sal BETWEEN 2450 AND 3000
(or)
SAL
------------
1000 F
2500 T
4000 F
2450 T
6000 F
3000 T
1-JAN-1982
.
.
31-DEC-1982
HIREDATE
--------------------
25-DEC-1980 F
ORACLE 730AM JUNE 2024 Page 67
25-DEC-1980 F
17-AUG-1982 T
SELECT *
FROM emp
WHERE empno BETWEEN 7600 AND 7800;
Display the emp records whose salary is less than 1000 or more
than 3000 [whose sal not between 1000 and 3000]:
(or)
SAL
----------
5000 T
2500 F
LIKE:
• It is used to compare column value with text pattern.
Syntax:
<column_name> LIKE <text_pattern>
SELECT *
FROM emp
WHERE ename LIKE 'S%';
SELECT *
FROM emp
WHERE ename LIKE '%S';
SELECT *
FROM emp
WHERE ename LIKE 'A%';
Display the emp names whose names are ended with RD:
SELECT *
FROM emp
WHERE ename LIKE '%RD';
SELECT *
FROM emp
WHERE ename LIKE 'S%S';
SELECT *
FROM emp
WHERE ename LIKE '____';
SELECT *
FROM emp
SELECT *
FROM emp
WHERE ename LIKE '%A%';
Display the emp records whose names are not started with S:
SELECT *
FROM emp
WHERE ename NOT LIKE 'S%';
IS NULL:
• It is used for null comparison.
Syntax:
<column> IS NULL
EXAMPLE:
SAL
------------
6000 F
null T
7000 F
null T
NULL=NULL FALSE
Note:
for null comparison we cannot use =
we must use IS NULL
Concatenation Operator:
Syntax:
<string1> || <string2>
Example:
SELECT 'RAJ' || 'KUMAR' FROM dual;
Output:
RAJKUMAR
SELECT ename || ' works as ' || job || ' and earns ' || sal
FROM emp;
NULL:
• NULL means empty / blank / no value.
Example:
SELECT 100+200+null FROM dual;
Output:
null
Note:
we can insert NULL in 2 ways. they are:
• Direct way: use NULL keyword
• Indirect way: insert limited column values
Example:
EMP21
ORACLE 730AM JUNE 2024 Page 75
EMP21
EMPID ENAME SAL
1001 A
1st way: direct way => using null keyword:
1002 B
2nd way: indirect way => insert limited column values:
1003 7000
EMPLOYEE
EMPID ENAME SAL
1001 A 12000
1002 B 10000 NULL
1003 C
when we don't know the value
we insert NULL
STUDENT
SID SNAME M1 NUMBER(3)
1001 A 76
1002 B 0
1003 C 66
NULL
1004 D
UPDATE:
• UPDATE command is used to modify table data.
Syntax:
UPDATE <table_name>
SET <column_name> = <new_value> [, <column_name> = <new_value>, ..]
[WHERE <condition>];
SQL ENGLISH
QUERIES SENTENCES
CLAUSES WORDS
UPDATE emp
SET sal=sal+2000
WHERE empno=7521;
UPDATE emp
ORACLE 730AM JUNE 2024 Page 78
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 sal=sal+sal*&per/100
WHERE empno=&empno;
Output:
Enter value for per: 10
Enter value for empno: 7499
/
Output:
Enter value for per: 20
Enter value for empno: 7698
UPDATE emp
SETdeptno=20
WHERE deptno=10;
UPDATE emp
SET sal=sal+sal*0.1, comm=comm+comm*0.2
WHERE comm is not null;
UPDATE emp
SET comm=900
WHERE comm IS null;
UPDATE emp
SET comm=null
WHERE empno IN(7369,7698,7788);
Note:
ORACLE 730AM JUNE 2024 Page 80
Note:
For null comparison we use IS NULL
For null assignment we use =
UPDATE emp
SET sal=sal+sal*0.1
WHERE sal*12>30000;
UPDATE emp
SET sal=sal+sal*0.15
WHERE TRUNC((sysdate-hiredate)/365)>42;
Example:
EMPLOYEE11
EMPID ENAME SAL TA HRA TAX GROSS
1234 A 18000
1235 B 20000
1234 A 18000
1235 B 20000
COMMIT;
UPDATE employee11
SET ta=sal*0.1, hra=sal*0.2, tax=sal*0.05;
UPDATE employee11
SET gross=sal+ta+hra-tax;
COMMIT;
DELETE:
• DELETE command is used to delete the records
from table.
Note:
After performing DML operation, to save it use COMMIT.
to cancel it use ROLLBACK.
Syntax:
Examples on delete:
TCL:
• TCL => Transaction Control Language
• It deals with transactions.
• Transaction:
Transaction is a series of actions [SQL commands].
Examples:
deposit, withdraw, placing order, fund transfer
Note:
Transaction must be successfully finished or cancelled.
Example:
ACCOUNTS
ACNO NAME BALANCE
1234 A 70000-10000 = 60000
1235 B 30000+10000 = 40000
ORACLE DB SERVER
Client
INSTANCE DB
1234 emp
INSERT => 1234
1235 1234
INSERT => 1235
1235
RAM HARD DISK
COMMIT:
• it is used to save the transaction.
• when COMMIT command is executed the changes in
INSTANCE [RAM] will be moved to DB [HARD DISK].
• COMMIT command makes the changes permanent.
Syntax:
COMMIT;
ROLLBACK:
• It is used to cancel the transaction.
• When ROLLBACK command is executed, it cancels
all uncommitted actions.
Syntax:
ROLLBACK [TO <savepoint_name>];
EMPLOYEE12
EMPID ENAME SAL
ROLLBACK;
SAVEPOINT:
• It is used to set margin for ROLLBACK.
• savepoint names are temporary.
When transaction is ended names will be cleared.
ORACLE 730AM JUNE 2024 Page 88
• When transaction is ended names will be cleared.
Syntax:
SAVEPOINT <savepoint_name>;
Example:
CREATE TABLE t1(f1 INT);
7.00 AM
BEGIN TRANSACTION
EMPLOYEE
EMPID ENAME SAL Structure [columns]
1234 A 6000 +
1235 B 8000 data [rows]
Note:
To modify table data we use UPDATE
To modify table structure we use ALTER
ALTER:
• ALTER => Change
Syntax:
Example on ALTER:
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)
DESC student
Output:
NAME TYPE
DESC student
Output:
NAME TYPE
-----------------------------------------
SID NUMBER(4)
SNAME VARCHAR2(10)
M1 NUMBER(3)
M2 NUMBER(3)
MATHS NUMBER(3)
NOTE:
DROP COLUMN can drop one column only
DROP can drop one or multiple columns. For DROP parenthesis are
mandatory.
DESC student
Output:
NAME TYPE
-----------------------------------------
SID NUMBER(4)
ORACLE 730AM JUNE 2024 Page 92
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)
---------------
KIRAN 5
NARESH 6 we can decrease up to 6
SAI 3
AMAR 4
DESC student
Output:
NAME TYPE
-----------------------------------------
SID CHAR(7)
SNAME VARCHAR2(20)
Note:
To modify the data type column must be empty.
FLASHBACK RESTORE
DELETE
PURGE
DROP:
• DROP command is used to delete the table.
• When table is dropped, it will be moved to RECYCLEBIN.
Syntax:
DROP TABLE <table_name> [PURGE];
Example:
DROP TABLE student;
--it will be moved to recyclebin
FLASHBACK:
• FLASHBACK command introduced in ORACLE 10g version.
• It is used to restore the dropped table from RECYCLEBIN.
Syntax:
FLASHBACK TABLE <table_name> TO BEFORE DROP
[RENAME TO <new_name>];
Example:
FLASHBACK TABLE student TO BEFORE DROP;
PURGE:
• PURGE command introduced in ORACLE 10g version.
• It is used to delete the table from RECYCLEBIN.
• If table purged, it will be deleted permanently.
Syntax:
PURGE TABLE <table_name>;
Example:
PURGE TABLE student;
to see RECYCLEBIN:
SHOW RECYCLEBIN
PURGE RECYCLEBIN;
CASE-1:
FLASHBACK TABLE t1
TO BEFORE DROP;
--it restores recently dropped t1 8:35
Note:
Within SCHEMA, table name must be unique.
CASE-2:
CREATE TABLE t3(f1 INT);
DCL:
• DCL => Data Control Language.
• It deals with data accessibility.
• It is used to implement table level security.
GRANT:
• It is used to grant permission on DB Objects to
other users.
privileges_list
------------------------
Syntax:
privilege => permission
GRANT <privileges_list>
ON <DB_Object>
SELECT
TO <users_list>;
INSERT
UPDATE
DELETE
REVOKE:
ALTER
• REVOKE command is used to cancel the
.
permissions on db objects from other users.
.
Syntax:
REVOKE <privileges_list>
ON <DB_Object>
FROM <users_list>;
Examples:
GRANT select
ON emp
TO 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 select
ON emp
FROM c##userA;
ORACLE 730AM JUNE 2024 Page 100
FROM c##userA;
REVOKE select
ON emp
FROM c##userA;
REVOKE all
ON emp
FROM c##userA, c##userB, c##userC;
REVOKE all
ON emp
FROM public;
Login as DBA:
username: system
password: naresh
T1
F1 F2
1 A
2 B
CREATE TABLE t1
(
f1 NUMBER(4),
f2 VARCHAr2(10)
);
GRANT select
ON t1
TO c##userB;
COMMIT;
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 all
ON t1
FROM c##userB;
USER_TAB_PRIVS_MADE
USER_TAB_PRIVS_RECD
USER_TAB_PRIVS_MADE:
• it is a system table / built-in table / readymade table.
• it maintains all the permissions which are given by
GRANTOR.
SELECT
INSERT
UPDATE
DELETE
ALTER
FLASHBACK
DEBUG
QUERY REWRITE
ON COMMIT REFRESH
READ
REFERENCES
INDEX
Copying table:
Syntax:
Examples:
EMP1
EMP
8 columns
8 columns
15 rows
15 rows
Example-2:
Syntax:
False Condition
---------------------------
CREATE TABLE <name>
1=2 FALSE
AS
'A'='B' FALSE
SELECT <columns_list>
400=500 FALSE
FROM <table_name>
WHERE <false_condition>;
Examples:
Example-2:
EMP EMP4
8 columns EMPNO ENAME SAL
15 rows no rows
Copying Records:
Syntax:
Examples:
EMP EMP5
8 columns copy 4 columns => empno, ename, job, sal
15 rows no rows
EMP EMP5
8 columns EMPNO ENAME JOB SAL
15 rows copy no rows
managers
ORACLE 730AM JUNE 2024 Page 110
8 columns EMPNO ENAME JOB SAL
15 rows copy no rows
managers
INSERT ALL:
• Introduced in ORACLE 9i.
• INSERT ALL command is used to copy one table
data to multiple tables.
• It avoids of writing multiple INSERT commands.
• It can be used to perform ETL operations.
• E=> Extract, T => transfer, L => Load
• INSERT ALL can be used in 2 ways. They are:
○ Unconditional INSERT ALL
○ Conditional INSERT ALL
Syntax:
INSERT ALL
INTO <table_name>(<columns_list>) VALUES(<values_list>)
INTO <table_name>(<columns_list>) VALUES(<values_list>)
.
.
<SELECT QUERY>;
EMP6
4 columns => empno, ename, job, sal
no rows
EMP copy
ORACLE 730AM JUNE 2024 Page 112
EMP6
4 columns => empno, ename, job, sal
no rows
EMP copy
8 columns
15 rows
copy EMP7
4 columns => empno, ename, job, sal
no rows
copy
EMP8
4 columns => empno, ename, job, sal
no rows
INSERT ALL
ORACLE 730AM JUNE 2024 Page 113
INSERT ALL
INTO emp6 VALUES(empno, ename, job, sal)
INTO emp7 VALUES(empno, ename, job, sal)
INTO emp8 VALUES(empno, ename, job, sal)
SELECT empno,ename,job,sal FROM emp;
Output:
45 rows created.
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 => empno,ename,job,sal
8 columns
no rows
15 rows copy
MANAGER
CLERK emp_clerk
copy
ANALYST 4 => empno,ename,job,sal
SALESMAN no rows
PRESIDENT
copy
emp_others
ORACLE 730AM JUNE 2024 Page 114
SALESMAN no rows
PRESIDENT
copy
emp_others
4 => 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 * FROM emp;
dept10
EMP
empno ename sal deptno
8 cols
no rows
15 rows copy
deptno 10
deptno 20 dept20
copy
deptno 30 empno ename sal deptno
deptno 40 no rows
copy
dept_others
empno ename sal deptno
no rows
emp1980
WHEN hiredate BETWEEN '1-JAN-1980'
AND '31-DEC-1980' THEN
emp1981
emp_others
Head Office
Branch Office s.cid = t.cid
CUSTOMER1 s CUSTOMER2 t => replica
CID CNAME CCITY CID CNAME CCITY
1001 A ABC HYD BLR 1001 A HYD
1002 B BLR 1002 B BLR
1003 C MUM 1003 C MUM
1004 D PUN
1005 E CHN
MERGE:
• Introduced in ORACLE 9i.
• MERGE = UPDATE + INSERT
• MERGE is a combination of UPDATE and INSERT commands.
• It is used to apply one table changes to its replica.
Syntax:
COMMIT;
1004 D PUN
1005 E CHN
UPDATE customer1
SET cname='ABC', ccity='BLR'
WHERE cid=1001;
COMMIT;
TRUNCATE:
TRUNCATE
Syntax:
TRUNCATE TABLE <table_name>;
Example:
TRUNCATE TABLE customer1;
--all rows will be deleted permanently
DESC customer1
Output:
NAME
------------
CID
CNAME
CCITY
Note:
TRUNCATE deletes entire table data
ORACLE 730AM JUNE 2024 Page 120
TRUNCATE deletes entire table data
It does not delete table structure
TRUNCATE DELETE
• it is faster. • It is slower.
DATABASE
TABLESPACES
SEGMENTS
EXTENTS
BLOCKS
DATA
ORACLE 730AM JUNE 2024 Page 121
DATA
RENAME:
It is used to rename the table.
Syntax:
RENAME <old_name> TO <new_name>;
Example:
RENAME emp TO e;
Output:
Table renamed.
By default,
All DDL commands are auto committed.
All DML commands are not auto committed.
DUAL:
• DUAL is a readymade table / built-in table.
• DUAL table has 1 column and 1 row.
DESC dual
Output:
NAME TYPE
---------- -------------
DUMMY VARCHAR2(1)
In ORACLE 23AI,
SELECT 100+200; --300
Built-In Functions:
• To make our actions easier ORACLE software developers
defined some functions and placed them in ORACLE DB. These
functions are called "Built-In Functions / Predefined Functions /
Readymade Functions".
String Functions:
LOWER():
• It is used to convert string to lower case.
Syntax:
Lower(<string>)
Examples:
Lower('RAJU') raju
Lower('RAJ KUMAR') raj kumar
upper():
• it is used to convert string to upper case.
Syntax:
upper(<string>)
Examples:
upper('raju') RAJU
upper('ravi teja') RAVI TEJA
Syntax:
initcap(<string>)
Example:
initcap('RAJ KUMAR VARMA') Raj Kumar Varma
Examples:
LOWER(ENAME) SAL
----------------------------------------------------
smith 800
allen 1600
ENAME SAL
----------------------------------------------------
smith 800
allen 1600
ENAME lower(ename)='blake'
-------------- ---------------------------------------
SMITH lower('SMITH') => smith = blake F
ALLEN lower('ALLEN') => allen = blake F
BLAKE lower('BLAKE') => blake = blake T
UPDATE emp
SET ename=lower(ename);
length():
• it is used to find length of the string.
• string length => no of chars in string.
Syntax:
length(<string>)
Examples:
length('RAJU') 4
length('RAVI TEJA') 9
(or)
Concat():
• 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
'RAJ' || ' ' || 'KUMAR' || ' ' || 'VARMA' RAJ KUMAR VARMA
Example:
EMPLOYEE
EMPID FNAME LNAME ENAME
1234 SAI KRISHNA ------------
1235 RAVI TEJA Sai Krishna
Ravi Teja
UPDATE employee
SET ename= Initcap(fname || ' ' || lname);
Syntax:
Substr(<string>, <position> [, <no_of_chars>])
Examples:
1 2 3 4 5 6 7 8 9
R A J K U M A R
1 2 3 4 5 6 7 8 9
R A J K U M A R
-9 -8 -7 -6 -5 -4 -3 -2 -1
your password:
your name's first 4 chars
your mobile number's last 4 digits
VIJA6789
Generate mail ids to all emps by taking emp name's first 3 chars,
empno's last 3 digits as user name for the domain tcs.com:
EMP MAIL_ID
EMPNO ENAME --------------------
7369 SMITH [email protected]
[email protected]
7499 ALLEN
UPDATE emp
SET mail_id = Substr(ename,1,3) || Substr(empno,-3,3) || '@tcs.com';
SELECT *
FROM emp
WHERE Substr(ename,1,1)='S';
(or)
SELECT *
FROM emp
WHERE ename LIKE 'S%';
SELECT *
ORACLE 730AM JUNE 2024 Page 131
SELECT *
FROM emp
WHERE substr(ename,1,1) IN('A','E','I','O','U');
Lpad():
it is used to fill specified char set at left side.
Syntax:
Lpad(<string>, <size> [, <char_set>])
Rpad():
it is used to fill specified char set at right side.
Syntax:
Rpad(<string>, <size> [, <char_set>])
Examples:
Example:
Display output as following if acno is 1234567891:
amount debited from acno XXXXXX7891
Ltrim():
• It is used to remove unwanted chars from left side
Syntax:
Ltrim(<string> [, <char_set>])
Rtrim():
• It is used to remove unwanted chars from right side
Syntax:
Rtrim(<string> [, <char_set>])
Trim():
ORACLE 730AM JUNE 2024 Page 133
Trim():
It can be used to remove unwanted chars from left side or right side
or both sides.
Syntax:
Trim(leading / trailing / both <char> from <string>)
Examples:
Trim(leading '*' FROM '*****RAJU*****') RAJU*****
Trim(trailing '*' FROM '*****RAJU*****') *****RAJU
Trim(both '*' FROM '*****RAJU*****') RAJU
Trim(' RAJU ') RAJU
Instr():
• It is used to check whether the sub string is existed in string or
not.
• If sub string existed in string, it returns position number.
If sub string is not existed I string, it returns 0.
Syntax:
Instr(<string>, <sub_string> [, <position>, <occurrence>])
1 2 3 4 5 6 7 8 9
R A V I T E J A 3rd arg default position 1
4th arg default occurrence 1
Examples:
Instr('RAVI TEJA', 'TEJA') 6
Instr('RAVI TEJA', 'RAVI') 1
Instr('RAVI TEJA', 'I TE') 4
Instr('RAVI TEJA', 'SAI') 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:
EMP60
FNAME LNAME
EMPID ENAME
RAJ KUMAR
1234 RAJ KUMAR
VIJAY KUMAR
1235 VIJAY KUMAR
SAI KRISHNA
1236 SAI KRISHNA
UPDATE emp60
SET fname=Substr(ename, 1, Instr(ename, ' ')-1),
lname= Substr(ename, Instr(ename, ' ')+1);
COMMIT;
(or)
(or)
(or)
(or)
Replace():
It is used to replace search string with replace string.
Syntax:
Repalce(<string>, <search string>, <replace string>)
Examples:
Replace('SAI KRISHNA', 'SAI', 'RAVI') RAVI KRISHNA
Replace('SAI KRISHNA SAI TEJA', 'SAI', 'RAVI') RAVI KRISHNA RAVI TEJA
Translate():
• it is used to replace the characters.
Syntax:
Translate(<string>, <search_char_set>, <replace_char_set>)
Examples:
S => X
A => Y
I => Z
Normal Text
Normal Text Cipher Text
Encryption Decryption
Reverse():
Syntax:
Reverse(<string>)
Example:
Reverse('SAI') IAS
ASCII():
It returns ASCII value of specified char
Syntax:
ASCII(<char>)
Examples:
ASCII('A') 65
ASCII('Z') 90
ASCII('a') 97
Chr():
• It returns character of specified ASCII value.
Examples:
Chr(65) A
Chr(97) a
Soundex():
• It is used to retrieve the data based on sounds.
Syntax:
Soundex(<string1>) = Soundex(<string2>)
Examples:
to_date() to_number()
Syntax:
To_Char(<date>, <format>)
1 => jan-mar
2 => apr-jun
3 => jul-sep
4 => oct-dec
MI minutes part
SS seconds part
FF fractional seconds
AM / PM AM or PM
Display the emp records who joined in JAN, MAY and DEC:
(or)
to_char(hiredate,'DAY')
SUNDAY3spaces 9
TUESDAY2spaces 9
WEDNESDAY 9 max str length
.
.
SATURDAY1space 9
RTRIM(SUNDAY3spaces)
SUNDAY = SUNDAY TRUE
Syntax:
To_Char(<number> [, <format> , <NLS_parameters>])
Examples:
To_Char(123) '123'
To_Char(123.45) '123.45'
FORMAT PURPOSE
L currency symbol [$]
C currency name [USD]
./D Decimal Point
,/G Thousand separator
9 Digit
To_Date():
• It is used to convert string to date.
Syntax:
To_Date(<string> [, <format>])
Examples:
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
ORACLE 730AM JUNE 2024 Page 145
To_Date('25/12/2023', 'DD/MM/YYYY') 25-DEC-23
Example:
F1 implicit conversion
-------
25-DEC-23 date
Note:
implicit conversion degrades the performance
F1
-------
27-OCT-23 date
/
Enter value for d: 17
Enter value for m:2
Enter value for y:2021
To_Number():
• It is used to convert string to number.
• String must be numeric string only.
Syntax:
To_Number('123') 123
To_Number('123.45') 123.45
ORACLE 730AM JUNE 2024 Page 147
To_Number('123.45') 123.45
To_Number('$5000.00') ERROR
To_Number('$5000.00', 'L9999.99') 5000
F1 sum(f1) 10+20+30 = 60
----- avg(f1) 60/3 = 20
10
max(f1) 30
20
30 min(f1) 10
count(*) 3
sum():
• it us 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:
max():
It is used to find max value in a set of values.
Syntax:
max(<column>)
Examples:
min():
It is used to find min value in a set of values.
Syntax:
Examples:
count():
• it is used to find number of records or number of
column values.
Syntax:
count(* / <column>)
Examples:
Note:
to find number of records we can write following
queries:
Built-In Functions
power() Mod()
sqrt() Ceil()
ORACLE 730AM JUNE 2024 Page 151
power() Mod()
sqrt() Ceil()
sign() Floor()
abs() Trunc()
Round()
power():
• it is used to find power value.
Syntax:
power(<number>, <power>)
Examples:
power(2,3) 8
power(3,2) 9
sqrt():
it is used to find square root value.
Syntax:
sqrt(<number>)
Examples:
sqrt(100) 10
sqrt(25) 5
sign():
• it is used to check whether the number
is +ve or -ve or 0.
• if num is +ve, returns 1
• if num is -ve, returns -1
• if num is 0, returns 0
Syntax:
sign(<number>)
Examples:
sign(25) 1
sign(-25) -1
sign(0) 0
abs():
Syntax:
abs(<number>)
Examples:
abs(25) 25
abs(-25) 25
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:
Floor() Ceil()
456 => 456.789 => 457
Ceil(456.789) 457
Floor(456.789) 456
TRUNC():
it is used to remove decimal places.
ORACLE 730AM JUNE 2024 Page 153
• it is used to remove decimal places.
Syntax:
TRUNC(<number> [, <no_of_decimal_places>])
Examples:
TRUNC(123.6789) 123
TRUNC(123.6789,1) 123.6
TRUNC(123.6789,2) 123.67
TRUNC(123.6789,3) 123.678
-1 rounds in 10s
-2 rounds in 100s
-3 rounds in 1000s
Round():
• It considers avrg.
• If value is avrg or above avrg, it gives upper value.
• if value is below avrg, it gives lower value.
Syntax:
Round(<number> [, <no_of_decimal_places>])
Examples:
Round(123.6789) 123 and 124
avrg: 123.5
124
Trunc(123.6789) 123
Round(123.3789) 123 and 124
avrg: 123.5
123
Trunc(123.3789) 123
Round(456.6789,2) 456.68
Trunc(456.6789,2) 456.67
Round(456.6739,2) 456.67
Round(345.678923,3) 345.679
TRUNC(345.678923,3) 345.678
Date Functions:
sysdate
systimestamp
Add_Months()
Months_Between()
Last_day()
Next_day()
Syntax:
sysdate
systimestamp:
• it returns current system date and time
Syntax:
systimestamp
Add_Months():
• it is used to add or subtract months to specific
date or from specific date.
Syntax:
Add_Months(<date>, <no_of_months>)
Examples:
Orders
Order_id cid pid ordered_Date delivery_Date
1234 .. .. sysdate sysdate+5
Products
Pid Pname manufactured_date expiry_date
5001 XYZ sysdate Add_Months(sysdate,3)
EMPLOYEE
EMPID ENAME DOBirth DORetirement
1001 A 25-DEC-2000 Add_months(DOBirth, 60*12)
CMS_LIST
STATE_CODE CM_NAME START_DATE END_DATE
TG RR 7-DEC-23 Add_Months(start_Date, 5*12)
Examples:
COMMIT;
Output:
no rows selected.
Output:
displays emp records who joined today
NOTE:
TRUNC() function can be used to remove time from date and time.
TRUNC(SYS
---------
12-JUL-24
Assignment:
GOLDRATES
dateid price find today's goldrate:
1-JAN-2020 45000
2-JAN-2020 48000 WHERE trunc(dateid) = trunc(sysdate)
..
find yesterday's goldrate:
..
12-JUL-24 68000 find 1 month ago goldrate:
SALES
DATEID AMOUNT find today's sales
1-JAN-2020 90000
2-JAN-2020 85000 find yesterday sales
..
find 1 month ago sales
..
12-JUL-24 95000 find 1 year ago sales
Months_Between():
• It is used to find difference between 2 dates.
Example:
Months_Between('12-JUL-24', '12-JUL-23') 12 [months]
Months_Between('12-JUL-24', '12-JUL-23')/12 1 [year]
(or)
15 months
30 months
years months
TRUNC(15/12) = 1 Mod(15,12) = 3
TRUNC(30/12) = 2 Mod(30,12) = 6
Assignment:
Find age of SACHIN if DOB is: 24-APR-1973
TRUNC(Months_Between(sysdate, '24-APR-1973')/12)
Last_day():
it is used to get last date in the month.
Syntax:
Last_day(<Date>)
Examples:
Last_day(sysdate) 31-JUL-24
Last_day('17-FEB-2024') 29-FEB-24
Last_day('17-FEB-2023') 28-FEB-23
31-JUL-24 + 1
1-AUG-24
1-JUL-24
Next_Day():
• it is used to find next date based on weekday.
• For example, to find next Sunday date we use it.
Syntax:
Next_day(<date>, <weekday_name>)
Examples:
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)
(or)
5000 18-AUG-1990 1
3000 25-DEC-1981 2
3000 23-OCT-1982 3
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
according to specific column
Row_Number():
• it is used to apply row numbers to records
Syntax:
Row_Number(PARTITION BY <column>
ORDER BY <column> ASC/DESC)
Examples:
Special Functions:
NVL()
NVL2()
Greatest()
Least()
Decode()
User
Uid
NVL():
• It is used to replace the nulls.
• If first argument is not null, it returns first argument.
• If first argument is null, it returns 2nd argument.
Syntax:
NVL(<arg1>, <arg2>)
Examples:
NVL(100,200) 100
NVL(null,200) 200
Examples on NVL():
Assignment:
STUDENT
SID SNAME M1
1001 A 60
1002 B
1003 C 75
1004 D
NVL(to_char(m1), 'ABSENT')
NVL2():
• It is used to replace nulls and not nulls.
• If arg1 is not null, it 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
Example on NVL2():
UPDATE emp
SET comm=NVL2(comm, comm+1000, 900);
Greatest():
• It is to find max value in horizontal values.
Syntax:
Greatest(<value1>, <v2>, <v3>, …….. , <value_n>)
Examples:
Greatest(10,20,30) 30
Greatest(6,5,8,7,3,2,4) 8
T1
greatest(f1, f2, f3)
F1 F2 F3
------------------------------
45 78 60 greatest(45, 78, 60) => 78
74 32 81 greatest(74, 32, 81) => 81
30 55 77 greatest(30, 55, 77) => 77
F3
60 max(f3)
81
77
Least():
• it is used to find minimum value in horizontal values.
• single row function
• it can take variable length arguments
Min():
• it is used to find minimum value in vertical values.
• multi row function.
• it can take 1 argument
User:
• it returns current user name
show user
Uid:
(or)
• it returns current user id
select user from dual;
Example:
SELECT user, uid FROM dual;
Syntax:
Decode(<column>,
<value1>, <expression1>,
<value2>, <expression2>,
.
.
[else_epression>)
Example on Decode():
SELECT ename,
decode(job,
'PRESIDENT', 'BIG BOSS',
'MANAGER', 'BOSS',
'EMPLOYEE') AS job,
sal
FROM emp;
UPDATE emp
SET sal=decode(deptno,
10, sal+sal*0.1,
20, sal+sal*0.2,
sal+sal*0.15);
SQL ENGLISH
QUERIES SENTENCES
CLAUSES WORDS
Syntax:
SELECT <columns_list>
Examples:
SELECT ename, sal
SELECT *
* All columns
FROM:
• It is used to specify tables list
• it selects entire table
Syntax:
FROM <tables_list>
Examples:
FROM emp
FROM emp, dept
WHERE:
• it is used to specify filter condition
• it filters the rows
Syntax:
WHERE <condition>
Examples:
WHERE job='MANAGER'
WHERE deptno=30
EMP
EMPNO ENAME SAL
1234 A 7000
1235 B 2500
1236 C 5000
1237 D 2000
FROM emp:
it selects entire emp table
EMP
EMPNO ENAME SAL
1234 A 7000
1235 B 2500
1236 C 5000
1237 D 2000
WHERE sal>3000:
○ it filters the rows
○ WHERE condition will be applied on every row
ENAME SAL
A 7000
C 5000
ORDER BY:
• It 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, ….
Example:
1 10
A Z 1-JAN-23 31-DEC-24
2 9
B Y 2-JAN-23 30-DEC_24
3 8
. . . .
. .
. . . .
. .
Z A 31-DEC-23 1-JAN-24
10 1
1-JAN-24 31-DEC-23
. .
. .
31-DEC-24 1-JAN-23
(or)
(or)
(or)
SELECT *
FROM emp
ORDER BY 2 ASC;
(or)
SELECT *
FROM emp
ORDER BY empno ASC;
clear breaks
20 10
10 20
10 4000 10 6000
10 6000 10 4000
Note:
In ASCENDING ORDER, nulls will be displayed last.
In DESCENDING ORDER, nulls will be displayed first.
GROUP BY:
• It is used to group the records according to specific
column(s).
• On these groups we can apply aggregate functions.
• It gives summarized data from detailed data.
• It can be used for data analysis.
Syntax:
GROUP BY <columns_list>
Example:
GROUP BY deptno
EMP => detailed data summarized data
EMPNO ENAME DEPTNO SAL deptno sum_of_Sal
1001 A 30 10000 10 30000
1002 B 30 5000 20 20000
1003 C 10 20000 30 15000
1004 D 10 10000
1005 E 20 12000
1006 F 20 8000
DEPTNO SUM_OF_SAL
10 ?
20 ?
30 ?
DEPTNO NO_OF_EMPS
ORACLE 730AM JUNE 2024 Page 179
DEPTNO NO_OF_EMPS
10 ?
20 ?
30 ?
DEPTNO AVG_SAL
10 ?
20 ?
YEAR NO_OF_EMPS
1980 ?
1981 ?
1982 ?
QUARTER NO_OF_EMPS
1 ?
2 ?
3 ?
4 ?
Assignment:
Find week day wise no of emps joined in org
WEEKDAY NO_OF_EMPS
1 ?
2 ?
ORACLE 730AM JUNE 2024 Page 181
2 ?
3 ?
JOB SUM_OF_SAL
MANAGER ?
CLERK ?
SALESMAN ?
Assignment:
Find job wise no of emps
JOB NO_OF_EMPS
CLERK ?
MANAGER ?
gender population
M ?
F ?
Rollup():
It calculates sub totals and grand total according to
first column in GROUP BY columns list
Syntax:
GROUP BY ROLLUP(<grouping_columns_list>)
Example:
GROUP BY Rollup(deptno, job)
Cube():
It calculates sub totals and grand total according to
all columns in GROUP BY columns list
Syntax:
ORACLE 730AM JUNE 2024 Page 184
Syntax:
GROUP BY CUBE(<grouping_columns_list>)
Example:
GROUP BY Cube(deptno, job)
Assignment:
SALES
DATEID AMOUNT
1-JAN-2022 80000
2-JAN-2022 70000
..
..
18-JUL-2024 90000
Sum (Amount)
GROUP BY CUBE(to_char(dateid, 'YYYY'), to_char(dateid, 'Q'))
Assignment:
PERSON
PID PNAME STATE GENDER AADHAR
TG M
TG F
TG F
TG M
AP F
AP F
AP M
AP M
HAVING:
• HAVING clause is used to write conditions on groups.
• It will be applied on result of GROUP BY.
• It cannot be used without GROUP BY.
• It filters the groups.
Syntax:
HAVING <group_condition>
Examples on HAVING:
WHERE HAVING
FROM
WHERE
GROUP BY
HAVING
SELECT
DISTINCT
ORDER BY
OFFSET
FETCH
OFFSET:
• introduced in ORACLE 12C.
it is used to specify no of rows to be skipped.
Syntax:
OFFSET <number> ROW/ROWS
FETCH:
• introduced in ORACLE 12C.
• it is used to specify no of rows to be fetched.
Syntax:
FETCH <FIRST/NEXT> <number> ROW/ROWS ONLY
DISTINCT:
• it is used to eliminate duplicate records.
Syntax:
SELECT ALL/DISTINCT <columns_list>
Examples on DISTINCT:
JOB JOB
-------- -----------
CLERK CLERK
SALESMAN SALESMAN
MANAGER MANAGER
SALESMAN
MANAGER
CLERK
CLERK
MANAGER
MANAGER
SALESMAN
YEAR NO_OF_EMPS
1980 ?
1981 ?
Output:
ERROR: YEAR invalid IDENTIFIER
FROM
WHERE Till oracle 21c,
GROUP BY we cannot use column alias in GROUP BY,
HAVING HAVING and WHERE.
SELECT
DISTINCT In oracle 23AI,
ORDER BY we can use column alias in
OFFSET GROUP BY and HAVING
FETCH
NOTE:
• When we use group function, SELECT clause
allows either GROUP BY column or GROUP
FUNCTION.
10
20
ORACLE 730AM JUNE 2024 Page 196
20
30
JOINS:
GOAL:
• It is used to retrieve the data from multiple tables
COLLEGE DB
COURSE
STUDENT
MARKS
FEE
S.SID = M.SID
STUDENT S MARKS M
SID SNAME SID Maths Phy Che
1001 A 1001 70 50 60
1002 B 1002 55 44 81
1003 C 1003 39 50 47
1004 D
JOINS
JOINS:
• JOIN => combine / connect / link
• JOIN is an operation.
Types of Joins:
Inner Join:
• Inner Join can give matched records only.
• It has 2 sub types. they are:
○ Equi Join
○ Non-Equi Join
Equi Join:
• If Join Operation is performed based on
equality condition then it is called "Equi Join".
1001 70 50 60
1002 55 44 81
1003 39 50 47
Note:
From ORACLE 9i version onwards, we can write
JOIN QUERY in 2 styles. They are:
• ORACLE STYLE / NATIVE STYLE
• ANSI STYLE => best way [portable]
we can run
ORACLE STYLE:
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
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
Note:
to see execution plan write following command:
ORACLE STYLE:
ANSI STYLE:
ORACLE STYLE:
commit;
ORACLE STYLE:
ANSI STYLE:
Inner Join:
• Inner Join = matched records only
• Inner Join can give matched records only.
Outer Join:
• Outer Join = matched + unmatched records
• 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.
• LHS table => left table
• RHS table => right table
Examples:
WHERE e.deptno = d.deptno
Examples:
WHERE d.deptno = e.deptno
Example:
FROM emp e INNER JOIN dept d
• In ORACLE STYLE,
For Left Outer Join we write (+) symbol at right side.
• In ANSI STYLE,
For Left Outer Join use the keyword: LEFT [OUTER] JOIN
COMMIT;
ORACLE STYLE:
ANSI STYLE:
ORACLE STYLE:
ANSI STYLE:
• Full Outer Join = matched + unmatched from left and right tables
In SQL:
• In ANSI style, we use keyword: FULL [OUTER] JOIN
ORACLE STYLE:
ANSI STYLE:
Example:
Display the emps to whom dept is not assigned.
ENAME SAL DNAME LOC
EMP e DEPT d
ORACLE STYLE:
ANSI STYLE:
Example:
Display the depts which are not having emps.
ENAME SAL DNAME LOC
ORACLE STYLE:
ANSI STYLE:
Example:
ORACLE STYLE:
ANSI STYLE:
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
EMP e SALGRADE s
EMPNO ENAME SAL GRADE LOSAL HISAL
1001 A 1500 1 700 1200
1002 B 5000 2 1201 1400
1003 C 1300 3 1401 2000
1004 D 1000 4 2001 3000
1005 E 5 3001 9999
ORACLE STYLE:
ANSI STYLE:
Example:
e.mgr = m.empno
EMP e EMP m
EMPNO ENAME JOB SAL MGR EMPNO ENAME JOB SAL MGR
1001 A MANAGER 20000 1001 A MANAGER 20000
1002 B CLERK 8000 1001 1002 B CLERK 8000 1001
1003 C ANALYST 6000 1001 1003 C ANALYST 6000 1001
1004 D MANAGER 25000 1004 D MANAGER 25000
1005 E CLERK 9000 1004 1005 E CLERK 9000 1004
ORACLE STYLE:
ANSI STYLE:
Display the emp records who are earning more than their
manager:
EMP_NAME EMP_SAL MGR_NAME MGR_SAL
ORACLE STYLE:
ANSISTYLE:
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}
AXB = ? 2
5
3
AXB = { (1,4)(1,5)
(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
WIND VS SL
WIN VS NZ
ORACLE STYLE:
ANSI STYLE:
JOINS:
• JOIN is an operation.
• one table record will be joined with another table record based on join
condition.
• GOAL:
to retrieve data from multiple tables
Types Of Joins:
Natural Join:
Equi Join without duplicate columns
SELECT *
FROM emp e NATURAL JOIN dept d;
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
Sub Queries:
Syntax:
SELECT <columns_list>
FROM <tables_list>
WHERE <column> <operator> (<SELECT QUERY>);
Display the emp records who are earning more than BLAKE:
BLAKE 2850
SELECT max(sal)
SAL
FROM emp
----------
WHERE sal<6000;
4000
3000
5000
4000
6000 max sal => 5000
3000
2000 2nd max sal
5000
ORACLE 730AM JUNE 2024 Page 217
4000
6000 max sal => 5000
3000
2000 2nd max sal
5000
2000
SELECT max(sal)
FROM emp
WHERE sal<(find max sal);
SELECT max(Sal)
FROM emp
WHERE sal<(SELECT max(sal) FROM emp);
3000
max sal => 4000
4000
3rd max sal
2500
2000
SAL
------- SELECT max(sal) FROM emp
3000 WHERE sal<(SELECT max(sal) FROM emp
6000 WHERE sal<(SELECT max(sal) FROM emp));
4000
5000
2500
2000
Assignment:
• Find the deptno which is having max no of emps
• Find the dept name which is having max no of emps
SAL sal>ALL(800,2850)
ORACLE 730AM JUNE 2024 Page 222
then condn is TRUE
SAL sal>ALL(800,2850)
----------
1500 1500 F
3000 3000 T
2500 2500 F
6000 6000 T
Output:
enter .. n: 2
--displays 2nd max sal
ROWNUM
ROWID ROWNUM => pseudo column
ROW_NUMBER() => analytic function
ROWNUM:
• It is a pseudo column.
• It is used to apply row numbers to records.
• Always row numbers will be applied on result
of SELECT query.
Examples on ROWNUM:
SELECT *
FROM (SELECT rownum as rn, ename, sal
FROM emp)
WHERE rn=3;
Display 1st row, 5th row and 11th row from emp table:
SELECT *
FROM (SELECT rownum as rn, ename, sal
FROM emp)
WHERE rn IN(1,5,11);
SELECT *
FROM (SELECT rownum as rn, ename, sal FROM emp)
WHERE rn BETWEEN 6 AND 10;
SELECT *
FROM (SELECT rownum as rn, ename, sal FROM emp)
WHERE MOD(rn,2)=0;
Syntax:
SELECT (<sub query>)
FROM <table_name>
WHERE <condition>;
Output:
EMP DEPT
-------- --------
14 4
selects a row
1 3
2 passes value
Outer Inner
4 passes value
Example:
Display the emp records who are earning more than their dept's avrg
salary:
Display the emp records who are earning max salary in each dept:
EMP e
EMPID ENAME DEPTNO SAL ENAME DEPTNO SAL
1001 A 10 12000 A 10 12000
1002 B 10 8000 D 20 20000
1003 C 20 10000
1004 D 20 20000
EXISTS:
Syntax:
EXISTS(<Sub Query>)
NOT EXISTS:
Syntax:
NOT EXISTS(<Sub Query>)
If sub query does not select any row then it returns TRUE.
If sub query selects the rows then it returns FALSEE.
DEPT d EMP e
DEPTNO DNAME EMPID ENAME DEPTNO SAL
10 ACCOUNTING 1001 A 10 12000
20 RESEARCH 1002 B 10 8000
30 SALES 1003 C 20 10000
ORACLE 730AM JUNE 2024 Page 232
10 ACCOUNTING 1001 A 10 12000
20 RESEARCH 1002 B 10 8000
30 SALES 1003 C 20 10000
1004 D 20 20000
DNAME
ACCOUNTING
RESEARCH
UPDATE emp
SET sal=(find 30th dept max sal)
WHERE ename='JAMES';
UPDATE emp
SET sal=(SELECT max(Sal) FROM emp WHERE deptno=30)
WHERE ename='JAMES';
CONSTRAINT:
• CONSTRAINT => Restrict / Limit / Control
M1 NUMBER(3)
------
70
123 ERROR
CHECK(gender IN('M','F'))
GENDER
---------------
M
F
Z ERROR
CONSTRAINTS:
Primary Key:
• It does not accept duplicates.
• It does not accept nulls.
• When value is mandatory and should not be duplicated then we
use PRIMARY KEY.
• A table can have only one primary key.
Example:
Employee
PK
EMPID ENAME JOB SAL
1234 SAI CLERK 8000
1235 KIRAN CLERK 6000
1236 SAI SALESMAN 8000
null
A MANAGER 12000 ERROR
1234 RAJU CLERK 7000 ERROR
duplicate
T1
F1 Number(4) PK
CREATE TABLE t1
(
f1 NUMBER(4) PRIMARY KEY
);
T2
F1 NUMBER(4) PK
F2 VARCHAR2(10) PK
It is not possible.
A table can have one primary key only
Not Null:
○ It does not accept nulls.
○ It accepts duplicates.
○ When value is mandatory and it can be duplicates
then use NOT NULL.
Example:
EMPLOYEE
NOT NULL
EMPID ENAME SAL
1234 SAI 7000
1235 SAI 6000
1236 8000 ERROR
null
Example:
CREATE TABLE t3
(
f1 NUMBER(4) NOT NULL
);
UNIQUE:
• It does not accept duplicates.
• It accepts nulls.
• When value is optional and it should not be
duplicated then use UNIQUE.
• We can insert multiple nulls also.
Example:
CUSTOMER UNIQUE
UNIQUE
CID CNAME MOBILE_NUMBER MAIL_ID
------------------
1234 A 9123456789
[email protected]
1235 B null
1236 C 9123456789 ERROR [email protected] ERROR
Example:
CREATE TABLE t4
(
f1 NUMBER(4) UNIQUE
);
Check:
• It is used to apply our own condition on column
Example:
STUDENT
CHECK(m1 BETWEEN 0 AND 100)
SID SNAME M1
1234 A 78
1235 B 345 ERROR
Default:
• It is used to apply default value to column.
• When for almost all records value is same then we set default value
for that column.
Example:
Example:
COURSE STUDENT
PK FK
CID CNAME REFERENCES COURSE(CID)
10 JAVA SID SNAME CID
20 C# 1001 A 20
30 HTML 1002 B 20
1003 C 10
1004 D 30
1005 E
1006 F 90 ERROR
Examples on constraints:
Example-1:
USERSINFO
USERID UNAME PWD
Example-2:
STUDENT
SID SNAME M1
Example-3:
EMPLOYEE
EMPID ENAME GENDER SAL
Example-4:
STUDENT1
SID SNAME CNAME CCITY FEE
SID PK
SNAME NOT NULL
CNAME DEFAULT 'NARESH'
CCITY DEFAULT 'HYD'
20000.00
FEE DEFAULT 20000
Example-5:
NOTE:
PK column data type and FK column data type
must be same
Assignment:
Example:
COURSE STUDENT
PK FK
CID CNAME REFERENCES COURSE(CID)
SID SNAME CID
ORACLE 730AM JUNE 2024 Page 243
COURSE STUDENT
PK FK
CID CNAME REFERENCES COURSE(CID)
10 JAVA SID SNAME CID
20 C# 1001 A 20
30 HTML 1002 B 20
1003 C 10
1004 D 30
1005 E
1006 F 90 ERROR
Naming Constraints:
• To identify every constraint uniquely name is required.
• We can give names to constraints.
• If we don't define constraint name implicitly ORACLE defines
a constraint name.
• To define constraint name we use CONSTRAINT keyword
Example:
STUDENT5
SID SNAME M1
SID PK c1
SNAME
M1 CHECK => must be b/w 0 to 100 c2
USER_CONSTRAINTS:
• it maintains all constraints info
SID PK c3
SNAME NOT NULL c4
M1 CHECK c6
STUDENT7
SID SNAME M1
SID PK c7
SNAME NOT NULL c8
M1 CHECK c9
Example:
COURSE5 STUDENT5
PK FK
CID CNAME REFERENCES COURSE5(cid)
10 JAVA SID SNAME CID
20 PYTHON 1001 A 20
30 C# 1002 B 20
1003 C 10
1004 D 90 ERROR
2 reasons:
Example:
STUDENT
PK(SID, SUBJECT)
SID SNAME SUBJECT MARKS
1001 A M1 70
1001 A M2 65
1002 B M1 55
1002 B M2 70
1003 C M1 80
1003 C M2 45
1001 M1 ERROR
PRODUCTS
PID PNAME MANUFATURED_DATE EXPIRY_DATE
1001 A 1-AUG-24 25-DEC-23
CHECK(expiry_date>manufactured_date)
Syntax of ALTER:
Example:
STUDENT
SID SNAME M1
Add PK to sid:
ALTER TABLE student ADD CONSTRAINT c15 PRIMARY KEY(sid);
Note:
Using ADD keyword we can add Table Level Constraints only.
Using MODIFY keyword we can add all Column Level Constraints.
Disabling Constraint:
ALTER TABLE student DISABLE CONSTRAINT z;
Enabling Constraint:
ALTER TABLE student ENABLE CONSTRAINT z;
Dropping Constraint:
ALTER TABLE student DROP CONSTRAINT z;