Professional Documents
Culture Documents
============================
--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
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
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;
Commit; (tcl)
Delete ... can use the where clause ... rows can be Rollback, DML statement
Truncate - DDL
TRUNCATE TABLE < tablename>
--Constraints
It is a RULE to make sure INSERT/UPDATE/DELETE rows in the table
--Types of Constraints
--Method1
create table depart (
dept_code varchar2 (4) primary key,
dept_name varchar2 (20) not null
);
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
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.
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.
SHIPID SHIPNAME
---------- -------------------------
2 Queen
--Customers (master)
--Column Level Constraints
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 )
Table created.
SQL>
SQL> desc orders
Name Null? Type
----------------------------------------------------- --------
------------------------------------
ORDERID NOT NULL NUMBER(5)
ORDERDATE NOT NULL DATE
CUSTID NUMBER(5)
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
Session altered.
SQL> /
Session altered.
SYSDATE
-------------------
07:04:2021 12:41:02
-- 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.
-- To drop the F.K constraint from orders child table and also drop the constraint
PK and the column from the master table
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
Table dropped.
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
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)
The Final using the View, will not access the view with the View Name
--Select * from Viewname ;
--PART A
Create or replace View Empview
As
Select Employee_id, First_name,last_name,salary
from employees;
Desc empview;
DESC User_Views
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 ?
--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)
--To Search for Constraint related Views,we can used the Below Command
--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;
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
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
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
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
Update hr.testemp
set department_id = 10
where department_id = 20;
Insufficient privs
Switch to HR
Switch to northwind
Update hr.testemp
set department_id = 10
where department_id = 20;
Rollback;
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
--Topic : Sequences
Sequence created.
SQL> desc s1
SP2-0381: DESCRIBE sequence is not available
1 row created.
1 row created.
1 row created.
CUSTID CNAME
---------- --------------------------------------------------
CITY
-------------------------
1 XYZ
BLR
2 ABC
MUM
3 TYZ
BLR
CURRVAL
----------
3
1 row created.
CUSTID CNAME
---------- --------------------------------------------------
CITY
-------------------------
1 XYZ
BLR
2 ABC
MUM
3 TYZ
BLR
CUSTID CNAME
---------- --------------------------------------------------
CITY
-------------------------
4 GUG
MUM
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
1 row created.
1 row created.
1 row created.
1 row created.
ID NAME
---------- -------------------------
5 bhavna
6 philip
7 simi
8 Jack
SQL> rollback;
Rollback complete.
NEXTVAL
----------
9
NEXTVAL
----------
10
NEXTVAL
----------
11
no rows selected
Sequence dropped.
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.
--what is a Transaction ?
account (bank)
Debit/Credit
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,.........)
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
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
--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
-- 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
Time Zone may also be set to using the Below Options Using ALTER SESSION SET
TIMEZONE
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
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.
--check:
select sessiontimezone, current_date from dual;
select sessiontimezone,current_timestamp from dual;
select sessiontimezone,localtimestamp from dual;
TZ_OFFSET(tz)
EXTRACT: without converting to character, we can use the extract function to get
the date part
20:24
DAY
HOUR
MINUTE
SECOND
D,H,M,S
The data type of INTERVAL YEAR TO MONTH stores a time interval in years and months.
It format is:
some Examples
INTERVAL '4 5:12:10.222' DAY to second (3) -- can specify upto 9 precision of a
second
http://www.dba-oracle.com/t_advanced_year_month_interval.htm
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
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;