You are on page 1of 27

Database :-

=> a Database is a organized collection of interrelated data.For


example a univ db stores data related to students,courses,facutly
etc and bank db stores data related to customers,transactions
and loans.

Types of Databases :-
----------------------

1 OLTP DB (online transaction processing)


2 OLAP DB (online analytical processing)

=> organizations uses OLTP for storing day-to-day transactions


and OLAP for analysis.

=> OLTP is used to run business and OLAP is used to analyze business.

=> day-to-day operations on db includes

C create
R read
U update
D delete

DBMS :- (Database Management System)

=> it is a software used to create and to manage database.


=> DBMS is an interface between user and database.

Evolution of DBMS :-
---------------------

1960 FMS (File Mgmt System)

1970 HDBMS (Hierarchical DBMS)


NDBMS (Network DBMS)

1980 RDBMS (Relational DBMS)

1990 ORDBMS (Object Relational DBMS)


OODBMS (Object Oriented DBMS)

RDBMS :- (Relational Database Mgmt System)


---------

=> RDBMS concepts are introduced by E.F.CODD

=> according to E.F.CODD in database data must be organized in


tables i.e. rows and columns.

CUST
CID NAME ADDR => columns,fields,attributes
10 sachin mum
11 rohit del
12 ravi hyd => row,record,tuple

DATABASE = collection of tables


TABLE = collection of rows and columns
ROW = collection of field values
COLUMN = collection of values assigned to one field

=> every table must contain primary key to uniquely identity the
records.

Ex :- ACCNO,EMPID,CUSTID,AADHARNO,PANNO

=> one table is related to another table by using foreign key

ORDERS CUST
ORDID ORD_DT DEL_DT CID(FK) CID(Pk) NAME ADDR
1000 20- 25- 10 10 sachin mum
1001 21- 28- 11 11 rohit del
1002 22- 29- 12 12 ravi hyd

RDBMS features :-
-----------------

1 easy to read and manipulate data


2 less redundency (duplication of data)
3 more security
4 gurantees data integrity i.e. data quality
5 supports data sharing
6 supports transactions (ACID properties)

A atomocity
C consistency
I isolation
D durability

RDBMS softwares :- (SQL databases)


-------------------

oracle from oracle corp


sql server from Microsoft
mysql from Oracle corp
postgresql from PostgreSQL
db2 from IBM

NoSQL :-
-------

MongoDB
cassandra

ORDBMS :- (object oriented dbms)


--------------------------------

=> it is the combination of RDBMS & OOPS

ORDBMS = RDBMS + OOPS (reusability)

=> RDBMS doesn't support reusability but ordbms supports reusability

=> ORDBMS supports reusability by using ADT (abstract datatype)

RDBMS :-
CUST
CID NAME HNO STREET CITY STATE PIN

EMP
EMPID ENAME HNO STREET CITY STATE PIN

ORDBMS :-
ADT :- ADDR(HNO,STREET,CITY,STATE,PIN)

CUST
CID NAME ADDR

EMP
EMPID ENAME ADDR

summary :-

what is database ?
types of databases ?
what is dbms ?
types of dbms ?
what is rdbms ?
what is ordbms ?

---------------------------------------------------------------------

24-apr-21 ORACLE

=> ORACLE is basically rdbms product from oracle corp and also
supports features of ordbms and used to create and to manage database.

=> ORACLE can be used for both db development and administration.

Design Development Administration


ER model ORACLE ORACLE
Normalization

Development Administration

creating tables installation of oracle


creating views creating database
creating synonyms creating userids
creating indexes db backup & restore
creating sequences db upgradation & migration
creating procedures performance tuning
creating functions
creatring triggers
writing queries

versions of ORACLE :-
---------------------

Version Year New Features

Oracle v2, 1979 First commercially SQL-based RDBMS


Oracle v3, 1983 Concurrency control, data distribution, scalability
Oracle v4, 1984 Multiversion read consistency
Oracle v5, 1985 Client/server computing Support & distributed
database systems
Oracle v6, 1988 Row-level locking, scalability, online backup and
recovery, PL/SQL, Oracle Parallel Server
Oracle 7, 1992 PL/SQL stored procedures, Triggers, Shared Cursors,
Cost Based Optimizer, Transparent Application Failover
Oracle 8i, 1997 Recovery Manager, Partitioning, Dataguard, Native
internet protocols, Java, Virtual Private Database
Oracle 9i, 2001 Oracle Real Application Clusters (RAC), Oracle XML
DB, Data Mining, Streams, Logical Standby
Oracle 10gR1, 2003 Grid infrastructure, Oracle ASM, Flashback
Database, Automatic Database Diagnostic Monitor
Oracle 10gR2, 2005 Real Application Testing, Database Vault, Online
Indexing, Advanced Compression, Transparent Data Encryption
Oracle 11gR1, 2007 Active Data Guard, Secure Files, Exadata
Oracle 11gR2, 2009 Data Redaction, Hybrid Columnar Compression, Cluster
File System, Golden Gate Replication, Database Appliance
Oracle 12cR1, 2013 Multitenant architecture, In-Memory Column Store,
Native JSON, SQL Pattern Matching, Database Cloud Service
Oracle 12cR2, 2016 Native Sharding, Zero Data Loss Recovery Appliance,
Exadata Cloud Service, Cloud at Customer
Oracle 18c, 2018 Autonomous Database, Data Guard Multi-Instance Redo
Apply, Polymorphic Table Functions, Active Directory Integration
Oracle 19c 2019 Automatic Indexing, Data-guard DML
Redirect,Partitioned Hybrid Tables, Real-time Stats + Stats Only Queries

i => internet
g => grid
c => cloud

=> from 8i onwards oracle supports internet applications.

=> grid means collection of servers , from 10g onwards oracle db


can be accessed through multiple servers.so this improves
availability.

=> from 12c onwards oracle db can be deployed in

1 on premises server
2 on cloud server

=> in " on premises " db is deployed in the server managed by client.

=> in " on cloud " db is deployed in the server managed by cloud


service provider like amazon,microsoft,google etc.

26-apr-21

client/server architecture :-
-------------------------------

SERVER :-

=> server is a system where oracle software is installed and running


=> inside the server oracle manages the following two memories.

1 DB
2 INSTANCE

=> DB is created in hard disk and it acts as permanent storage.


=> INSTANCE is created in ram and it acts as temporary storage.

CLIENT :-
---------

=> client is a system where users can

1 connects to server
2 submit requests to server
3 recieves response from server

client tools :-
---------------

SQLPLUS (CUI based)


SQL DEVELOPER (GUI based)
TOAD (GUI based)

link for downloading oracle 18c :-

https://www.oracle.com/database/technologies/oracle-database-software-
downloads.html#19c

link for step by step installation :-

https://blog.toadworld.com/2018/09/26/how-to-install-oracle-database-18c-on-windows

SQL :-
-------

=> SQL stands for structured query language.


=> It is a Language used to communicate with oracle.
=> using SQL user communicates with oracle by sending commands
called queries.
=> a query is a command/instruction/question submitted to oracle
to perform some operation over database.
=> SQL is originally introduced by IBM and initial name of this
language was "SEQUEL" and later it is renamed to sql.
=> SQL is common to all rdbms

ORACLE MYSQL SQL SERVER POSTGRESQL DB2


SQL SQL SQL SQL SQL

27-arp-21

=> based on operations over db SQL is categorized into following


sublanguages.

DDL (DATA DEFINITION LANG)


DML (DATA MANIPULATION LANG)
DQL (DATA QUERY LANG)
TCL (TRANSACTION CONTROL LANG)
DCL (DATA CONTROL LANG)

SQL
DDL DML DQL TCL DCL
create insert select commit grant
alter update rollback revoke
drop delete savepoint
truncate insert all
rename merge
flashback
purge

schema :-
----------

=> a user in oracle db is called schema.


=> objects created by user are called schema objects.

SERVER
DATABASE
USERS
TABLES
DATA

SERVER
ORCL
sys dba
system/TIGER dba
scott normal user

how to connect to oracle :-


---------------------------

=> to connect to oracle open sqlplus and username & password

username :- system
password :- TIGER

OR

username :- system/TIGER

creating user/schema/account in oracle db :-


-------------------------------------------

=> only DBA can create new users

step 1 :- conn as dba

username :- system/TIGER

step 2 :- create user

syntax :-

CREATE USER <NAME> IDENTIFIED BY <PWD>


DEFAULT TABLESPACE USERS
QUOTA UNLIMITED ON USERS ;

Example :-

SQL>CREATE USER C##BATCH4PM IDENTIFIED BY ORACLE


DEFAULT TABLESPACE USERS
QUOTA UNLIMITED ON USERS ;

=> above command creates a new user but user is dummy because
user is not having permissions.

step 3 :- granting permissions to user

SQL>GRANT CONNECT,RESOURCE TO C##BATCH4PM ;

CONNECT => to connect to db


RESOURECE => to create objects like tables

28-apr-21

Datatypes in ORACLE :-
----------------------

=> datatype in oracle specifies type of the data allowed in a column


and amount of memory allocated for column.

Datatypes
CHAR NUMERIC DATE BINARY
ASCII UNICODE number(p) date bfile
char nchar number(p,s) timestamp blob
varchar2 nvarchar2
long nclob
clob

char(size) :-
-------------

=> allows character data upto 2000 chars


=> recommended for fixed length char columns

ex :- NAME CHAR(10)

vijay-----
wasted

ravi------
wasted

=> in char datatype extra bytes are wasted so char is not recommended
for variable length fields and it is recommended for fixed length
fields.

ex :- STATE_CODE CHAR(2)

AP
TS
MH

COUNTRY_CODE CHAR(3)

IND
USA
AUS

VARCHAR2(size) :-
-----------------
=> allows character data upto 4000 chars.
=> recommended for variable length fields.

ex :- NAME VARCHAR2(10)

vijay-----
released

ravi------
released

=> char/varchar2 allows ascii characters (256) that includes


a-z,A-Z,0-9,special chars.

PANNO CHAR(10)
VEHNO CHAR(10)

LONG :- allows character data upto 2GB.

CLOB :- (character large object )

=> allows character data upto 4GB.

NCHAR/NVARCHAR2/NCLOB :- ( N => National)


------------------------

=> allows unicode characters (65536) that includes all ascii


chars and chars belongs to different languages.

=> ascii char occupies 1 byte but a unicode char occupies 2 bytes.

NUMBER(p) :-
-------------

=> allows numeric data upto 38 digits.


=> allows exact numbers i.e. numbers without decimal point (integer)

ex :- EMPID NUMBER(4)

10
100
1000
10000 => not accepted

NUMBER(P,S) :-
--------------

=> allows approximate numbers i.e. numbers with decimal point.

P => precision => total no of digits allowed


S => scale => no of digits allowed after decimal

ex :- SALARY NUMBER(7,2)

5000
5000.50
50000.50
500000.50 => not accepted
5000.507 => accepted => 5000.51
5000.503 => accepted => 5000.50

=> if before decimal exceeds number is not accepts


=> if after decimal exceeds number is rounded

DATE :-
-------

=> allows date & time


=> time is optional if not entered then oracle stores 12:00 AM
=> default date format in oracle is DD-MON-YY / YYYY

EX :- DOB DATE

28-APR-21 => 28-APR-2021


19-MAR-95 => 19-MAR-2095
19-MAR-1995 => 19-MAR-1995

TIMESTAMP :-
-----------

=> allows date , time and also milliseconds

T TIMESTAMP

28-APR-21 5:03:20.123
--------- ------- ----
DATE TIME MS

diff b/w date & timestamp ?

=> date datatatype requires TO_DATE function to insert time


=> using timestamp datatype we can insert date & time without TO_DATE function

BFILE / BLOB :-
---------------

=> allows binary data that includes audio,video,images.

BFILE :- (Binary File)


--------

=> bfile is called external blob because lob stored outside db


but db stores path.

BLOB :- (Binary Large Object)


-------

=> stores multimedia objects upto 4GB.


=> BLOB is called internal lob because lob stored inside db.

29-apr-21 :-

creating tables in oracle db :-


--------------------------------

CREATE TABLE <tabname>


(
COLNAME DATATYPE(SIZE),
COLNAME DATATYPE(SIZE),
---------------------
);

Rules :-
---------

1 tabname should start with alphabet


2 tabname should not contain spaces and special chars but allows _,$
3 tabname can be upto 128 chars
4 table can have max 1000 cols
5 no of rows unlimited

emp123 valid
123emp invalid
emp 123 invalid
emp*123 invalid
emp_123 valid

Example :-

create table with following structure ?

EMP
EMPID ENAME JOB SAL HIREDATE

CREATE TABLE emp


(
empid NUMBER(4),
ename VARCHAR2(10),
job VARCHAR2(10),
sal NUMBER(7,2),
hiredate DATE
);

=> above command created table structure/definition/metadata that


includes columns,datatype and size.

DESC :- (DESCRIBE)
-------------------

=> command used to see the table structure

SYN :- DESC tabname ;

EX :- SQL>DESC emp ;

empid NUMBER(4),
ename VARCHAR2(10),
job VARCHAR2(10),
sal NUMBER(7,2),
hiredate DATE

Inserting data into table :-


----------------------------

=> "insert" command is used to insert data into table.


syn :- INSERT INTO <tabname> VALUES(V1,V2,V3,-----);

=> character and date values must be enclosed in ' '.

Ex :-

1 INSERT INTO emp VALUES(100,'suresh','clerk',4000,'01-JAN-21');


2 INSERT INTO emp VALUES(101,'vijay','manager',8000,SYSDATE);

=> above commands inserted data into instance which is created in


RAM , to save this data execute COMMIT and after executing
COMMIT data will be copied to DB which is created in hard disk.

SQL>COMMIT;

INSERTING MULTIPLE ROWS :-


--------------------------

=> we can execute insert command multiple times with different


values by using variables prefixed with "&".

SQL>INSERT INTO emp VALUES(&empid,&ename,&job,&sal,&hiredate);


enter value for empid := 102
ename :- 'ravi'
job :- 'clerk'
sal :- 5000
hiredate :- SYSDATE
1 row created

SQL>/ (previous command is reexecuted)


enter value for empid :- 103
ename :- 'vinod'
job :- 'analyst'
sal :- 8000
hiredate :- '10-MAR-2020'
1 row created

INSERTING NULLS :-
------------------

=> a null means blank or empty


=> it is not equal to 0 or space
=> nulls can be inserted in two ways

method 1 :-

SQL>INSERT INTO emp VALUES(104,'satish','',NULL,SYSDATE);

method 2 :-

SQL>INSERT INTO emp(empid,ename,hiredate)


VALUES(105,'kumar','15-APR-19');

=> remaining fields job,sal filled with nulls

30-apr-21

Displaying Data :-
------------------

=> use "SELECT" command to display data from table.


=> users can perform following operations using SELECT command.

1 PROJECT => selecting specific columns


2 SELECT => selecting specific rows
3 JOIN => displaying data from multiple tables

syntax :- SELECT columns/* FROM tablename ;

SQL = ENGLISH
queries = sentences
clauses = words

FROM clause => specify tablename


SELECT clause => specify column name
* => all columns

=> display all the data from emp table ?

SELECT * FROM emp ;

=> display employee names and salaries ?

SELECT ename,sal FROM emp ;

=> display employee names and hiredates ?

SELECT ename,hiredate FROM emp ;

Operators in ORACLE :-
-----------------------

1 Arithmetic Operators => + - * /


2 Relational Operators => > >= < <= = <>
3 Logical Operators => AND OR NOT
4 Special Operators => BETWEEN
IN
LIKE
IS
ANY
ALL
EXISTS
PIVOT
5 Set Operators => UNION
UNION ALL
INTERSECT
MINUS

WHERE clause :-
---------------

=> used to get specific row/rows from table based on a condition.

SELECT columns/*
FROM tabname
WHERE condition ;
condition :-
-------------

COLNAME OPERATOR VALUE

=> OPERATOR must be any relational operator like > >= < <= = <>
=> if cond = true then row is selected
=> if cond = false then row is not selected

Examples :-

1 display employee details whose empid=103 ?

SELECT * FROM emp WHERE empid=103 ;

2 display employee details whose name = vijay ?

SELECT * FROM emp WHERE ename='vijay' ;

3 display employees earning more than 5000 ?

SELECT * FROM emp WHERE sal > 5000;

4 display employees joined after 2020 ?

SELECT * FROM emp WHERE hiredate > 2020 ; => ERROR

SELECT * FROM emp WHERE hiredate > '31-DEC-20' ;

5 display employees joined before 2020 ?

SELECT * FROM emp WHERE hiredate < '01-JAN-20' ;

compound condition :-
---------------------

=> multiple conditions combined with AND / OR operator is called


compound condition.

COND1 AND COND2 RESULT


T T T
T F F
F T F
F F F

COND1 OR COND2 RESULT


T T T
T F T
F T T
F F F

=> display employees working as clerk,manager ?

SELECT * FROM emp WHERE job='clerk','manager' ; => ERROR

SELECT * FROM emp WHERE job='clerk' OR job='manager' ;

=> display employees whose empid=100,103,105 ?


SELECT * FROM emp WHERE empid=100 OR empid=103 OR empid=105 ;

01-may-21

=> display employees working as clerk and earning more than 4000 ?

SELECT * FROM emp WHERE job='clerk' AND sal>4000 ;

=> display employees earning more than 5000 and less than 10000 ?

SELECT * FROM emp WHERE sal>5000 AND sal<10000 ;

=> display employees joined in 2020 year ?

SELECT * FROM emp WHERE hiredate = 2020 ; => error

SELECT * FROM emp WHERE hiredate >= '01-JAN-2020'


AND
hiredate <= '31-DEC-2020' ;

Example :-

STUDENT
SID SNAME S1 S2 S3
1 A 80 90 70
2 B 30 60 50

=> display list of students who are passed ?

SELECT * FROM STUDENT WHERE S1>=35 AND S2>=35 AND S3>=35 ;

=> display list of students who are failed ?

SELECT * FROM STUDENT WHERE S1<35 OR S2<35 OR S3<35 ;

=> display employees working as clerk,manager


and earning more than 5000 ?

SELECT * FROM emp WHERE job='clerk'


OR
job='manager'
AND
sal>5000 ;

=> in the above query sal>5000 condition is applied only to managers


but not to clerk because operator AND has got more precedence
than operator OR , to control this use ( ).

SELECT * FROM emp WHERE (job='clerk'


OR
job='manager')
AND
sal>5000 ;

IN operator :-
---------------

=> use IN operator when "=" comparision with multiple values.


=> use IN operator for list comparision.
WHERE COLNAME IN (V1,V2,V3,----) (COL=V1 OR COL=V2 OR COL=V3--)

WHERE COLNAME NOT IN (V1,V2,V3,--)

=> display employees working as clerk,manager,analyst ?

SELECT * FROM emp WHERE job IN ('clerk','manager','analyst');

=> display employees whose empid=100,103,105 ?

SELECT * FROM emp WHERE empid IN (100,103,105);

=> display employees not working as clerk,manager ?

SELECT * FROM emp WHERE job NOT IN ('clerk','manager');

BETWEEN operator :-
--------------------

=> use BETWEEN operator for range comparision.

WHERE COLNAME BETWEEN V1 AND V2 (SAL>=V1 AND SAL<=V2)


WHERE COLNAME NOT BETWEEN V1 AND V2

=> display employees earning between 5000 and 10000 ?

SELECT * FROM emp WHERE sal BETWEEN 5000 AND 10000 ;

=> display employees joined in 2020 year ?

SELECT * FROM emp


WHERE hiredate BETWEEN '01-JAN-2020' AND '31-DEC-2020' ;

=> display employees not joined in 2020 year ?

SELECT * FROM emp


WHERE hiredate NOT BETWEEN '01-JAN-2020' AND '31-DEC-2020' ;

Question :-

SELECT * FROM emp WHERE sal BETWEEN 10000 AND 5000 ;

a ERROR
b RETURNS ROWS
c RETURNS NO ROWS
d NONE

ANS :- c

SELECT * FROM emp WHERE sal BETWEEN 5000 AND 10000;

WHERE sal>=5000 and sal<=10000;

SELECT * FROM emp WHERE sal BETWEEN 10000 AND 5000 ;

WHERE sal>=10000 and sal<=5000

NOTE :- use BETWEEN operator with lower and upper but not with
upper and lower.

03-may-21 :-

display employee list working as clerk,manager and earning between


5000 and 10000 and joined in 2021 year ?

SELECT *
FROM emp
WHERE job IN ('clerk','manager')
AND
sal BETWEEN 5000 and 10000
AND
hiredate BETWEEN '01-JAN-21' AND '31-DEC-21' ;

scenario :-

products
prodid pname price category brand

=> list of realme,redmi,samsung brand mobiles phones price between 10000


and 20000 ?

SELECT *
FROM products
WHERE category='mobiles'
and
brand in ('realme','redmi','samsung')
and
price between 10000 and 20000 ;

2
CUST
CID NAME GENDER AGE ADDR CITY STATE

=> display list of male customers staying in hyd,mum,del city


whose age between 20 and 30 ?

SELECT *
FROM cust
WHERE gender='M'
AND
city IN ('hyd','mum','del')
AND
age BETWEEN 20 AND 30 ;

LIKE operator :-
-----------------

=> use LIKE operator for pattern comparision.

WHERE COLNAME LIKE 'PATTERN'


WHERE COLNAME NOT LIKE 'PATTERN'

=> PATTERN consists of alphabets,digits,wildcard chars.

wildcard chars :-
----------------

% => 0 or many chars


_ => exactly 1 char

=> display employees name starts with 'S' ?

SELECT * FROM emp WHERE ename LIKE 'S%' ;

=> display employees name ends with 'S' ?

SELECT * FROM emp WHERE ename LIKE '%S' ;

=> display employees name contains 'S' ?

SELECT * FROM emp WHERE ename LIKE '%S%' ;

=> display employees where 'A' is the 2nd char in their name ?

SELECT * FROM emp WHERE ename LIKE '_A%';

=>display employees where 'A' is the 3rd from last ?

SELECT * FROM emp WHERE ename LIKE '%A__' ;

=> display employees name contains 4 chars ?

SELECT * FROM emp WHERE ename LIKE '____' ;

=> display employees joined in APR month ?

DD-MON-YY

SELECT * FROM emp WHERE hiredate LIKE '%APR%' ;

=> display employees joined in 1981 year ?

SELECT * FROM emp WHERE hiredate LIKE '%81' ;

Question :-
-----------

SELECT * FROM emp WHERE job IN ('CLERK','%MAN%');

A ERROR
B returns no rows
C returns clerk,manager,salesman rows
D returns only clerk

ANS :- D

SELECT * FROM emp WHERE job='CLERK' OR job LIKE '%MAN%' ;

ANS :- C

IS operator :-
--------------

=> use IS operator for NULL comparision


WHERE COLNAME IS NULL
WHERE COLNAME IS NOT NULL

=> display employees not earning comm ?

SELECT * FROM emp WHERE comm = NULL ; => no rows

SELECT * FROM emp WHERE comm IS NULL ;

=> display employees who are earning comm ?

SELECT * FROM emp WHERE comm IS NOT NULL ;

summary :-

WHERE COL IN (V1,V2,V3,--)


WHERE COL BETWEEN V1 AND V2
WHERE COL LIKE 'PATTERN'
WHERE COL IS NULL

04-MAY-21

Display list of tables ?

1 SELECT * FROM tab ;


2 SELECT TABLE_NAME FROM USER_TABLES ;

Display list of users ?

SELECT USERNAME FROM ALL_USERS ;

Display db name ?

SELECT * FROM GLOBAL_NAME ;

Display version ?

SELECT * FROM V$VERSION ;

ORDER BY clause :-
-------------------

=> ORDER BY clause is used to sort data based on one or more columns
either in ascending or in descending order.

SELECT columns/*
FROM tabname
[WHERE condition]
ORDER BY <col> [ASC/DESC]

=> default order is ASC

=> arrange employee list name wise ascending order ?

SELECT empno,ename,job,sal,deptno
FROM emp
ORDER BY ename ASC ;
=> arrange employee list sal wise desc order ?

SELECT empno,ename,job,sal,deptno
FROM emp
ORDER BY sal DESC ;

=> arrange employee list experience wise and employee having max
experience should be displayed first ?

SELECT empno,ename,hiredate,sal,deptno
FROM emp
ORDER BY hiredate ASC ;

NOTE :-

=> in order by clause we can use column name or column number

SELECT *
FROM emp
ORDER BY 6 DESC;

=> above query sorts data based on 6th column i.e. SAL.

2 ORDER BY number is not based on table it is based on select list.

SELECT empno,ename,job,sal,deptno
FROM emp
ORDER BY 6 DESC; => ERROR

=> to sort based on sal

SELECT empno,ename,job,sal,deptno
FROM emp
ORDER BY 4 DESC ;

=> arrange employee list dept wise asc ?

SELECT empno,ename,job,sal,deptno
FROM emp
ORDER BY 5 ASC;

1 A CLERK 3000 20 3 C CLERK 4000 10


2 B MANAGER 6000 30 1 A CLERK 3000 20
3 C CLERK 4000 10 ===> 5 E CLERK 2000 20
4 D SALESMAN 4000 30 2 B MANAGER 6000 30
5 E CLERK 2000 20 4 D SALESMAN 4000 30

sorting based on multiple columns :-


-------------------------------------

=> arrange employee list dept wise asc and with in dept sal wise
desc order ?

SELECT empno,ename,sal,deptno
FROM emp
ORDER BY deptno ASC,sal DESC ;
1 A 3000 20 6 F 5000 10
2 B 2000 10 5 E 4000 10
3 C 4000 30 ==========> 2 B 2000 10
4 D 6000 20 4 D 6000 20
5 E 4000 10 1 A 3000 20
6 F 5000 10 3 C 4000 30

scenario :-

STUDENTS
SNO SNAME M P C
1 A 80 90 70
2 B 60 50 70
3 C 90 70 80
4 D 90 80 70

=> arrange student list avg wise desc ,m desc,p desc ?

SELECT *
FROM STUDENTS
ORDER BY (M+P+C)/3 DESC,M DESC,P DESC ;

4 D 90 80 70
3 C 90 70 80
1 A 80 90 70
2 B 60 50 70

=> to display avg in output ?

SELECT sno,sname,m,p,c,(m+p+c)/3
FROM students
ORDER BY (m+p+c)/3 DESC,m DESC,p DESC ;

SNO SNAME M P C (M+P+C)/3


4 D 90 80 70 80
3 C 90 70 80 80
1 A 80 90 70 80
2 B 60 50 70 60

=> to change column heading declare alias as follows

SELECT sno,sname,m,p,c,(m+p+c)/3 as avg


FROM students
ORDER BY (m+p+c)/3 DESC,m DESC,p DESC ;

DML commands :- (Data Manipulation Language)


----------------------------------------------

INSERT
UPDATE
DELETE
INSERT ALL
MERGE

=> DML commands acts on table data.


=> DML commands acts on instance(RAM).
=> to save these operations execute COMMIT.
=> to cancel these operations execute ROLLBACK.
UPDATE command :-
------------------

=> command used to modify the existing data.


=> using update command we can modify single column or multiple columns
=> using update command we can modify all rows or specific rows.

syntax :- UPDATE <tabname>


SET colname=value , colname=value,-------
[WHERE condition]

=> update all employees comm to 500 ?

UPDATE emp SET comm=500 ;

=> update employees comm to 500 whose comm = null ?

UPDATE emp SET comm=500 WHERE comm IS NULL ;

=> update employees comm to null whose comm <> null ?

UPDATE emp SET comm = NULL WHERE comm IS NOT NULL ;

NULL assignment =
NULL comparision IS

=> increment sal by 20% and comm by 10% those working as salesman
and joined in 1981 year ?

UPDATE emp
SET sal = sal + (sal*0.2) , comm = comm + (comm*0.1)
WHERE job='SALESMAN'
AND
hiredate LIKE '%81';

=> transfer all employees from 10th dept to 30th dept ?

UPDATE emp SET deptno=30 WHERE deptno=10 ;

=> increment salaries by 10% those having more than 40 years of expr ?

UPDATE emp
SET sal=sal+(sal*0.1)
WHERE (SYSDATE-HIREDATE)/365 > 40 ;

06-may-21

DELETE command :-
------------------

=> command used to delete row/rows from table


=> using delete we can delete all rows or specific rows

syn :- DELETE FROM <tabname> [WHERE cond]

=> delete all rows from emp ?

DELETE FROM emp ;


=>delete employee rows having more than 40 years of experience ?

DELETE FROM emp WHERE (SYSDATE-hiredate)/365 > 40 ;

=> delete employee row whose empno=7844 ?

DELETE FROM emp WHERE empno=7844 ;

FLASHBACK :-
------------

=> Introduced in oracle 10g.


=> using flashback we can see the data that exists some time back.
=> it is useful to recover data after commit.
=> a normal query returns current data and a flashback query returns past data.

syn :- SELECT columns/*


FROM tabname
AS OF TIMESTAMP(SYSDATE - INTERVAL) ;

Example :-

=> display 5 mins back data in emp table ?

SELECT *
FROM emp
AS OF TIMESTAMP(SYSDATE-INTERVAL '5' MINUTE);

recovering data after commit :-


--------------------------------

SQL>DELETE FROM emp ;


SQL>COMMIT;

=> get the data that exists 5 mins back and insert that data into
current emp table ?

SQL>INSERT INTO EMP


SELECT *
FROM emp
AS OF TIMESTAMP(SYSDATE - INTERVAL '5' MINUTE);

-------------------------------------------------------------------

DDL commands :- (Data Definition Lang)


---------------------------------------

CREATE
ALTER
DROP
TRUNCATE
RENAME
FLASHBACK
PURGE

=> all DDL commands acts on table structure (columns).


=> all DDL commands are auto committed.
DDL command = DDL command + COMMIT

ALTER command :-
----------------

=> command used to modify table structure.


=> command used to

1 add columns
2 drop columns
3 rename column
4 modify a column
incr/decr field size
changing datatype

Adding columns :-
-----------------

=> add column gender to emp table ?

ALTER TABLE emp


ADD (gender char(1));

=> after adding by default the new column is filled with NULLs.
to insert data into this new column use UPDATE command.

1 UPDATE emp SET gender='M' WHERE empno=7369 ;

2 SQL>UPDATE emp SET gender='&gender' WHERE empno=&empno;


enter value for gender :- F
enter value for empno :- 7499
1 row updated

SQL>/ (previous command reexecutes)

Droping column :-
-----------------

=> drop column gender from emp ?

ALTER TABLE emp


DROP (gender);

Renaming a column :-
---------------------

=> rename column comm to bonus ?

ALTER TABLE emp


RENAME COLUMN comm TO bonus ;

SELECT empno,ename,sal,comm as bonus


FROM emp ;

diff b/w rename and alias ?

rename alias

1 permanent not permanent


2 rename changes changes column heading in select
column name in table statement output

You might also like