You are on page 1of 26

Co-Related Subqueries from Book

============================
--Questions for Assignments on Co-related Subqueries : Northwind
--Display the names of the employees who have atleast created 1 order ?
--Find the names of the employees who earn more than the average salary in thier
department
--Display the details of those employees who have changed jobs at least twice

Module 9,10,11 we were supposed to read

Introduction Schema Objects :

Tables
Views
Indexes
sequences
Synonyms
--Data Dictionary /Catalogue

--Tables
--Create Table >>> /Alter table/Drop table /rename table
--Alter table
Alter Table (DDL )
Change the name of column
Add a New Column
modify Data type of the column
Drop a Column

-- To add a City column to the Dept table;


Alter Table Dept
add City varchar2(25);
--Syntax to rename column
--Alter Table <tablename> Rename column <oldcolname> to <newcolname>
Alter Table Dept
Rename column deptno to deptnumber;
Desc Dept;

--Syntax to Rename the Table


--Rename <OldTable> to <NewTable>
Rename Employee to Emp
Desc Emp
--To change the Column Details of a Table
Alter table <Table Name>
--for 1 Col
Add(new_colname datatype constraint cons_name cons_type)
--for Many cols
Add(new_colname1 datatype constraint cons_name cons_type, new_colname2 datatype
constraint cons_name cons_type)
--change the Existing Columns datatype,
Constraint
Modify(old_colname new_datatype)
--Rename
Rename column deptno to deptnumber;
--To Drop 1 Column
Drop Column Deptno
--To Drop Many Cols
Drop (col1,col2,col3)
Update Data in Row in a Table
=========================
Alter Table Dept
add City varchar2(25);

Update dept
Set city = 'Mumbai'
where deptid = 10; ---- Aviod the where clause , it will add City value Mumbai to
all the rows of the table

Update Dept
set city = 'Bangalore'
where deptid = 20;

Update Dept
Set city = 'Delhi'
where deptid = 30;

Update Dept
Set city = null
where deptid = 40;

commit;

Select * from dept;

insert rows (dml)

Commit; (tcl)

Add a Column city (ddl) -- autocommit will happen here

Update the column city (DML)


commit;

Delete all rows (DML) - Delete from tablename;


BUT I did a fire a commit here ?
Rollback;

Delete ... can use the where clause ... rows can be Rollback, DML statement
Truncate - DDL
TRUNCATE TABLE < tablename>

--Q. Difference between Delete(DML) vs Truncate(DDL)


--Delete is a DML statement, Can use the where clause, we can use Rollback to undo
rows in a table
--Truncate is a DDL statement,cannot use a where clause,All rows are removed
permanantly (autocommit is fired) and cannot undo the Rows .

--Constraints
It is a RULE to make sure INSERT/UPDATE/DELETE rows in the table

--Types of Constraints

Primary key : Unique + not null constraint --


: Also an Index Object is also Created for the P.K columns
: A Unique+not null Index of type BTree is created for the P.K
: A primary is logical unique Id for a every row of the table
Q.What is Diff between P.K and Unique
1. There can only 1 P.K for a table , but many unique Columns , may go null
note : index is created for both P.K and Unique columns

--Different ways to write the Constraints

--Method1
create table depart (
dept_code varchar2 (4) primary key,
dept_name varchar2 (20) not null
);

select constraint_name,constraint_type,delete_rule from user_constraints where


table_name ='DEPART';

drop table depart;

method2 :
create table depart (
dept_code varchar2 (4) constraint dept_code_pk primary key,
dept_name varchar2 (20) constraint dept_name_nn not null

);
--It is possible to name the not null constraint

drop table depart;

method 3 : Created a P.K as Table Level Constraint

--Difference between column level and table level ?


-- Not null constraint cannot be given at Table level , has to given along with the
column

create table depart (


dept_code varchar2 (4) ,
dept_name varchar2 (20) not null ,
constraint dept_pk primary key (dept_code) -- Table level constraint
defination
);

--How to View Constraints tablewise?

we have to use Data Dictionary View : USER_CONSTRAINTS

SQL> select constraint_name,constraint_type,delete_rule from user_constraints where


table_name ='EMPLOYEES';

--How to View Contraints Table Wise/ColumnWise ?

we have to use Data Dictionary View : USER_CONS_COLUMNS

SQL> desc user_cons_columns;


Name Null? Type
----------------------------------------- -------- ----------------------------
OWNER NOT NULL VARCHAR2(30)
CONSTRAINT_NAME NOT NULL VARCHAR2(30)
TABLE_NAME NOT NULL VARCHAR2(30)
COLUMN_NAME VARCHAR2(4000)
POSITION NUMBER

SQL> select * from user_cons_columns where table_name ='EMPLOYEES';

Create table ship


(shipid number(5) Constraint PK_ship_shipid Primary key,
shipname varchar2(25));

insert into ship values(1,'King');


insert into ship values(2,'Queen');

--F.K Without the Delete cascade rule default NOAction, no cascade

create table shipv


(
vogid number(5),
vdate date not null,
vdest varchar2(50),
vshipid number(5),
constraint PK_shipv_vogid Primary Key(vogid),
constraint FK_shipv_vshipid foreign key(vshipid) references ship(shipid)
);

insert into shipv(vogid,vdate,vshipid) values(101,sysdate,1);

--Delete the date of the master Ship table

SQL> delete from ship where shipid =1;


delete from ship where shipid =1
*
ERROR at line 1:
ORA-02292: integrity constraint (HR.FK_SHIPV_VSHIPID) violated - child record
found

--drop the F.K constraint


--re-add theF.K constraint with Delete cascade clause - when a master record is
deleted and if child records exists then automatically the child record also gets
deleted

SQL> alter table shipv drop constraint FK_SHIPV_VSHIPID_DC;

Table altered.

SQL>
SQL> alter table shipv add constraint FK_SHIPV_VSHIPID_DC1 foreign key(vshipid)
references ship(shipid)
2 on delete cascade;

Table altered.

SQL> select constraint_name,constraint_type,delete_rule from user_constraints where


table_name ='SHIPV';

CONSTRAINT_NAME C DELETE_RULe
------------------------------ - ---------
SYS_C007026 C
PK_SHIPV_VOGID P
FK_SHIPV_VSHIPID_DC1 R CASCADE
SQL> delete from ship where shipid=1;

1 row deleted.

SQL> select * from ship;

SHIPID SHIPNAME
---------- -------------------------
2 Queen

--Customers (master)
--Column Level Constraints

Create table Customer


(
Custid number(5) Constraint Customer_Custid_PK Primary key,
Cname varchar2(50) Constraint Customer_Cname_UQ_NN Unique not null,
City varchar2(25) Constraint Customer_City_Ck check(city in
('BLR','HYD','MUM','NCR'))
);

Table created.

--orders Table

--Example of Composite Primary Key and Real reason for Table constraint
--Primary key is composite and has to be defined as Table level constraint
--usually table level constraints are given when more than 1 column in the table is
involved in the constraints

--Example PK
Constraint Orders_PK_orderid_orderate Primary Key(Orderid,Orderdate)
--Example Check for table level
qty_in_stock
qty_reorder_level
Constraint qty_chk check(qty_in_stock >qty_reorder_level )

Create table Orders


(
Orderid Number(5),
Orderdate date ,
Custid number(5) Constraint Orders_CustId_FK references customer(custid), -- FK
at the column level
Constraint Orders_PK_orderid_orderate Primary Key(Orderid,Orderdate)
);

Table created.

-- Test for F.k references


SQL> /

CUSTID CNAME CITY


---------- --------------------------------------------------
-------------------------
1 SAT
2 PAT MUM
3 MACK HYD

SQL>
SQL> desc orders
Name Null? Type
----------------------------------------------------- --------
------------------------------------
ORDERID NOT NULL NUMBER(5)
ORDERDATE NOT NULL DATE
CUSTID NUMBER(5)

SQL> insert into orders(101,sysdate,4);


insert into orders(101,sysdate,4)
*
ERROR at line 1:
ORA-00928: missing SELECT keyword

SQL> insert into orders values(101,sysdate,4);


insert into orders values(101,sysdate,4)
*
ERROR at line 1:
ORA-02291: integrity constraint (HR.ORDERS_CUSTID_FK) violated - parent key not
found

SQL> insert into orders values(101,sysdate,1);

1 row created.

SQL> /

1 row created.

SQL> /

1 row created.

SQL> select * from orders;

ORDERID ORDERDATE CUSTID


---------- --------- ----------
101 07-APR-21 1
101 07-APR-21 1
101 07-APR-21 1

SQL> alter session set nls_date_format = 'DD:MM:YYYY HH:MI:SS'


2 ;

Session altered.

SQL> /

Session altered.

SQL> select * from orders;


ORDERID ORDERDATE CUSTID
---------- ------------------- ----------
101 07:04:2021 12:38:05 1
101 07:04:2021 12:38:09 1
101 07:04:2021 12:38:38 1

SQL> select sysdate from dual'


2 ;
ERROR:
ORA-01756: quoted string not properly terminated

SQL> select sysdate from dual;

SYSDATE
-------------------
07:04:2021 12:41:02

-- To Enable and Disable Constraints

SQL> Alter table Orders disable constraint Orders_PK_orderid_orderate;


Table altered.

-- Before Re-enabling the constraint the data in the table must be as per the
Constraint rules.
SQL> Alter table Orders enable constraint Orders_PK_orderid_orderate;
Table altered.

--cascade Constraints : Find out what the below commands do ?

SQL> alter table customer drop column custid;


alter table customer drop column custid
*
ERROR at line 1:
ORA-12992: cannot drop parent key column

SQL> drop table customer;


drop table customer
*
ERROR at line 1:
ORA-02449: unique/primary keys in table referenced by foreign keys

DROP COLUMN custid --- this command will not work

--This CASCADE CONSTRAINTS is used when dependent F.K constraints have


--to be dropped for a P.K column

-- To drop the F.K constraint from orders child table and also drop the constraint
PK and the column from the master table

alter table customer


DROP COLUMN custid -- of the master table
CASCADE CONSTRAINTS;

Or
Also the F.K constraint from the Orders table

Alter table Orders Drop Constraint Orders_CustId_FK ; -- break the Link of F.K

SQL> drop table customer CASCADE CONSTRAINTS; -- break the link with the Order
table by dropping the F.K constraint only not the ORDER TABLE

Exercise on cascade constraints

SQL> drop table customer CASCADE CONSTRAINTS;

Table dropped.

SQL> desc orders;


Name Null? Type
----------------------------------------------------- --------
------------------------------------
ORDERID NOT NULL NUMBER(5)
ORDERDATE NOT NULL DATE
CUSTID NUMBER(5)

SQL> select constraint_name, constraint_type from user_constraints where table_name


= 'ORDERS';

CONSTRAINT_NAME C
------------------------------ -
ORDERS_PK_ORDERID_ORDERATE P

SQL>

--when we have enable /disable constraint we have to CASCADE to disable the f.K
constraint

Alter table dept


DISABLE CONSTRAINT cd_pk CASCADE;

Topic : Controlling User Access

--Managing Schema Objects and Viewing Dictionary Tables


--Dictionary Tables - Meta data info
--3 different Perceptives === User(owned)/ALL(owned+access given to other
user'sobjects)/
--DBA (across all schemas the DBA can see all objects)

--Controlling access to users


--Grants >>Privs
-- Session Level Privs (Granting a user a priv. to create a certain type of an
object)
--SQL> Grant create table,create view,create sequence to northwind,HR;
--SQL> revoke create table,create view,create sequence to northwind,HR;

-- Object Level Privs (granting access on Select/Insert/Update/Alter a specific


Object)
--SQL> grant select,insert,update on Hr.Employees to Northwind;
--SQL> grant ALL on Hr.Employees to Northwind;

Topic : Views

--SQL_VIEWS

What is View?
--View is a Object based on a Query (simple/Complex/Read only data)
--View does not store any data
--ONLY materialized which store data (not in scope)

What is the Purpose of a view ?


--To hide the Complexity of the Query , so that the Report User does not know where
the underlying data is
--being pulled from the data tier
--The base credentials of the Table have to be hidden from the Users

The Final using the View, will not access the view with the View Name
--Select * from Viewname ;

--Simple View -Based on 1 table

--PART A
Create or replace View Empview
As
Select Employee_id, First_name,last_name,salary
from employees;

-- Added the department_id Column without using the Alter Command

Create or Replace View Empview


As
Select Employee_id, First_name,last_name,salary,department_id
from employees;

Desc empview;

Data Dictionary For the Views

DESC User_Views

Select View_name, Text from user_views;

--to See data to the table through the View

Select * from employees; -- from the base table


Select * from EmpView; -- from the view

Observation :
1.The Number of rows in the empview is the same as the no of rows of the Base table
employees
2. The view has visibility on only some cols of the table
--How to change the query of the View ?

Create or Replace View EMPVIEW as select * from Employees;

select view_name,text As Query,read_only,view_type


from user_views where view_name ='EMPVIEW';

--Good to know Information about views can read from slides post Training
--Additional Clauses of the View
--WITH READ ONLY Option - makes a View Read only
--FORCE - Keyword used when creating view based table which currently has no
data ,its like creating a view with a table which exists but still has no data
--By Default a Table which has no Data does notallow to create a view, so have to
force the creation of the view using FORCE clause
--With check Option
-TYPE OF VIEW
--MATERIALIZED VIEWS -This is the only type of view based on a query but also
stores data
--The View can be refresh using 2 options
On Commit ;
Manually : Refresh command on the View
--which can be refreshed Immediately or Later based on Manual refresh options
--check the Oracle docs
==============================================================================

Topic : Indexes :
Sql-Indexes
--Index Object (segment)-it has its own space and is usually created for a table,
--but can also be created for a view)
--for searching mechanism
--to speed up the searching mechanism
-1000 pages book
--BOOK(1000 pages) = TABLE(1000 rows)

--A Table /Book without index


--ALways TABLE SCAN will be executed
--slow response time

--if we need to search for a KEYWORD -- entire book scan/table scan


--where clause is used for criteria/keyword search

--A Table /Book with index


--Optimiser will try to optimise the Query
--OPT.decides to use Table SCAN/INDEX SCAN

--Lets Take an Example


--Of the Table Employee
--How to check if Index Exists for a Table ?
--Use SQLDEV. TABLE TAB, INDEXES
--IN SQLPLUS -Query the Dictionary Catalogue - USER_INDEXES

select Index_name,Uniqueness,Index_type,Table_name from USER_indexes where


Table_name = 'EMPLOYEES';

--How to we know which Index for Which Column ?


--user_IND_COLUMNS -- which tells me which Index for which Columns
Select * from USER_IND_COLUMNS where TABLE_NAME = 'EMPLOYEES';
--To search in the DICT catalogue for a particular type of View

--To Search for Constraint related Views,we can used the Below Command

Select * from DICT where Table_name like '%USER%CON%';

--Index_Type,For a Column
--Unique Index -- is automatically created when a Primary Key or Unique key
constraint
--is applied to a column
--Select * from employees where employee_id = 101;

--NON Unique Index -- should be created manually by us,when we need to query a


certain column frequently in the where clause

--Select * from employees where department_id = 10


--Select * from employees where job_id like '%IT%;

--Since the Department_id and the Job_id is NOT the PK

Create INDEX IDX_EMPLOYEES_DEPARTMENT_ID on EMPLOYEES(DEPARTMENT_ID);


--this above command creates a NON-UNIQUE INDEX of TYPE BTREE(default INDEX
ORGANIZATION)

Select * from employees;


Select * from employees where employee_id = 101;

--How to Check if Index is used by the Query


--Use the Explain Plan feature of the Developer (F10)

Select * from employees;


Select * from employees where employee_id = 101;

--Additional Reading on Types of Indexes From the slides (post Training)

Types of Indexes *which differ in how they store data and Organised
1.BTREE structure is used by Normal/Reverse/FUNCTION
2.BitMapped Index -Stores a Bitmap Values of Where Data bit is True for Indexed
column, Good for low cardinality Values
3.Index Organised Tables(IOT's) -Clustered Index

==Altering or Rebuilding an Index

Like creation of index, altering index also requires either the schema to be your
own or ALTER ANY INDEX system privilege.

Note that what cannot be changed using the ALTER INDEX statement is an index's
column structure.
To change an existing index as a reverse key index you can use the alter index
statement.
Types

ALTER INDEX indexname REBUILT REVERSE;

Rebuilding an index based on an existing data removes intra-block fragmentation. It


gives better performance compared to dropping the index and using the recreating
it.

ALTER INDEX indexname REBUILD;

To add ONLINE option:


ALTER INDEX indexname REBUILD ONLINE;

Analyzing Tables for Integrity


 
The ANALYZE TABLE command has an option to validate the structure of a table,
cluster or an index.
 
For example, to analyze table CUSTOMER, issue the following command:
 
analyze table Customer validate structure;
 
Oracle verifies the integrity of each of the table's blocks and rows. If it finds
any corruption, it returns an error.

Validating the structure of an object prevents SELECT, INSERT, UPDATE and DELETE
statements on that object.
 
If you want to validate the indexes of a table, then use the CASCADE clause, as
follows:
 
analyze table Customer validate structure cascade;

--Synonyms
/*
Creating a Synonym in HR Schema

There are 2 types of Synonym


1.Public : the sysdba creates public synonym so that all users can use the
alternate name for a Table/View
-tab,cat

2.private : by a user like HR, Northwind

CREATE SYNONYM testemp for Employees; -- this is Private Synonym

Now, 'testemp; can be used in place of employee, such as

SELECT * FROM testemp;


HR can now use 2 names for the Table , EMPLOYEES, testemp

Resolving Object Synonyms : Oracle will always first look for the table, synonym

A synonym can also be used to give SELECT privileges to all other users, on the
said table.
Grant access to Other User

GRANT select on testemp to Northwind;

Create another SQLplus session


Connect as Northwind

Check if Northwind has access to the object

Select * from hr.testemp

Update hr.testemp
set department_id = 10
where department_id = 20;

Insufficient privs

Switch to HR

Grant ALL on testemp to northwind;

Switch to northwind

Update hr.testemp
set department_id = 10
where department_id = 20;

Rollback;

If you are getting a trigger Error Message

Then you can try update

update hr.testemp
set first_name ='Diana'
where employee_id = 101;

Observations
=============
The Table and the Synonym reference the same data
Synonyms can be used as alternate objects to hide original object names from Other
users

note : This kind of a synonym can only be created by the DBA and such a synonym is
referred to as PUBLIC SYNONYM.

As an HR user

Create synonym testemp on hr.employees to PUBLIC

Try as a SYS User


Create synonym testemp on hr.employees to PUBLIC
Dropping A Synonym A Synonym can be dropped, without affecting any of the objects.
We can drop a synonym using the DROP SYNONYM command.
drop synonym testemp;
Difference Between views and Synonym
A Synonym is an alternate name to an object

--Topic : Sequences

--Primary key column in a table , generate Sequence no


--Sequence object is separate , does have any data
--Sequence is used during insert statement to generate a Sequence Number
/*
SQL> create sequence s1;
SP2-0734: unknown command beginning "createe se..." - rest of line ignored.
SQL> create sequence s1;

Sequence created.

SQL> desc s1
SP2-0381: DESCRIBE sequence is not available

SQL> desc user_sequences


Name Null? Type
----------------------------------------- -------- ----------------------------
SEQUENCE_NAME NOT NULL VARCHAR2(30)
MIN_VALUE NUMBER
MAX_VALUE NUMBER
INCREMENT_BY NOT NULL NUMBER
CYCLE_FLAG VARCHAR2(1)
ORDER_FLAG VARCHAR2(1)
CACHE_SIZE NOT NULL NUMBER
LAST_NUMBER NOT NULL NUMBER

SQL> desc customer


Name Null? Type
----------------------------------------- -------- ----------------------------
CUSTID NOT NULL NUMBER(5)
CNAME NOT NULL VARCHAR2(50)
CITY VARCHAR2(25)

SQL> select * from user_sequences where sequence_name ='S1';

SEQUENCE_NAME MIN_VALUE MAX_VALUE INCREMENT_BY C O CACHE_SIZE


------------------------------ ---------- ---------- ------------ - - ----------
LAST_NUMBER
-----------
S1 1 1.0000E+28 1 N N 20
1

SQL> insert into customer values(s1.nextval,'XYZ','BLR');

1 row created.

SQL> insert into customer values(s1.nextval,'ABC','MUM');

1 row created.

SQL> insert into customer values(s1.nextval,'TYZ','BLR');

1 row created.

SQL> select * from customer;

CUSTID CNAME
---------- --------------------------------------------------
CITY
-------------------------
1 XYZ
BLR
2 ABC
MUM

3 TYZ
BLR

SQL> select s1.currval from dual;

CURRVAL
----------
3

SQL> insert into customer values(s1.nextval,'GUG','MUM');

1 row created.

SQL> select * from customer;

CUSTID CNAME
---------- --------------------------------------------------
CITY
-------------------------
1 XYZ
BLR

2 ABC
MUM

3 TYZ
BLR

CUSTID CNAME
---------- --------------------------------------------------
CITY
-------------------------
4 GUG
MUM

SQL> create table t1( id number, name varchar2(25));

Table created.

SQL>
SQL> insert into t1(s1.nextval,'bhavna');
insert into t1(s1.nextval,'bhavna')
*
ERROR at line 1:
ORA-01747: invalid user.table.column, table.column, or column specification

SQL> insert into t1 values(s1.nextval,'bhavna');

1 row created.

SQL> select * from t1;


ID NAME
---------- -------------------------
5 bhavna

SQL> insert into t1 values(s1.nextval,'philip');

1 row created.

SQL> insert into t1 values(s1.nextval,'simi');

1 row created.

SQL> insert into t1 values(s1.nextval,'Jack');

1 row created.

SQL> select * from t1;

ID NAME
---------- -------------------------
5 bhavna
6 philip
7 simi
8 Jack

SQL> rollback;

Rollback complete.

SQL> select s1.nextval from dual;

NEXTVAL
----------
9

SQL> select s1.nextval from dual;

NEXTVAL
----------
10

SQL> select s1.nextval from dual;

NEXTVAL
----------
11

SQL> select * from t1;

no rows selected

SQL> drop sequence s1;

Sequence dropped.

SQL> create sequence s1


2 increment by 10
3 start with 100
4 maxvalue 200
5 cycle;

Sequence created.

SQL>
SQL> insert into t1 values(s1.nextval,'X'||s1.nextval);

1 row created.

SQL> /

1 row created.

SQL> /

1 row created.

SQL> /

1 row created.

SQL> /

1 row created.

SQL> /

1 row created.

SQL> /

1 row created.

SQL> /

1 row created.

SQL> /

1 row created.

SQL> /

1 row created.

SQL> /

1 row created.

SQL> /

1 row created.

SQL> /

1 row created.

SQL> /
1 row created.

SQL> /

1 row created.

SQL> /

1 row created.

SQL>
SQL> select * from t1;

ID NAME
---------- -------------------------
100 X100
110 X110
120 X120
130 X130
140 X140
150 X150
160 X160
170 X170
180 X180
190 X190
200 X200

ID NAME
---------- -------------------------
1 X1
11 X11
21 X21
31 X31
41 X41

16 rows selected.

SQL> select * from user_sequences where sequence_name ='S1';

SEQUENCE_NAME MIN_VALUE MAX_VALUE INCREMENT_BY C O CACHE_SIZE


------------------------------ ---------- ---------- ------------ - - ----------
LAST_NUMBER
-----------
S1 1 200
10 Y N 20
201

SQL> drop sequence s1;


Sequence dropped.
*/

--Topic: Manage Scheema Objects with Data Dictionary Views

SELECT * FROM USER_OBJECTS where Object_Type ='TABLE'


SELECT * FROM USER_OBJECTS where Object_Type ='VIEW'
SELECT * FROM USER_OBJECTS where Object_Type ='SEQUENCE'
SELECT * FROM USER_OBJECTS where Object_Type ='INDEX'

Topic : Oracle Transactions

--what is a Transaction ?
account (bank)

Debit/Credit

As Atomic Unit of work = 1 Transaction (Commited alltogether/Rollback)

Account1 balance Updated as a Debit : update accounts set balance = balance -5000
where accid=1
power failure /lag /
Account 2 balance Updated as a credit: update accounts set balance = balance +
5000 where accid=2
Entry Leger entry
Insert (Sysdate,5000,.........)

All Transaction : ACID

A -Atomicity
C -Consistency
I -Isolation - Transaction isolation
--concurent Access of a data item (row/stable/s)
--Readers can Read (shared Locks,old snapshot of data-) ,Writers can Write when the
2 records are different
--Locking mechanism -

--application Developer
--control of locks (Exclusive Locking on row level or table level so that no user
can read the data while A user a Transaction)
--The size of the transaction must be small

D-Durability - this is taken care by the DB(DBA-shutdown) autobuilt in


--Session is closed / killed / Power failure/ Transcations are automatically
Rollback

--In Oracle database as a SERVER -there is no SQL commnd as autocommit

---Tool Specific(EV) -SQLPLUS/SQLDEVELOPER


--Set Autocommit OFF -- Transaction will rollback
--Set Autocommit On--- Not a good Practice -- very dml gets committed

TCL statements in Oracle

Commit; -- End a Transaction and releases all the locks required during a DML , so
that other users can change the data . Makes changes permanent

Rollback; -- End a Transaction and releases all the locks required during a DML ,
so that other users can change the data . Undo's the Previously fired DML which
just started a Transaction

SavePoint : Creates Points to be marked in a Transaction , upto which we can


rollback;

--Exercise Sheets on Working with Transactions in Oracle


--Use the Employees Table in the HR Schema
--Ex1.
--Open 2 separate Sessions of HR Scehema
--Work in Session 1
--Insert a Row
--Query the table to see the Row
--Work in Session 2
--Query the table to see the Row
--state your observations here
--Work in Session 1
--Fire a Commit;
--Work in Session 2
--Query the table to see the Row
--State your observations here

--Use the Employees Table in the HR Schema


--Ex2.
--Work in Session 1
--Delete the row that you just inserted
--Query in Session 1
--state your observations here
--Query in Session 2
--state your observations here
--work in session 1
--Fire Rollback;
--Query in Session 1
--state your observations here

--Use the Employees Table in the HR Schema


--Ex3.

--Work in Session 1
--Update the salary of 101 and increase to 1000
--Query in Session 1
--state your observations here
--Query in Session 2
--state your observations here
--Update the salary of 101 and increase to 1000
--Check if you are getting a message 1 row updated
--work in session 1
--Fire commit;
--Query in Session 1
--state your observations here
--Query in Session 2
--state your observations here
--Fire Rollback in Session 2 ;
--Query in Session 2
--state your observations here

--Use the Employees Table in the HR Schema


--Ex4.
--Work in session 1
--Update the salary of 100 and increase to 1000
--Savepoint A;
--Insert a New Row
--Savepoint B;
--Delete the Row for employee 101;
--Savepoint C;
--Query the Data in Both the sessions
--State your observations in both the sessions

-- go back to Session 1
--Rollback to Savepoint B;
--Query the Data in Both the sessions
--State your observations in both the sessions

--Rollback to Savepoint A;
--Query the Data in Both the sessions
--State your observations in both the sessions

--Rollback;
--Query the Data in Both the sessions
--State your observations in both the sessions

--Use the Employees Table in the HR Schema


--Ex5.
--Work in session 1
--Update the salary of 100 and increase to 1000
--Create Table t1_dummy (id number);
--Work in session 2
--State your Observations
--check if Salary is Updated
--Desc t1_dummy
--State your Observations

--Go back to session 1


--again ,Update the salary of 100 and increase to 1000
--Query the salary..
--Drop Table T1-Dummy;

--Go back to Session 2


--Query the salary..
--State your Observations;

--Go back to Session 1


--Fire Rollback
--Query the salary..
--State your Observations

Topic :Working with Date Time and TimeZones

Difference between date and timestamp Datatype

DATE 7 bytes stores the Date and the time - sysdate


vs
Timestamp has a precision of 9 digits precison of a fraction sec - 11bytes
Normal timestamp datatype does not store the timezone offset

--to store the timestamp with Timezone

a>Timestamp with timezone - 13 bytes -- maintain an International


schedule -
b>Timestamp with Localtimezone - 13 bytes -- Maintain schedule of India only
what is a Timezone ?
It is a displacement of time in +,- from the UCT time (Greenwhich Mean Time-
GMT/UCT)

Time zone offset has a syntax of '+/-HH:MM'

Time Zone may also be set to using the Below Options Using ALTER SESSION SET
TIMEZONE

--An Absolute Value


ALTER SESSION SET TIME_ZONE ='-05:00';

--Database Time Zone


ALTER SESSION SET TIME_ZONE =dbtimezone;

--OS local time Zone


ALTER SESSION SET TIME_ZONE =local;

--A named region


ALTER SESSION SET TIME_ZONE ='America/New_York';

Date Functions
=============
SYSDATE
Returns current date and time to seconds of the server-Data type is DATE
SELECT sysdate FROM dual;

CURRENT_DATE
Returns the current date for the session timezone-Data type is DATE

SELECT sysdate,current_date, sessiontimezone FROM dual;

LOCALTIMESTAMP(p)
p is precision between 0 and 9. Default is 6. The return data type is TIMESTAMP.
Return current date and time in the session time zone to p digits precision.

SELECT current_timestamp, localtimestamp FROM dual;

CURRENT_TIMESTAMP(p) -returns data type is TIMESTAMP WITH TIMEZONE.


Returns current date and time in the session time zone to p digits precision

SELECT current_timestamp FROM dual;


SELECT sysdate, current_timestamp, sessiontimezone FROM dual;
--Comparing Date and Time in a session's Timezone
--to set the date format to any other format apart from the default for a session
only

Alter session set time_zone = '-5:00'

--check:
select sessiontimezone, current_date from dual;
select sessiontimezone,current_timestamp from dual;
select sessiontimezone,localtimestamp from dual;

--Difference between date and Timestamp


--Login as hr/hr@@xe

select sysdate from dual;


Select hire_date from employees;

Alter session Set NLS_DATE_FORMAT ='DD-MON-YYYY HH24:MI:SS';

select sysdate from dual;

Select hire_date from employees;

alter table employees modify hire_date timestamp;

Select hire_date from employees;

alter table employees modify hire_date date;

--Insert Data into the Table

Create table weborders


(order_date TIMESTAMP WITH TIME ZONE,delivery_time TIMESTAMP WITH LOCAL TIME ZONE);

insert into weborders values (current_date,current_timestamp + 2);

select * from weborders;

Select * from V$TIMEZONE_NAMES; -- this is TZNAME, TZABBRV

TZ_OFFSET(tz)

Returns the numeric timezone offset for a textual timezone name :

SELECT tz_offset(dbtimezone) chicago,


Tz_offset( 'US/EASTERN') NEW_YORK ,
Tz_offset( 'EUROPE/LONDON') LONDON ,
Tz_offset( 'ASIA/SINGAPORE') SINGAPORE,
Tz_offset( 'ASIA/CALCUTTA') INDIA FROM dual;

--How to the time by specifyinf a TZname or a region name ?


-- and the Difference in time from The UTC ??? Assignment
--

EXTRACT: without converting to character, we can use the extract function to get
the date part

SELECT sysdate, extract(year FROM sysdate) As year,


Extract(month FROM systimestamp) As month,
Extract(timezone_hour FROM systimestamp) tzh
FROM dual;

What is the difference between DBTIMEZONE VS SESSIONTIMEZONE?

Interval data Types


YEAR
MONTH
DAY
HOUR
MINUTE
SECOND

Interval Year(2) to Month(2) - Data type


YEAR
MONTH

20:24

Interval Day to Second - Data Type

DAY
HOUR
MINUTE
SECOND

D,H,M,S

Ex1 : Loan periods table

Interval Year to Month

The data type of INTERVAL YEAR TO MONTH stores a time interval in years and months.

It format is:

INTERVAL YEAR[(years_precision)]TO MONTH

years_precision, optional, may be an integer from 0 to 9. The default precision is


2. 2 means you can store two digits for the years in your interval. It can store a
positive or negative time interval.

An INTERVAL YEAR TO MONTH literal is defined in syntax:

INTERVAL '[+|-][y][-m]' [YEAR[(years_precision)])] [TO MONTH]


where

+, optional, specifies if the time interval is positive, the default is positive.


-, optional, specifies if the time interval is positive.
y, optional, the number of years.
m, optional, the number of months. TO MONTH must be added if you supply years and
months.
years_precision, optional, precision for the years, the default is 2.

Demo1:Example to get a future date , for Loan completion date

create table interval_example1


(loan_duration INTERVAL Year(3) to month);

create table interval_example2


(loan_duration INTERVAL Year(2) to month(2)
);

Insert into interval_example1 values( INTERVAL '120' month(3));

Insert into interval_example2 values( INTERVAL '1-2' Year to month);

--for 1 year and 2 months : Interval of 14 months (1 year 2 months).

Insert into interval_example2 values( INTERVAL '14' month);

select to_char(sysdate +loan_duration,'dd-mon-yyyy') from interval_example1;


insert into interval_example1 values( INTERVAL '100' year(3));
Year(2) and month(2)

INTERVAL DAY to Seconds datatype

some Examples

INTERVAL '4 5:12:10.222' DAY to second (3) -- can specify upto 9 precision of a
second

Indicates 4days 5 hrs 12mins 10sec 222 thousands of a sec.

INTERVAL '4 5:12' DAY to MINUTE

INTERVAL '400 5' DAY(3) to HOUR

INTERVAL '11:12:10.2222222' Hour to seconds(7)

For more Examples refer to the Link below

http://www.dba-oracle.com/t_advanced_year_month_interval.htm

--To Conversion Functions

--To_timestamp() -get the date converted to a timestamp () -- try to explore


--TO_YMINTERVAL - converts a char string in the format YEAR MONTH like 01-02
--TO_DSINTERVAL converts a char string in the format INTERVAL DAY TO SECOND
datatype

Q.Display a Date that is 1 year and 2 months after the hire date for the Employees
working in the department with the department_id 20

Select hire_date,hire_date + TO_YMINTERVAL('01-10') As HIRE_DATE_YMINTERVAL


from employees
where department_id=20;

TO_DSINTERVAL converts a char string in the format INTERVAL DAY TO SECOND datatype

Select last_name,
To_char(hire_date,'mm-dd-yy hh:mi:ss') hire_date1,
To_char(hire_date + TO_DSINTERVAL('100 10:00:00'),'mm-dd-yy hh:mi:ss') hire_date2
From employees;

Ex2 : Day Duration table

Create table Interval_example3


(day_duration INTERVAL DAY (3) to second);

insert into Interval_example3 values( INTERVAL '180' DAY(3));


insert into Interval_example3 values(INTERVAL '300' HOUR(3));
insert into Interval_example3 values(INTERVAL '120' minute(3));

Select sysdate+ day_duration from interval_example2;

You might also like