0% found this document useful (0 votes)
45 views52 pages

Oracle Database Modes and Objects Guide

Uploaded by

renuranarenu1234
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views52 pages

Oracle Database Modes and Objects Guide

Uploaded by

renuranarenu1234
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

SQL ::

Oracle database : DB MODE

DB Logical view

DB objects

Database mode:

open (or) Read/write mode: users can use the DB ex: raw materials

Mount mode: DBA can use the DB for maintenance/upgradation/migration

Inactive mode: none can use the DB, this is where pre-requisites are defined.

Database—Tablespace—Segment—Block

Database object list: tables, views, Functions, Indexes, materialized views, Triggers, Stored Procedure,
Packages.

Table: where is the actual data lies.

Vies- is a query like a virtual table where u store ur query and it has two or more table and multiple
column. Table stored in the database is view

Functions: smallests logical unit

Indexes_: help retrieve the data from database as fast as possible.

Sequences: generate the series of number ,

Materialized views: the result of the query or view stored in database.

Triggers: action based on event.

Stored procedures: small procedural unit which give result after. Have procedural way to perform
action

Package: series of stored procedures

DATA : processed Information

Types of data:: CHAR, VARCHAR2,INTEGER, DECIMAL,DATE,TIMESTAMP,CLOB,BLOB,BFILE

CHAR:: Memory allocation 5 spaces. Accepts alphabet only. Maximum length is 5

VARCHAR 2: memory allocation 3 spaces. Accepts alphabet, number and symbol. Maximum length is
5.

Data type : Integer, Decimal :: integer- only whole numbers eg 173226

Decimal {Decimal (p,s)} eg 173222.62-Decimal (8,2)

Scale is exactly considered but precision is =>8 as defined.

Number -Number(p,s) Eg. 173226.62- Number (8,2)

Scale and precision are considered exactly as defined.


Data type:: date and timestamp:

Date -only dat[Link] DD-MON-YYYY

Timestamp: - date and time :: DD-MON-YYYY HH:MM:SS:SSSSSS

DATA TYPE : CLOB , BLOB, and BFILE

CLOB – character Large objects . Eg Resume

BLOB- Binary Large objects. Eg – Photo

BFILE- Binary file . Eg – Audio or video file.

CONSTRAINTS :: Primary key , foreign key, unique key, check

Primary key : only one column can be declared as primary key in a table. No duplicates are allowed.
No null values are allowed. Auto-Indexed ( marking it as important)

Unique key : more than one column can be declared as unique key in a table. No duplicate value
allowed. Null values are allowed. Auto indexed.

Foreign key – reference key: more than one column can be declared as foreign key is a table.
Duplicates allowed as they are referenced values. Null values are allowed as they are referenced
value.

When a primary column referenced in another table then in that another table it becomes a foreign
key.

Nut null : not supposed to be left blank. More than one column can be declared as not null column
in a table. Duplicate values are allowed. No null values are allowed.

CHECK : any column can be checked for its value. Eg salary>20000- this allow only the values greater
than 20000 in the declared column.

CREATE STATEMENTS ::

Type 1 :: CREATE TABLE ALL-TEST ( TEST_CODE VARCHAR( 10) , TEST_TYPE CHAR( 10), TEST_SUBJ-
MARK INT);

Type 2 : CREATE TABLE ALL _TEST2 ( TEST_CODE VARDCHAR(10) PRIMARY KEY, TEST_DOMAIN
VARCHAR (20) NOT NULL , TEST_TYPE CHAR(10) NOT NULL, TEST_SUBJ_CODE CHAR (4) UNIQUE,

TEST_SUBJ_MARK INT CHECK (TEST_SUBJ_MARK <100) ) ;

{ TEST_CODE VARCHAR (10) REFERENCES ALL_TEST2 ( TEST_CODE), --- to check foreign column

TYPE 3 to name constraint ::

CREATE TABLE TEST_TBL3 (

TEST_ID INT CONSTRAINT TID_PK PRIMARY KEY,


TEST_NAME VARCHAR ( 20 ) CONSTRAINT TNM_MN NOT NULL,

TEST_CODE VARCHAR( 10) CONSTRAINT TC_REF REFRENCES ALL_TEST3(TEST_CODE),

TEST_STATE CHAR ( 2) ,

TEST_SUBJ_CODE CHAR( 4) CONSTRAINT TSCD_UNQ UNIQUE,

TEST)_SUBJ_MARK INT CONSTRAINT TMRK_CHK CHECK( TEST_SUBJ_MARK <100) ) ;

TYPE 4 ::

CREATE TABLE ALL_TEST4 AS SELECT * FROM ALL_TEST1; -- to create a table by selecting a particular
table to require column of the table.

Data Definition language.: to define the database objects in a Database. :: CREATE , ALTER, DROP ,
TRUNCATE, RENAME.

ALTER Statements :: to add column

Add ::

ALTER TABLE ALL_TEST 1 ADD ( TEST_DOMAIN VARCHAR2 (20) );

ALTER TABLE ALL_TEST 1 ADD CONSTRAINT TC_PK_ADDED PRIMARY KEY (TEST_CODE);---- TO ADD
PRIMARY KEY

ALTER TEST_TABLE ADD CONSTRAINT TMRK_CHK_ADDED CHECK (TEST_SUBJ_MARK <100); --ADD


CHECK CONSTRAINT FOR VALUE.

ALTER TABLE TEST_TBL1 ADD CONSTRAINT TNM_NN_ADDED CHECK( TEST_NAME IS NOT NULL);--
ADD NOT NULL CONSTRAINT

ALTER TABLE TEST_TBL1 ADD CONSTRAINT TC_REF_ADDED FOREIGN KEY (TEST_CODE) REFERENCES
ALL_TEST1(TEST_CODE):---ADD FOREIGN KEY CONSTRAINT.

RENAME

ALTER TABLE TEST_TBL1 RENAME COLUMN TST_TYPE TO TEST_TYPE;----Rename column.

--MODIFY

ALTER TABLE ALL_TEST1 MODIFY TEST_DOMAIN VARCHAR2(15); ---MODIFY THE LEGTH OF THE
COLUMN ( when there is a data in the column cannot reduce the size of the column but we can
increase the length of the column by modify )

ALTER TABLE ALL_TEST1 MODIFY TEST_DOMAIN NOT NULL; --- Modify to not null constraint.

--Drop
ALTER TABLE TEST_TBL1 DROP COLUMN TEST_STATE; -- TO drop a column.

ALTER TABLE TEST_TBL1 DROP CONSTRATINT TNM_NN_ADDED; ( TNM_NM_ADDED Was the


constraint name. )

ALTER TABLE ALL_TEST1 DROP CONSTRAINT TC_PK_ADDED CASCADE; (( TO Drop primary key
constraint) CASCADE word tried to eliminate the foreign key as well).

Disable

ALTER TABLE TEST_TBL3 DISABLE CONSTRAINT TID_PK; ---DISABLE primary key . so it cut the
reference .

Enable :

ALTER TABLE TEST_TBL3 ENABLE CONSTRAINT TID_P;--- TO enable primary key – so that it can again
has the reference.

TRUNCATE STATEMENT ::: ( to remove the data from the table but the structure would be there )

TRUNCATE TABLE ALL_TEST1;

--

RENAME STATEMENT

RENAME TEST_TBLE3 TO TEST_TABLE3;

--

DROP STATEMENT :: To drop the table

DROP TABLE ALL_TEST4;

DML ( DATA MANIPULATION LANGUAGE) : to manipulate the data in the database.

INSERT

UPDATE

DELETE

--

INSERT STATEMENTS ::

TYPE 1 ONLY VALUES ::

INSERT INTO TEST_TBL VALUES(101, ‘101GRP1’ , ‘PSY’ , 92);

INSERT INTO TEST_TBL1 VALUES(102, ‘102GRP2’ , ‘GRP2’ , ‘APT’ , 87);

INSERT INTO TEST_TBL1 VALUES(1103, ‘103CVL’ , ‘QAPT’ , NULL);


TYPE 2 : PROMPT FOR INPUT :: ( Not that helpful )

INSERT INTO TEST_TBL1 VALUES (&TEST_NAME’ , ‘&TEST_CODE’ , ‘ &TEST_SUBJ_CODE’ , ‘&TEST


SUBJ_MARK);

TYPE 3 :: RESPECTIVE COLUMNS AND VALUES::

INSERT INTO TEST_TBL1 ( TEST_ID, TEST_NAME, TEST_CODE, TEST_SUBJ_CODE, TEST_SUBJ_MARK)


VALUES ( 103, ‘103CVL’, ‘CVL’ , ‘TAM’ , 93);

TYPE 4 :: INSERT WITH SELECT

INSERT INTO ALL_TEST2 SELECT*FROM ALL_TEST1;

TYPE 5 :: INSERT WITH SELECT BY LIST OF COLUMNS:

INSERT INTO TEST_TBL2(TEST_ID, TEST_NAME) SELECT TEST_ID , TEST_NAME FROM TEST_TBL1


WHERE TEST_CODE = ‘GRP1’;

UPDATE STATEMENTS ::

TYPE 1 :

UPDATE TEST_TBLE1 SET TEST_CODE=’GROUP1’ WHERE TEST_ID=101;

UPDATE TEST_TBL1 SET TEST_SUBJ_CODE=’QPT’ WHERE TEST_SUBJ_MARK IS NULL;

DELETE STATEMENTS ::

DELETE FROM TEST_TBL1 WHERE TEST_SUBJ_CODE=’FRN’;

DELETE FROM TEST_TBL1 WHERE TEST_SUBJ_MARK IS NULL;

TCL :: TRANSACTION CONTROL LANGUAGE

To control the transactions (or) any query executed. ::

COMMIT :: TO SAVE

ROLLBACK :: UNDO

SAVEPOINT

--

COMMIT; --SAVES THE TRANSACTIONS.

ROLLBACK; - -- UNDO/GOES BACK TO PREVIOUS COMMIT STATUS.


DCL ( DATA CONTROL LANGUAGE ) :: TO CONTROL THE ACCESS LEVELS OF DATA. ( can be executed
only by DBA)

GRANT

REVOKE

GRANT: Privileges u give to a particular user.

GRANT SELECT, INSERT, UPDATE, DELETE, CREATE ON HR, TEST_TBL1 TO MGR;--- here ‘MGR’ is
manager role

GRANT SELECT , INSERT , UPDATE , DELETE , CREATE ON HR.TST_TBL1 TO CHRIS; ---here ‘CHRIS’ Is
user with grant access.

GRANT SELECT, INSERT, UPDATE, DELETE , CREATE ON HR.TEST_TBL1 TO CHRIS WITH GRANT OPTION;
---- Here ‘CHRIS’ is user with GRANT ACCESS.

== CONNECT AS CHRIS AND GRANT ACCESS TO OTHER USER.

GRANT SELECT ON HR.TEST_TBL1 TO RAM; ---- Here chris gives select access to ram

== REVOKE

REVOKE CREATE, DELETE, INSERT, UPDATE, SELECT ON HR.TEST_TBL1 FROM CHRIS; ( RAM will also
loses access on the table as he is a successor of CHRIS

DRL : ( DATA RETRIEVAL LANGUAGE )

To retrieve the data from the database. ::

SELECT STATEMENTS ::

TYPE 1 :; RETERIEVAL OF ALL COLUMNS

SELECT * FROM TEST_TBL1;

SELECT TEST_ID, TEST_NAME, TEST_CODE, TEST_SUBJ_CODE, TEST_SUBJ_MARK FROM TEST_TBL1;

Type 2

RETRIEVAL OR PARTIAL NO OF COLUMNS::

SELECT TEST_ID, TEST_NAME, TEST_CODE FROM TEST_TBL1;

Type 3

CONDITIONED RETRIEVAL

SELECT * FROM TEST_TBL1 WHERE TEST_ID = 101;

Type 4
CONDITIONED ON NULL VALUE ::

SELECT TEST_NAME, TEST_SUBJ_CODE, TEST_SUBJ_MARK FROM TEST_TBL1 WHERE


TEST_SUBJ_MARK IS NULL;

Type 5 :

CONDITIONED ON OPERATORS {< , >, =, LIKE, BETWEEN, IN , NOT IN}

SELECT TEST_NAME, TEST_SUBJ_CODE, TEST_SUBJ_MARK FROM TEST_TBL1 WHERE


TEST_SUBJ_CODE LIKE ‘P%’;

Type 6

CONDITIONED AND ORDERED

SELECT TEST_NAME, TEST_SUBJ_CODE, TEST_SUBJ_MARK FROM TEST_TBL1 ORDER BY TEST_ID

Type 7

SIMPLE SUB_QUERIES

SELECT TEST_DOMAIN FROM ALL_TEST1 WHERE TEST_CODE IN (SELECT TEST_CODE FROM


TEST_TBL1 WHERE TEST_ID = 103 );

SQL FUNCTION :: sql functions are built into oracle database and are available for use in various
appropriate SQL statements.

SQL functions are different from the user_defined functions in PLSQL

Types of functions:: String/ char functions ,, numeric/math functions ,, date/time functions,,,


conversion functions.

--

String/char functions ::

CONCAT – to add 2 strings.

INITCAP – to capitalize only the first letter in the string.

INSTR – to find position of string in a string

SUBSTR – to extract part of the string

LENGTH – to find the length of the string

LOWER/UPPER – to convert the string to lowercase/uppercase

TRIM – to trim the string.


CONCAT ::

SELECT CONCAT ( ‘Technical’, ‘genius’) FROM DUAL;

INITCAP :: (Capitalise the initial letters)

SELECT INITCAP (‘learn sql’) FROM DUAL;

INSTR::

SELECT INSTR ( I’ have the papers’ , ‘e’ ) FROM DUAL;

(Result : 2 (the first occurrence of ‘e’)

SELECT INSTR (‘I have the papers’ , ‘e’ , 1, 1 ) FROM DUAL;

(Result : 2 (the first occurrence of ‘e’)

SELECT INSTR (‘I have the papers’ , ‘e’, 4 , 1) FROM DUAL;

Result : 11 ( the first occurrence of ‘e’)

---

SUBSTR

SELECT SUBSTR ( ‘Believe in yourself’ , 6 , 2) FROM DUAL;

SELECT SUBSTR( ‘Believe in yourself’ , 6) FROM DUAL;

SELECT SUBSTR(‘ Believe in yourself’ , 1 , 4) FROM DUAL;

SELECT SUBSTR(‘ Believe in yourself’ , 1, 4) FROM DUAL;

SELECT SUBSTR (‘Believe in yourself’, -3, 3) FROM DUAL ; ( - 3 means it will start from the end)

SELECT SUBSTR(‘Believe in yourself’ , -6, 3) FROM DUAL;

SELECT SUBSTR(‘Believe in yourself, -8,2) FROM DUAL;

--

LENGTH

SELECT LENGTH(NULL) FROM DUAL;

Result : NULL

SELECT LENGTH (‘ ‘) FROM DUAL;


Result :: NULL

SELECT LENGTH (‘ ‘) FROM DUAL;

Result : 1

SELECT LENGTH( ‘Hope’) FROM DUAL; ( count the length of the string)

--

LOWER

SELECT LOWER( ‘ HOW OR NEVER’) FROM DUAL;

SELECT LOWER (‘ NOW OR NEVER’) FROM DUAL;

--

UPPER

SELECT UPPER( ‘SIGN it before its too late’) FROM DUAL;

SELECT UPPER ( ‘ sleep is good’) FROM DUAL;

--

TRIM

SELECT TRIM( ‘ learn ‘ ) FROM DUAL; Result :: learn

SELECT TRIM ( ‘ ‘ FROM ‘ learn ‘ ) FROM DUAL; result :: learn

SELECT TRIM ( LEADING ‘0’ FROM ‘000123’) FROM DUAL; ( result 123 .. leading means prior to the
that)

SELECT TRIM( TRAILING ‘1’ FROM ‘Learn1’ ) FROM DUAL; result = Learn

SELECT TRIM( BOTH ‘1’ FROM ‘123Learn111’) FROM DUAL; result= 23learn

NUMERIC/MATH FUNCTIONS

COUNT- To count the number of records.

ROWNUM- To get the row number of the selected result or a table.

SUM – To sum up the values of any selected column.

TRUNC-To truncate/ trim the numeric value.

--

COUNT
SELECT COUNT (COUNTRY_ID) FROM CONUNTRIES; result--- 25.

--

MAX

SELECT MAX( Salary) AS ‘’Highest Salary” FROM employees;

--

ROWNUM

SELECT ROWNUM, EMPLOYEES. *FROM EMPLOYEES WHERE EMPLOYEE_ID > 115; result :: list of
records having employee_id greater than 115.

--

SUM

SELECT SUM( SALARY ) AS “Total Salary” FROM EMPLOYEES WHERE SALARY > 10000;

--

SUM WITH DISTINCT – (using the distinct – if there are 4 salaries wd same amount it will consider
only one while adding)

SELECT SUM (DEISTINCT salary) AS “Total salary” FROM employee WHERE SALARY> 10000;

--

TRUNCATE ( eliminate the decimal number and gives whole number)

SELECT TRUNC (125.815) FROM DUAL; result= 125

SELECT TRUNC(125.815 , 1) FROM DUAL; result = 125.8

SELECT TRUNC(125.815, 2) FROM DUAL; result = 125.81

SELECT TRUNC(125.815, -1) FROM DUAL; result = 120 – so here -1 represents unit place which is 5 so
5 would be subtracted from 125.

SELECT TRUNC(125.851, -2) FROM DUAL; result = 100 -- -2 represent tens value which is here 25

SELECT TRUNC(125.851, -3) FROM DUAL – result==0

Date/ time functions

SYSDATE- To display system date

SYSTIMESTAMP- To display system date and time

CURRENT_DATE- To display current date

CURRENT_TIMESTAMP- To display current date and time.

LAST_DAY – To display last date of the month or any given date value
--

Date Function

==SYSDATE

SELECT SYSDATE FROM DUAL;

==SYSTIMESTAMP

SELECT SYSTIMESTAMP FROM DUAL;

==CURRENT DATE

SELECT CURRENT_DATE FROM DUAL;

==CURRENT_TIMESTAMP

SELECT CURRENT_TIMESTAMP FROM DUAL;

==LAST_DAY

SELECT LAST_DAY(SYSDATE) FROM DUAL;

CONVERSTION FUNCTIONS

TO_DATE ( to have data in date format)

TO_CHAR ( to have data in character format)

TO_NUMBER ( ( to have data converted into number)

=== TO DATE

SELECT TO_DATE( 2015/05/15 [Link]’ , ‘YYYY/MM/DD HH:MM:SS’) FROM DUAL;

SELECT TO_DATE (‘070903’ , ‘MMDDYY’) FROM DUAL;

SELECT TO_DATE( ‘2003/07/09’ , ‘YYYY/MM/DD’) FROM DUAL;

SELECT TO_DATE (’070903’, ‘YYYYMMDD’) FROM DUAL;

== TO CHAR

SELECT TO CHAR(1210.73, ‘9999.9’) FROM DUAL ; result = 1210.7

SELECT TO_CHAR(1210.73, ‘$9,999.00’) FROM DUAL; result = $1,210.73

SELECT TO_CHAR( 21, ‘000099’) FROM DUAL; result = 00021

=== TO NUMBER

SELECT TO_NUMBER( ‘1210.73’, ‘9999.99’) FROM DUAL; result – 1210.73

SELECT TO_NUMBER( ‘546’ , ‘999’)FROM DUAL; result- 546


JOIN :: JOINS are used to retrieve data from multiple tables. It is performed whenever two or more
tables are joined in SQL statement. TYPES OF JOINS :

Oracle INNER JOIN ( or sometimes called simple join)

Oracle LEFT OUTER JOIN ( or sometimes called LEFT JOIN)

Oracle RIGHT OUTER JOIN ( or sometimes called RIGHT JOIN)

Oracle FULL OUTER JOIN ( or sometimes called FULL JOIN)

===

Join statements

---

INNER JOIN- MATCHING RECORDS ONLY

SELECT E.FIRST_NAME, D.DEPARTMENT_NAME.

FROM EMPLOYEES E

INNER JOIN DEPARTMENTS D

ON E. DEPARTMENT_ID=D. DEPARTMENT_ID;

----

LEFT OUTER JOIN- ALL RECORD FROM LEFT TABLE AND MATCHING FROM RIGHT TABLE

SELECT E.FIRST_NAME, D.DEPARTMENT_NAME

FROM EMPLOYEES E

LEFT OUTER JOIN DEPARTMENTS D

ON E.DEPATMENT_ID=D.DEPARTMEN_ID;

----

RIGHT OUTER JOIN- ALL RECORDS FROM RIGHT TABLE AND MATCHING RECORDS FROM LEFT TABLE

SELECT E.FIRST_NAME , D.DEPARTMENT_NAME

FROM EPLOYEES E

RIGHT OUTER JOIN DEPARTMENTS D

ON E.DEPATRMENT_ID=D.DEPATRMENT_ID;

---
FULL OUTER JOIN- ALL RECORDS FROM BOTH LEFT AND RIGHT TABLE ( INCLUDING UNMATCHED
RECORDS)

SELECT E.FIRST_NAME, D.DEPARTMENT_NAME

FROM EMPLOYEE E

FULL OUTER JOIN DEPARTMENTS D

ON E. DEPARTMENT_ID=D.DEPARTMENT_ID;

DBMS ( DATA BASE MANAGEMENT SYSTEM ) ::

DATA : Known fact, recorded with implicit meaning

Database : collection of logically related data

Database Management System: A computerized record-keeping system.

Note :: computer -based information system can serve a variety of complex tasks in a coordinated
manner.

Such system handles large volumes of data, multiple users and several applications for activities
occurring in a central and / or distributed environment.

DBMS provides for storage, retrieval and updation of data in an organized manner.

Goals of DBMS :: to provide an environment which will efficiently provide access to data in a
database. .. Enforce information security – database security , concurrency control, cash recovery.

General Purpose:: - defining database-specifying the types of data to be stored in the database.

- Constructing database-storing the data.


- Manipulating database-querying the DB , updating the DB and generating reports from DB.

== why database ??

File management system had drawbacks which lead to database:: - data is separated for every
individual program.

- Data can be duplicated as these are for individual program.


- No uniformity can be found in the data.
- All the data would have been arranged as per the need of the specific program.
- No security control.

Benefits of DBMS ::

- Redundancy is reduced
- Inconsistency is avoided
- Data is shared
- Standard is enforced
- Security is applied
- Integrity is maintained.
- Data independency is provided.
Database management system :: an agent that allows communication of the users with the physical
database and the operating system ( without the users knowing how it is done).

Metadata is data about the DATA stored in DB , i.e. structure of data stored in the DB.

3 Broad classes of users ---

- Application programmers:: programmers write application to use the database.


- End users: users who query the DB using the database Applications.
- Database Administrators ( DBA) : Administrators create the actual DB and maintain the DB
( like performance, technical services needed to enforce the policy decisions) .

3 types of DB systems :: DATA MODELS

- Data model :: the main tool which provides the data abstraction ( database approach ) by
hiding the details of data storage which is not needed by the users. i.e., set of concepts used
to describe the structure of the database.

Categories : as per data structure. ==

- high – level/ conceptual- provides details on the way users perceive the data. Using Entity ,
Attribute and Relationship.

- Low-level /Physical – provides details on how data is stored. Indexing which makes the
search efficient based on the structure.
- Representational/ implementation- Between above 2 extremes, that provides details on both
which are understood by end user and not too many details are hidden.

Database architecture::

There are 3 levels of architecture::

- External – the one at the user end which is concerned how the user views the data.
- Internal- the one at the physical DB end which is concerned on how the data is stored in DB.
- Conceptual – the one between the above mentioned which is concerned on how they are
connected.

SCHEMA :: description of data in terms of data model

3 level DB Architecture::

- External schema
- Conceptual schema
- Internal schema

Types of database models:: the most known record-based models are Hierarchical , Network and
Relational models.

Major Types:

- Hierarchical – information management system from IBM


- Network- integrated data store
- Relational – oracle, Sybase, MySQL , etc.
- Object oriented – versant object database, object store and ZODB
=== Relational database management system ( relational model ) :: it is a system in which :

- The data is perceived by the user as tables ( and nothing but tables)
- The operators at the user’s disposal – E.g. for data retrieval – are operators that generate
new tables from old, and those include at least SELECT, PROJECT and JOIN.

CODD RULES ::

- Information rule
- Guaranteed access rule
- Systematic treatment of null values
- Dynamic on-line catalog based on the relational model
- Dynamic on-line catalog based on the relational model
- View updating rule
- High level insert update and delete rule
- Physical data independence rule
- Logical data independence rule
- Integrity independency rule
- Distribution rule
- Non subversion rule

Features ::

- The ability to create multiple relations ( tables) and enter data into them.
- An interactive query language
- Retrieval of information stored in more than one table
- Provide a catalog or dictionary, which itself consists of tables( called system tables)

Important terms ::

- Relation- a table
- Tuple – a row in a table
- Attribute- a column in a table
- Degree- a number of attributes
- Cardinality – number of tuples
- Primary key- a unique identifier for the table
- Domain- a set of possible values that a given attribute can have

Keys ::

- Simple key Vs composite key – single attribute Vs combination of attributes


- Key – an attribute or set of attributes whose values uniquely identity each entity
- Super key- adding additional attributes to a key, an augmented key is super key
- Candidate key- combination of attributes. Candidate key are unique key and can be part of
super key

canditat

Key :: to identify a particular attribute.

E-R modelling

- Entity : anything that exists and distinguishable


- Entity set : a group of similar entities
- Attribute: properties that describe the entity
- Relationship: an association b/w the entities.

Notation

Entity type : rectangular shape

Relationship type : represented in diamond shape

Weak entity : thickened border with rectangular shape.

Attribute : in oval shape

Weak relationship : thicken border wd diamond shape.

== Relationship types :: 1-1 relationship ,, 1- many relationship , many-1 relationship ,, many-many


relationship

ER Modelling with key constraint ::

Emp ID Deptid

ename Employees Departments dename


Works
depit in
location

Deptid is the key to connect both entity.

=== Ternary relationship :::3 entities with a single relationship

== participation constraints :: how the relationship is establish and what kind of relationship they
have.

== Weak Entities :: part of entities are used

== Is A HIERARCHIES :: an entity having a relationship and branching out. The entity having its own
attribute and then branching out and not having a direct relation.

== Aggregation::

Some constraints cannot be captured in ER Diagrams::

- Functional dependencies
- Inclusion dependencies
- General constraints.
NORMALIZATON:: decomposing a larger, complex table into several smaller , simpler ones.

- Design the database without any anomalies and reduced redundancy.


- Types of normal forms: -- First Normal Form ( INF)
- -- Second Normal Form ( 2NF)
- -- Third Normal form ( 3NF)
- ---Boyce-codd Normal Form( BCNF/4NF)

Why normal forms ? – to understand that how complex our data base is.

- To know in which state we are in.


- This will allow us to understand present critically in the database.
- To ensure that all the operations related to database performs smoothly.
- Issues with redundancy.: - -- It is the main root cause for all the anomalies
- ---- INSERT, UPDATE and DELETE anomalies
- ---- Huge memory loss.

Insert anomalies – says that the data needs to be reentered for every new subjective data.

Update anomalies- says that the data needs to be updated in multiple places which in turn increase
the cost of the performance of the application .

Delete anomalies- says that the data might get lost due to delete actions for the entire record
including the subjective data.

Hence, we need normalization , to avoid all the anomalies.

=== First normal form :: if all the values in a relation are of atomic in nature, then it can be
considered as it is 1st normal form.

Functional dependency :- provides a formal mechanism to express constraints b/w attributes

- Every key should be functionally dependent on the primary key.


- To check the functional dependencies:: we need to make a primary key
--- and check all the other attributes are functionally dependent on it
--- If any attribute found unsatisfied, then remove and associate to another relation.
- FULL DEPENDENCY :: If there is a primary key with combination of more than 2 attributes,
then dependency comes into picture
- PARTIAL DEPENDENCY :: if there is a primary key with combination of 2 attributes but there
are other attributes which are dependent on only one, then it is partial dependency.

Second normal form ::: any relation to be in 2NF :: it should be in INF. All the attribute should
have full dependency on primary key. No partial dependencies allowed, hence it must be
removed.

= Transitive dependency :: if there is a primary key ( composite) with combination of 2 attributes


but there are attributes that are dependent on other attributes which are in turn dependent on
primary key , then it is transitive dependency.

= third normal form:: any relation to be in 3 NF: it should be in 2NF. No transitive dependencies,
hence it must be removed.

All the attributes should be truly dependent only on the primary key not even partially on other
attributes.
==BOYCE-CODD NORMAL FORM ( BCNF) :: the intention of having BCNF, is if in case there are
composite or overlapping candidate keys. It is said BCNF , only if every determinant is a
candidate key.

==== DENORMALIZATION ::

Sometimes we need to compromise with the needs.

- With normalized forms, we need more joins at the reporting end.


- With more joins, system will become slow
- Hence, for customer satisfaction we need to prefer de-normalized form
- We need to merge back the table , so we could get the data quickly
- Hence, we need to accept the redundancy.

Pros :: it can speed up the querying or data retrieval

It does not produce severe update anomalies.

SELECT * FROM EMPLOYEES;

SELECT EMPLOYEE_ID , SALARY, SALARY +100 FROM EMPLOYEES;

SELECT EMPLOYEE_ID, SALARY, 12*(SALARY +100) FROM EMPLOYEES;

SELECT EMPLOYEE_ID, SALARY, 12*SALARY +100 FROM EMPLOYEE;

SELECT EMPLOYEE_ID, SALARY, SALARY + ( SALARY*COMMISSION_PCT) FROM EMPLOYEE;

SELECT DITINCT COMMISSIO_PCT FROM EMPLOYEES;

SELECT FIRST_NAME | | ‘ ‘ ||LAST_NAME FROM EMPLOYEES; result :: Sunder Ande

SELECT FIRST_NAME||q’ [‘s]’||’ ‘||LAST_NAME FROM EMPLOYEES; result :: Ellen’s Abel

SELECT FIRST_NAME FROM EMPLOYESS WHERE EMPLOYEE_ID = 106;

SELECT FIRST_NAME FROM EMPLOYEES WHERE EMPLOYEE_ID <> 106;

SELECT EMPLOYEE_ID FROM EMPLOYEES WHERE SALARY > 220000;

SELECT FIRST_NAME FROM EMPLOYEES WHERE EMPLOYEE_ID <106;

SELECT EMPLOYEE_ID FROM EMPLOYEES WHERE SALARY >=22000;

SELECT FIRST_NAME FROM EMPLOYEES WHERE EMPLOYEE_ID <=106;

( DISTINCT :: Gives unique value no duplication) .

SELECT FIRST_NAME FROM EMPLOYEE WHERE EMPLOYEE_ID in ( 106, 201, 100, 111);

SELECT EMPLOYEE_ID FROM EMPLOYEES WHRE FIRST_NAME LIKE ‘J%’ ;

SELECT EMPLOYEE_ID FROM EMPLOYEES WHRE FIRST_NAME LIKE ‘_a%’;

SELECT EMPLOYEE_ID FROM EMPLOYEES WHERE COMMISSION_PCT IS NULL;

SELECT EMPLOYEE_ID FROM EMPLOYEES WHERE COMMISSION_PCT IS NOT NULL;


SELECT EMPLOYEE_ID FROM EMPLOYEES WHERE FIRST_NAE LIKE ‘_a%’ AND DEPARTMENT_ID =
50;

SELECT EMPLOYEE_ID FROM EMPLOYEES WHERE FIRST_NAME LIKE ‘_a%’ AND DEPARTMENT_ID
= 50;

SELECT EMPLOYEE_ID FROM EMPLOYEES WHERE FIRST_NAME LIKE ‘_a%’ OR DEPARTMENT_ID


=90;

SELECT EMPLOYEE_ID FROM EMPLOYEES WHERE DEPARTMENT_ID NOT IN (50, 90 , 60);

SORTING :: To display the result in an orderly way.

- Numeric values are displayed with the lowest values first ( 1 to 999)
- Date values are displayed with the earliest value first ( 01-jan -92 before 01-jan-95)
- Character values are displayed in the alphabetical order
- Null values are displayed last for ascending sequences and first for descending sequences
- Can also sort by a column that is not in the SELECT list.
- The default sort order is ascending
- Can use column alias in the ORDER BY clause
- Sorting by using the column’s position
- Sorting by multiple columns

SELECT EMPLOYEE_ID, DEPARTMENT_ID, JOB_ID FROM EMPLOYEES ORDER BY EMPLOYEE_ID;

SELECT EMPLOYEE_ID , DEPARTMENT_ID, JOB_ID FROM EMPLOYEES ORDER BY EMPLOYEE_ID DESC;

SELECT EMPLOYEE_ID, DEPARTMENT_ID, JOB_ID AS JOB FROM EMPLOYEES ORDER BY JOB DESC;

SELECT EMPLOYEE_ID , DEPARTMENT_ID, JOB_ID FROM EMPLOYEES ORDER BY 2;

SELECT EMPLOYEE_ID, DEPARTMENT_ID, JOB_ID FROM EMPLOYEES ORDER BY EMPLOYEE_ID,


DEPARTMENT_ID DESC;

SUBSTITUTION VARIABLES ::

To query for different values

Use substitution variables to temporarily store values with single-ampersand ( &) and double-
ampersand (&&)

Use substitution variables to supplement in:

-WHERE clause

- ORDER BY clause

-COLUMN NAME

-TABLE NAME

-ENTIRE SELECT STATEMENT

-DEFINE STATEMENT
-VERIFY COMMAND

Syntax :

SELECT & COLUMN_NAME

FROM & TABLE_NAME

WHERE & CONDITION

ORDER BY & ORDER_COLUMN;

SELECT EMPLOYEE_ID, MANAGER_ID FROM EMPLOYEES WHERE DEPARTMENT_ID =


&DEPARTMENT_ID;

SELECT &EMPLOYEE_ID , MANAGER_ID FROM EMPLOYEES WHERE DEPARTMENT_ID= 90;

SELECT EMPLOYEE_ID , MANAGER_ID FROM &TABLE-NAME WHERE DEPARTMENT_ID = 90;

SELECT EMPLOYEE_ID, MANAGER_ID FROM EMPLOYEES WHERE DEPARTMEN_ID = 90 ORDER BY


&ORDER_COLUMN DESC;

---

DEFINE DEPARTMENT_ID = 90

SELECT EMPLOYEE_ID, MANAGER_ID

FROM EMPLOYEES

WHERE DEPARTMENT_ID= &DEPARTMENT_ID;

UNDEFINCE DEPARTMENT_ID

---

SET VERIFY ON

SELECT EMPLOYEE_ID , LAST_NAME, SALARY

FROM EMPLOYEES

WHERE EMPLOYEE_ID= &EMPLOYEE_NUMBER;

FUNCTIONS :: -manipulate data items

- Accept arguments ( user-supplies, variable, column and Expression) and return one value.
- Return one result per row
- Return value data type may be different
- Can be nested
- Can be used in SELECT, WHERE, and ORDER BY clauses.

Types of Functions::

- String/Char Functions
- Numeric/Math Functions
- Date/time functions
- Conversion function
- General functions.

General Functions ::

- NVL function :: converts a null value to an actual value. Data types must match
- NVL2 function :: if expr1 (source) is not null, it returns expr2(replace value)

If expr1(source) is null, it returns expr3(replace value)

The argument can have any data type.

- NULLIF Function:: compares two expressions and returns null if they are equal; returns the
first expression if they are not equal . Logically equivalent to CASE function.

NVL ::

SELECT EMPLOYEE_ID , MANAGER_ID

NVL ( COMMISSION_PCT, 0) ‘’COMM’’,

NVL ( COMMISSION_PCT, 0) +20 “COMMISSION”

FROM EMPLOYEES;

So here ( commission pct , 0 means if there is null value the null will replace wd 0 )

NVL2 ::

SELECT LAST_NAME, SALARY, COMMISSION_PCT,

NVL2(COMMISSION_PCT, ‘SAL+COMM’ , ‘SAL’) INCOME

FROM EMPLOYEES

WHERE DEPARTMENT_ID IN ( 50, 80) ;

Here if commission pct null it will show sal and if it has a value it will be as sal + comm

NVLIF: :

SELECT FRIST_NAME, LENGTH(FIRST_NAME) “EXPR1”,

LAST_NAME, LENGTH(LAST_NAME) “EXPR2” ,

NULLIF ( LENGTH(FIRST_NAME), LENGTH(LAST_NAME) ) RESULT

FROM EMPLOYEES; result :: if the length of first and last names are equal then the result will null.

COALESCE FUNCTION :: returns the first non-null expression in the expression list.

Data type must be same.


SELECT LAST_NAME, EMPLOYEE_ID,

COALESCE( TO_CHAR( COMMISSION_PCT), TO_CHAR( MANAGER_ID); ‘No commission and no


manager’ ) FROM EMPLOYEES; result :: if commission pct and manager_id both are null then this
expression will be written.

SELECT LAST_NAME, SALARY, COMMISSIO_PCT,

COALESCE ( ( SALARY + (COMMISSION_ PCT*SALARY) ) , SALARY+2000, SALARY) “New Salary “

FROM EMPLOYEES;

NESTING FUNCTIONS ::

Single- Row functions can be nested to any level. Nested functions are evaluated from the innermost
to the outermost level.

SELECTT LAST_NAME, UPPER(CONCAT(SUBSTR(LAST_NAME, 1 , 8) , ‘_US’ ))

FROM EMPLOYEES; result :: ABEL US

CONDITIOANL EXPRESSION ::

METHODS :: Provide the use of the IF-THEN -ELSE logic within a SQL statement

- CASE expression
- DECODE function

CASE EXPRESSION :: Facilitates conditional inquiries by doing the work of an IF-THEN-ELSE Statement

The expressions must be of the same data type.

SELECT EMPLOYEE_ID , JOB_ID, SALARY ,

CASE JOB_ID

WHEN ‘AD_PRESS’ THEN 1000+SALARY

WHEN ‘AD_VP’ THEN 5000+SALARY

WHEN ‘IT_PROG’ THEN 8000+SALARY

WHEN ‘FI_ACCOUNT’ THEN 20000+SALARY

WHEN ‘PU_CLERK’ THEN 4000+SALARY

ELSE SALARY

END “Revised Salary”

FROM EMPLOYEES;
DECODE FUNCTIONS:: Facilitates conditional inquiries by doing the work of a case expression or an
IF-THEN-ELSE statement

If the default value is omitted, a null value is returned where a search value does not match any of
the result values.

SELECT LAST_NAME, SALARY,

DECODE (TRUNC(SALARY/2000, 0) ,

0, 0.00,

1, 0.09,

2, 0.20,

3, 0.30,

4, 0.40,

0.45) TAX_RATE

FROM EMPLOYEES

WHERE DEPARTMENT_ID = 80;

GROUP FUNCTIONS :: Group functions operate on sets of rows to give one result per group

Types of group funcions:: avg, count, max, min, stddev, sum , variance.

- All group functions ignore NULL values , but NVL functions forces to include NULL values
- Divide the table into smaller groups
- Cannot use column alias in the GROUP clause
- Use WHERE conditions to exclude the rows before grouping , but cannot use for restriction
- Use HAVING clause to restrict the groups
- Use ORDER BY clause to display order
- GROUP BY clause is mandatory is Nesting-Group functions.

SELECT DEPARTMENT_ID, COUNT(LAST_NAME)

FROM EMPLOYEES

GROUP BY DEPARTMENT_ID

- SELECT DEPARTMENT_ID , COUNT(LAST_NAME)


FROM EMPLOYEES
GROUP BY DEPARTMENT_ID
ORDER BY DEPARTMENT_ID;

- SELECT DEPARTMENT_IF, AVG( SALARY)


FROM EMPLOYEES
GROUP BY DEPARTMENT_ID;
HAVING AVG ( SALARY) >8000;
- SELECT JOB_ID, SUM(SALARY) PAYROLL
FROM EMPLOYEES
WHERE JOB_ID NOT LIKE ‘&REP&’
GROUP BY JOB_ID
HAVING SUM( SALARY) > 13000
ORDER BY SUM (SALARY) ;

- SELECT MAX ( AVG(SALARY) )


FROM EMPLOYEES
GROUP BY DEPARTMENT_ID;

TYPES OF JOINS ::

Oracle joins ::

Equi joins

Non-Equi joins

Outer joins( Left or Right)

Self join

Cross join

Natural join

Full outer joins.

--

Ambiguous Columns ::

Use table prefixes to qualify column names that are in multiple tables

Use table prefixes to improve performance

Instead of full table name prefixes, use table aliases

Table Alias gives a table a shorter name : -keeps SQL code smaller, uses less memeory

Use column aliases to distinguish columns that have identical names, but reside in different tables.

--

NATURAL JOIN ::

The join can happen on only those columns having same data type and column names

SELECT EMPLOYEE_ID , TO CHAR(HIRE_DATE, ‘fmDD Month YYYY’) as HIRE_DATE, JOB_ID ,


DEPARTMENT_ID

FROM EMPLOYEES

NATURAL JOIN DEPARTMENTS;


USING clause:

-Joins with USING clause, used when column names are same but not the data types

-Also, simple join or Equi join or Inner join are all same.

- But do not qualify a column that is used in USING clause.

- If the same column is used elsewhere in the SQL statement, do not alias it.

SELECT EMPLOYEE_ID, TO_CHAR( HIRE_DATE, ‘fmDD Month YYYY’) as HIRE_DATE, JOB_ID ,


DEPARTMENT_ID

FROM EMPLOYEES JOIN DEPARTMENTS

USING (DEPARTMENT_ID);

ON clause::

- Use ON clause to specify arbitrary conditions or specify column to join.


- The join condition is separated from search conditions
- ON clause makes code easy to understand.

SELECT E.EMPLOYEE_ID, TO_CHAR(E.HIRE_DATE, ‘fmDD Month YYYY’ ) as HIRE_DATE, E.JOB_ID , D.


DEPARTMENT_ID

FROM EMPLOYEES E JOIN DEPARTMENTS D

ON E.DEPARTMENT_ID = D.DEPARTMENT_ID

WHERE E. DEPARTMENT_ID = 80;

SELF Join ::

- Also referred as join within table


- The ON clause used to join columns that have different names, within the table or in
different table.

SELECT E.FIRST_NAME| | ‘ ‘ || E.LAST_NAME EMPLOYEE, M.FIRST_NAME|| ‘ ‘ | |M.LAST_NAME


MANAGER

FROM EMPLOYEES E JOIN EMPLOYEES M

ON E. MANAGER_ID = M.EMPLOYEE_ID;

==TO join 3 tables ::

SELECT E.FIRST_NAME| | ‘ ‘ | |E.LAST_NAME as EMPLOYEE_NAME, D.DEPARTMENT_NAME, [Link]

FROM EMPLOYEES E
JOIN DEPARTMENTS D

ON E.DEPARTMENT_ID = D. DEPARTMENT_ID

JOIN LOCATIONS L

ON D.LOCATION_ID = L.LOCATOION_ID.

= SELECT E. FIRST_NAME|| ‘ ‘ ||E.LAST_NAME as EMPLOYEE_NAME, D.DEPARTMENT_NAME, [Link]

FROM EMPLOYEES E

JOIN DEPARTMENTS D

USING ( DEPARTMENT_ID)

JOIN LOCATIONS L

USING (LOCATION_ID) ;

=== Joining two tables with more than one where conditions

SELECT E.EMPLOYEE_ID, TO_CHAR ( E.HIRE_DATE, ‘fmDD Month YYYY’) as HIRE_DATE, E.JOB_ID,


D.DEPARTMENT_ID

FROM EMPLOYEES E JOIN DEPARTMENTS D

ON E. DEPARTMENT_ID = D . DEPARTMENT_ID

WHERE E.DEPARTMENT_ID = 80

AND JOB_ID = ‘SA_REP’ ;

== NON-EQUI JOIN ::

- The relationship is obtained using an operator other than the equality ( = ) operator
- Table alias can be used for performance reasons, not because of possible ambiguity.

SELECT E.LAST_NAME, [Link], J.GRADE_LEVEL

FROM EMPLOYEES E JOIN JOB_GRADES J

ON E.MANAGER_ID = M. EMLOYEE_ID;

== CROSS JOIN ::

- Formed when join condition is omitted


- Formed when join condition is invalid
- All rows in the first table are joined to all rows in second table
- Always include a valid join condition if you want to avoid a cartesian product
- The cartesian product between 2 tables is also called as CROSS join

SELECT LAST_NAME, DEPARTMENT_NAME


FROM EMPLOYEES

CROSS JOIN DEPARTMENTS;

SUB- QUERY :: A sub-query is a SELECT statement that is embedded in the clause of another SELECT
statement. Can place the sub-query in number of SQL clauses:

- WHERE
- HAVING
- FROM

It is also referred as Nested select, sub-select and Inner select

Sub-query executes first, and then the main query

NOTE : Comparison conditions is of 2 classes:

- Single row operators ( = , <> , <, <=,>, >=)


- Multiple row operators ( IN, ANY, ALL, EXISTS)

Types of sub-queries ::

- Single row – queries that return only one row from the inner SELECT statement
- MULTIPLE ROW – queries that return more than one row from inner SELECT statement

NOTE :: The outer and inner query can be from different tables.

= SELECT FIRST_NAME||’ ‘||LAST_NAME

FROM EMPLOYEES

WHERE EMPLOYEE_ID = (SELECT MANAGER_ID FROM EMPLOYEES WHERE LAST_NAME =


‘Tobias’) ;

== = SELECT FIRST_NAME||’ ‘||LAST_NAME

FROM EMPLOYEES

WHERE SALARY > (SELECT SALARY FROM EMPLOYEES WHERE DEPARTMENT_ID = 40) ;

== SELECT FIRST_NAME||’ ‘||LAST_NAME

FROM EMPLOYEES

WHERE DEPARTMENT_ID = (SELECT DEPARTMENT_ID FROM DEPARTMENTS WHERE


DEPARTMENT_NAME = ‘Shipping’)

AND JOB_ID = (SELECT JOB_ID FROM JOBS WHERE JOB_TITLE = ‘Stock Manager’ ) ;

SELECT DEPATMENT_ID, MIN(SALARY)

FROM EMPLOYEES
GROUP BY DEPARTMENT_ID

HAVING MIN ( SALARY) > (SELECT MIN ( SALARY ) FROM EMPLOYEES WHRE DEPARTMENT_ID =
50 ) ;

== SELECT EMPLOYEE_ID, LAST_NAME , JOB_ID, SALARY

FROM EMPLOYEES

WHERE SALARY < ANY ( SELECT SALARY FROM EMPLOYEES WHERE JOB_ID = ‘IT_PROG’)

AND JOB_ID <> ‘IT_PROG’ ;

== SELECT EMPLOYEE_ID, LAST_NAME, JOB_ID, SALARY

FROM EMPLOYEES

WHERE SALARY < ALL ( SELECT SALARY FROM EMPLOYEES WHERE JOB_ID = ‘IT_PROG’)

AND JOB_ID <> ‘IT_PROG’ ;

== SELECT * FROM EMPLOYEES

WHERE NOT EXISTS ( SELECT*

FROM DEPARTMENTS

WHERE DEPARTMENTS. DEPARTMENT_IF = EMPLOYEES . DEPARTMENT_ID);

SET OPERATORS ::

Set operators combine the results of 2 or more component queries into one result.

- Queries having set operators are called as compound queries.


- Guidelines::
 The expressions in the select lists must match in number
 The data type of each column in the second query must match the data type of its
corresponding column in the first query
 Parenthesis can be used to alter the sequence of execution
 Order by clause can appear only at the very end of the statement

Key notes::

- Column names from the first query appear in the result.


- Duplicate rows are automatically eliminated except in union all.
- The output is sorted in ascending order by default except in union all.

Union operator ::

- Returns rows from both queries after eliminating duplications


- Number of columns being selected must be same
- Data types of selected columns must be in the same data type group
- Column names need not be same
- Union operators over, all of the selected columns
- NULL values are not ignored while checking the duplicates
- Output is sorted in ascending order.

SELECT DEPARTMENT_ID

FROM EMPLOYEES

UNION

SELECT DEPARTMENT_ID

FROM DEPARTMENTS ORDER BY DEPARTMENT_ID;

Union all operator::

- Returns rows from both queries, including all duplicates


- Both UNION and UNION ALL are same except below 2
 Duplicate rows are not eliminated
 Output are not sorted by default

SELECT DEPARTMENT_ID

FROM EMPLOYEES

UNION ALL

SELECT DEPARTMENT_ID

FROM DEPARTMENTS ORDER BY DEPARTMENT_ID;

Intersect Operator::

- Returns rows that are common to both queries


- Number of columns and the data types of the columns must be identical
- Column names can be different
- Revising the order of the tables, does not change the result
- NULL values are not ignored

SELECT EMPLOYEE_ID, JOB_ID

FROM EMPLOYEES

INTERSECT

SELECT EMPLOYEE_ID, JOB_ID

FROM JOB_HISTORY;

Minus operator ::
- Returns all the distinct rows selected by the first query, but not present in the second query
result set.
- Number of columns must be same
- Data type must be from same data type group
- Column names can be different

SELECT DEPARTMENT_ID

FROM EMPLOYEES

MINUS

SELECT EMPLOYEE_ID, JOB_ID

FROM JOB_HISTORY;

Matching the select statements::

- For UNION operator, must match the number of columns and data types.
- If column is not present in other table have to use the DUMMY table to match the SELECT
statement to perform UNION operator.

SELECT LOCATION_ID, DEPARTMENT_NAME “DEPARTMENT”, TO_CHAR (NULL) “Warehouse


Location”

FROM DEPARTMENTS

UNION SELECT LOCATION_ID, TO_CHAR(NULL) “Department” , STATE_PROVINCE

FROM LOCATIONS;

Order by in SET Operations::

- The order by clause can appear only once at the end of the compound query
- The component queries cannot have independent order by clauses
- The order by recognizes only the columns of the first SELECT query
- By default, the first column of the first SELECT query is used to sort the output in an
ascending order.
- Cannot use second query to sort the result.

SELECT EMPLOYEE_ID, DEPARTMENT_ID

FROM EMPLOYEES

UNION

SELECT DEPARTMENT_ID, 0

FROM DEPARTMENTS

ORDER BY DEPARTMENT_ID DESC;


READ CONSISTENCY

- Read consistency guarantees a consistent view of data at all times.


 Read operation ( SELECT)
 Write operation( INSERT, UPDATE, DELETE)
- Changes made by one user do not conflict with changes made by another user
- It ensures that on the same data
 Readers do not wait for writers
 Writers do not wait for readers
 Writers wait for writers.

FOR UPDATE IN SELECT ::

- SELECT will not lock the records.


- Only the records which has been changed but not committed are locked, but still others can
see the previous commit status of those records.
- If in case you want to lock the record and then do the changes and commit , then FOR
UPDATE if used.
- FOR UPDATE enables row level locks as per the WHERE condition in the SELECT , hence
others cannot do the change until the lock is released by COMMIT/ ROLLBACK
- DEFAULT option is to WAIT
- NOWAIT, is one of the optional keyword to be used with FOR UPDATE, if you don’t want your
query to wait until the lock is released on the table.

WHAT HAPPENS INSIDCE WHEN WE DO DML?

- Read consistency is an automatic implementation.


- It keeps the partial copy in the UNDO SEGMENT ( snapshot of the old table data)
- When the changes are done by one user, other user see the data from the snapshot
- Once the user COMMIT or ROLLBACK, others will be able to see the real data instead of
snapshot
- When COMMITTED, new data will be available to view
- When ROLLBACK , old data will be reverted and be available for the users
- Also, the UNDO SEGMENT will be released of memory for reuse/

FOR UPDATE OF COLUMN IN SELECT ::

- FOR UPDATE will lock all the rows involved in the where condition.
- We can use FOR UPDATE for multiple tables also ( join statement)
- If used in join statement , then we can exclusively mention to lock only the relevant rows
instead of locking all rows from both the tables.
- Hence, FOR UPDATE OF column_name

== SELECT EMPLOYEE_ID, HIRE_DATE, JOB_ID, MANAGER_ID

FROM EMPLOYEES

WHERE EMPLOYEE_ID = 111

FOR UPDATE

ORDER BY EMPLOYEE_ID; ----all rows locked for where condition

== SELECT E.EMPLOYEE_ID, [Link], E.COMMISSION_PCT


FROM EMPLOYEES E JOIN DEPARTMENTS D

USING ( DEPARTMENT_ID)

WHERE E. JOB_ID = ‘ST_CLERK’ AND D . LOCATION_ID = 1500

FOR UPDATE

ORDER BY E . EMPLOYEE_ID; ---all rows of both table locked for the where condition

== SELECT E. EMPLOYEE_ID, E . SALARY , E . COMMISSION_PCT

FROM EMPLOYEES E JOIN DEPARTMENTS D

USING E. JOB_ID = ‘ST_CLERK’ AND D . LOCATION_ID = 1500

FOR UPDATE OF E . SALARY

ORDER BY E . EMPLOYEE_ID; --- all rows of employee table locked because E . SALARY is meant to be
locked exclusively not any rows from DEPARTMENT table

== SELECT E . EMPLOYEE_ID , E . SALARY , E . COMMISSION_ PCT

FROM EMPLOYEES E JOIN DEPARTMENTS D

USING ( DEPARTMENT_ID)

WHERE E . JOB_ID = ‘ST_CLERK’ AND D . LOCATION_ID = 1500

FOR UPDATE WAIT 30 ---number of seconds to wait

ORDER BY E . EMPLOYEE_ID;

=== SELECT E . EMPLOYEE_ID, [Link], E.COMMISSION_PCT

FROM EMPLOYEES E JOIN DEPARTMENTS D

WHERE E . JOB_ID = ‘ST_CLERK’ AND D . LOCATION_ID = 1500

FOR UPDATE NO WAIT

ORDER BY E . EMPLOYEE_ID;

== SELECT E . EMPLOYEE_ID, E . SALARY, E . COMMISSION_PCT

FROM EMPLOYEES E JOIN DEPARTMENTS D

WHERE E . JOB_ID = ‘ST_CLERK’ AND D . LOCATION_ID = 1500

FOR UPDATE OF E . SALARY WAIT 30 --- number of seconds to wait

ORDER BY E . EMPLOYEE_ID;
SCHEMA OBJECTSS

- TABLE :: basic unit of storage


- VIEW :: logically represent subset of data from one or more table
- SEQUENCE :: Generate numeric values
- INDEX :: Improves the performance o data retrieval queries
- SYNONYM :: Gives alternative names to objects

View :: A view is stored as a SELECT in Data Dictionary.

Logical subsets or combinations of data from one or more table.

Advantages :: - to restrict data access – only selected columns are viewed

- To make complex queries easy – querying the view makes it easier for the user
- To provide data independence- one view to retrieve data from several tables( application
users)
- To present different views of the same data- Group of users access as per capita.
 Simple view and complex view ::

Feature Simple view Complex view


Number of tables One One or more
Contain functions NO Yes
Contain group of data No yes
DML operations through Yes Not always
view

View Create options ::

- OR REPLACE – recreates the view if already exists


- FORCE – creates view even if one of the base table does not exist
- ALIAS – names of expression in the view query
- NO FORCE- creates only when all the base tables are available
- SUBQUERY – simple or complex query ( join, subquery)
- WITH CHECK OPTION – only the rows accessible can be inserted or updated
- WITH READ ONLY – on DML operations can be performed.

With OR REPLACE, view can be altered.

== CREATE [ OR REPLACE] [ FORCE|NOFORCE] VIEW view

[ ( alias[ , alias]…..) ]

As subquery

[WITH CHECK OPTION [ CONSTRAINT constraint] ]

[WITH READ ONLY [CONSTRAINT constraint] ] ;

DML THROUGH VIES::


Cannot remove a row if view contains ::

- group functions

- A group by clause
- DISTINCT keyword
- ROWNUM keyword.

Cannot add a row if view contains ::

- Group functions
- A GROUP BY clause
- DISTINCT keyword
- ROWNUM keyword
- Columns defined by expressions
- NOT NULL columns in base table that are not selected by view.

OPTIONS FOR DML OPERATION ::

- WITH CHECK OPTION:: INSERT or UPDATE operations can be done but only for the rows
satisfying the WHERE condition in SELECT.
- To protect data integrity.

WITH READ ONLY ::

- This makes sure that no DML operations can be performed through the view

== CREATE VIEW EMP_VW

AS

SELECT EMPLOYEE_ID, HIRE_DATE, DEPARTMENT_ID

FROM EMPLOYEES

WHERE SALARY > 15000;

== DESCRIBE EMP_VW ; ------to see the structure of the view

===CREATE OR REPLACE VIEW EMP_VW1 ( EMP_ID, JOB_TITLE, DEPARTMENT)

AS

SELECT EMPLOYEE_ID, JOB_ID, DEPARTMENT_ID

FROM EMPLOYEES

WHERE SALARY > 15000 ; ---with alias

= SELECT * FROM EMP_VW; ---to see data of the view


CREATE OR REPLACE VIEW DEPT_SUM_VW ( DNAME, MINSAL, MAXSAL, AVGSAL)

AS

SELECT D . DEPARTMENT_NAME, MIN (E . SALARY ) , MAX(E . SALARY) , AVG(E . SALARY )

FROM EMPLOYEES E JOIN DEPARTMENTS D

ON E . DEPARTMENT_ID = D . DEPARTMENT_ID

GROUP BY D . DEPARTMENT_NAME; ---complex view

== to recreate :

CREATE OR REPLACE VIEW EMP_VW1

AS

SELECT *

FROM EMPLOYEES

WHRE DEPARTMENT_ID = 80

WITH CHECK OPTION CONSTRAINT EMP_VW_CHK ; ---with check option

== CREATE OR REPLACE VIEW EMP_VW1

AS

SELECT *

FROM EMPLOYEES

WHERE DEPARTMENT_ID = 80

WITH READ ONLY ;

= DROP VIEW EMP_VW;

A sequence :

A sequence is a DB object that creates integer values.

A sequence :

- Can automatically generate unique numbers


- Is a shareable object
- Can be used to create a primary key value
- Replace application code
- Speeds up the efficiency of accessing sequence values when cached in memory
 INCREMENT – Intervals b/w sequence number
 START WITH – sequence start number
 MAXVALUE – max value for the sequence number to be generated
 NOMAXVALUE- default is 10 power of 27 is maximum
 MINVALUE- min value for the sequence number to be generated
 NOMINVALUE – default is 1
 CYCLE/ NOCYCLE – whether to continue after it reaches the max value
 CACHE/ NOCACHE – cache memory, default 20

= NEXTVAL AND CURRVAL ::

- NEXTVAL – returns the next available sequence value. It returns a unique value every time it
is referenced, even for different users.
- CURRVAL – obtains the current sequence value

NEXTVAL must be issued to the sequence before the CURRVAL contains the value.

== CACHING :: this helps to have faster access to those values in memory.

Gaps can occur in sequence::

- A ROLLBACK occurs
- The system crashes
- A SEQUENCE is used in another table

=MODIFY A SEQUENCE ::

- Change the increment value, maximum value, minimum value, cycle option, or cache option;
- Cannot change the START WITH
- Drop and Re-create to restart the sequence with different number
- You must be the owner or have the ALTER privilege for the sequence
- Only future sequence numbers are affected using ALTER
- To remove a sequence use the DROP statement
- Some validation is performed, a new MAXVALUE cannot be less than the current sequence
number

== CREATE SEQUENCE EMP_ID_SEQ

INCREMENT BY 10

START WITH 100

MAXVALUE 999

NOCACHE

NOCYCLE;

THEN Insert ::

INSERT INTO EMP( EMPLOYEE_ID, LAST_NAME, HIRE_DATE, JOB_ID, DEPARTMENT_ID)


VALUES ( EMP_ID_SEQ.NEXTVAL , ‘TEST_DATA’ , ‘TESTMAIL’ , TO_CHAR(SYSDATE, ‘fmDD-
MON_YYYY’), ‘ DIRECT’ , 80) ;

SELECT EMP_ID_SEQ. CURRVAL FROM DUAL ; --view the current value

== ALTER SEQUENCE EMP_ID_SEQ

INCREMENT BY 20

MAXVALUE 999999

NOCACHE

NOCYCLE;

= DROP SEQUENCE EMP_ID_SEQ;

INDEXES ::

INDEXES are created to improve the performance of some queries.

- It is also be created automatically, AUTOINDEX , when primary key and unique are defined
- Can be used to speed up the retrieval of rows by using a pointer.
- Can reduce disk input/output by using rapid path access method to locate data quickly
- Is independent of table that it indexes, i.e. can be created or dropped anytime
- When you drop a table , respective indexes are also dropped
- If you don’t have an INDEX then full scan of the table happens
- INDEXES are used and maintained by Oracle server.

How are the INDEXES created ?

- Automatically : a unique index is created automatically when you define a PRIMARY KEY or
UNIQUE KEY constraint in a table definition
- Manually : Users can create nonunique indexes on columns to speed up access to the rows.

INDEX CREATE OPTIONS ::

Can be created :: a column contains wide range of values

- A column contains large number of null values


- One or more columns are frequently used in a WHERE or JOIN condition
- If table is large and most queries are expected to return less than 2 or 4 % of the rows.

DROP INDEX :: cannot modify the INDEX.

To DROP an INDEX

- Must be the owner of the index


- Should have DROP ANY INDEX privilege
 When u drop a table, indexes and constraints are dropped automatically, but views and
sequences remains.

== CREATE INDEX EMP_JOBID_IDX

ON EMP(JOB_ID);

DROP INDEX EMP_JOBID_IDX;

SYNONYM :: simplify access to objects by creating a SYNONYM ( another name for an object). With
synonyms, you can ::

- Ease referring to a table owned by another user


- Shorten lengthy object names

PUBLIC – creates a synonym that is accessible to all users.

= CREATE- the DBA can create a public synonym that is accessible to all users

= DROP – only DBA can drop the public synonym

=== CREATE SYNONYM EMP_DTL_VW

FOR EMP_DETAILS_VIEW;

DROP SYNONYM EMP_DTL_VW;

MANAGE SCHEMA OBJECTS ::

= SET UNUSED :: - ALTER statement to add, modify, drop and rename are applied on constraint and
column.

- Dropping a column can take a while if the column has large number of values.
- Hence better to set it to be UNUSED and DROP it when only few users are on the system to
avoid extended locks.
- Also, we cannot drop more than one column in a table. Hence making it to UNUSED and then
we can drop all the UNUSED columns
- If the column is set to UNUSED then no longer it can be accessed
- UNUSED columns are not shown in SELECT or DESCRIBE statements
- UNUSED is equivalent to DROP but still hold data, hence on demand of system resource is
lower we can drop it.

==ALTER TABLE EMP

SET UNUSED ( PHONE_NUMBER);


== ALTER TABLE EMP

DROP UNUSED COLUMNS;

---+ = ON DELETE CASCADE – use it to delete child rows when a parent key is deleted.

ON DELETE SET NULL – use it set the child rows value to NULL when a parent key is deleted, else it
will not allow the delete of parent key values

TO BE DONE WHILE DEFINING THE FOREIGN KEY.

== ALTER TABLE EMP

ADD CONSTRAINT DEPARTMENT_FK

FOREGN KEY ( DEPARMENT_ID)

REFERENCES DEPARTMENTS ( DEPARTMENT_ID) ON DELETE CASCADE;

== ALTER TABLE EMP

ADD CONSTRAINT DEPARTMENT_FK

FOREIGN KEY ( DEPARTMENT_ID)

REFERENCES DEPARTMENTS ( DEPARMENT_ID) ON DELETE SET NULL;

++++ DEFERRRING CONSTRAINTS ::

- A constraint is deferred if the system does not check if it is satisfied, until COMMIT statement
is submitted.
- If a deferred constraint is violated, the DB returns an error, and it will be rolled back.
- If a constraint is immediate it will check at the end of each statement, if violated it will be
rolled back immediately
- Use SET CONSTRAINTS to check , at end of each DML statement or when each transaction is
committed.
- To create deferrable constraint, should create a nonunique index for that onstraint
- OPTIONS :
 DEFERRABLE or NOT DEFERRABLE
 INITIALLY DEFERRED OT INITIALLY IMMEDIATE

=ALTER TABLE DEPT2

ADD CONSTRAINT DEPT_PK2

PRIMARY KEY ( DEPARTMENT_ID)


DEFERRABLE INITIALLY DEFERRED;

=SET CONSTRAINTS DEPT_PK2 IMMEDIATE;

=ALTER SESSION

SET CONSTRAINTS= IMMEDIATE;

DROP TABLE PURGE ::

Dropping a table will not release the space, rather DB renames and places in recycle bin.

If you want to drop the table and release the space along with it, then PURGE is used in DROP
statement

PURGE only when you want to drop and do not want to recover.

This reduces one step of dropping and purging from the recycle bin, directly it drops and purges
in same transaction.

= DROP TABLE DEPT PURGE ;

FLASHBACK TABLE ::

Enables to recover the table from recycle bin

- Restores table data along with the indexes and constraints


- After DROP statement, the table goes to recycle bin, hence can be reverted by the
FLASHBACK statement.
- This will be helpful if the user deletes the data by mistake, so the FLASHBACK statement can
help restoring the table to the time before delete.
- Also, we can revert the table and its content to a certain time or SCN.

NOTE :: SCN is system change number ( integer value) generated for each COMMIT statement.

= SELECT ORIGINAL_NAME , OPERATION, DROPTIME FROM RECYCLEBIN;

=FLASHBACK TABLE EMP1 TO BEFORE DROP;

= SELECT * FROM RECYCLEBIN;

RECYCLEBIN::

- Data dictionary table


- User can query and view the recycle bin, but only the objects which they own
- When a user is dropped, the object belonging to that user are not placed in recycle bin
instead purged
- Manually also recycle bin can be purged.
TEMPORARY TABLE ::

- IT is a table that holds data that exists only for the duration of a transaction or session.
- Data in a temporary table is private to the session
- Used mostly in applications where a result set must be buffered
- Once the data is moved to permanent table then the temporary data is automatically
dropped
- Indexes can also be created for the temporary tables, which are also temporary
- Can also create view or trigger on a temporary table
- Temporary tables can be created with 2 options.
 Delete rows- transaction specific
 Preserve rows- session specific.

CREATE GLOBAL TEMPORARY TABLE CART(PRODUCT VARCHAR 2 (2) , DETAILS VARCHAR2 (20) )

ON COMMIT DELETE ROWS;

= CREATE GLOBAL TEMPORARY TABLE TODAY_RECRUITS

ON COMMIT PRESERVE ROWS AS

SELECT * FROM EMP

WHERE HIRE_DATE = SYSDATE;

EXTERNAL TABLES ::

- READ-ONLY table, metadata stored in DB but data is stored outside


- These tables can be queried and joined directly and without loading in the DB
- Only difference b/w external table and regular tables is the data can only be viewed , no DML
allowed, no INDEXES can be created
- 2 major access drivers used are to push data into external table and reload into oracle;
 Oracle_loader
 Oracle_ datapump
- Create the directory object that corresponds to the directory on the file system where the
external data source resides
- GRANT access to the DIRECTORY
 READ- only view
 WRITE – unload data

NOTE—this is onetime load, it cannot be updated, inserted or deleted with any data.

== ORACLE_LOADER ::

CREATE OR REPLACE DIRECTORY EMP_DIR

AS ‘ / . . . /emp_dir’ ;

== GRANT READ ON DIRECTORY emp_dir TO ora_211 ;


== CREATE TABLE OLDEMP ( FNAME CHAR (25), LNAME CHAR (25) )

ORGANIZATION EXTERNAL

TYPE ORACLE_LOADER

DEFAULT DIRECTORY EMP_DIR

ACCESS PARAMETERS

(RECORD DELIMITED BY NEWLINE

NOBADFILE

NOLOGFILE

FIELDS TERMINATED BY ‘ , ‘

FNAME POSITION (1:20) CHAR,

LNAME POSITION (22:41) CHAR ) )

LOCATION (‘emp . dat’ ) )

PARALLEL 5

REJECT LIMIT 200;

DATA DICTIONARY VIEWS :: collection of tables and views, created and maintained by the oracle
server and contains information about the DB.

Can query data dictionary views to find below information:

- Definitions of all schema objects in the database ( tables, views, indexes , synonyms,
sequences, procedures, functions, packages, triggers and so on)
- Default values for columns
- Integrity constraints information
- Names of oracle users
- Privileges and roles that each user has been granted
- Other general database information

== DATA DICTIONARY STRUCTURE :

ORACLE SERVER

- BASE TABLES
- USER-ACCESSIBLE VIEWS

The SYS user owns all base tables and user-accessible views of the data dictionary. No oracle user
should ever perform any UPDATE/ DELETE/ INSERT any rows in these schema objects.

View prefix Purpose


USER User’s view ( what is in your schema; what you own)
ALL Expanded user’s view ( what you can access)
DBA Database administrator’s view ( what is in everyone’s schemas)
V$ Performance- related data

DESCRIBE DICTIONARY ;

SELECT * FROM DICTIONARY WHERE TABLE_NAME = ‘USER_OBJECTS’

= SELECT OBJECT_NAME, OBJECT_TYPE, CREATED, STATUS

FROM USER_OBJECTS

ORDER BY OBJECT_TYPE;

=DESCRIBE USER_TABLES;

=DESCRIBE USER_TAB_COLUMNS;

= SELECT COLUMN_NAME , DATA_TYPE, DATA_LENGTH, DATA_PRECISION, DATA_SCALE, NULLABLE

FROM USER_TAB_COLUMNS

WHERE TABLE_NAME = ‘EMPLOYEES’ ;

= DESCRIBE USER_CONSTRAINTS;

=SELECT CONSTRAINT_NAME, CONSTRAINT_TYPE, SEARCH_CONDITION, R_CONSTRAINT_NAME,


DELETE_TULE, STATUS

FROM USER_CONSTRAINTS

WHERE TABLE_NAME = ‘EMPLOYEES ‘ ;

= DESCRIBE USER_CONS_COLUMNS;

SELECT CONSTRAINT_NAME, COLUMN_NAME

FROM USER_CONS_COLUMNS

WHERE TABLE_NAME = ‘EMPLOYEES’ ;

= DESCRIE USER_VIEWS ;

SELECT TEXT FROM USER_VIEWS


WHERE VIEW_NAME = ‘EMP_DETAILS_VIES’ ;

= DESCRIBE USER_SEQUENCES;

SELECT SEQUENCE_NAME, MIN_VALUE, MAX_VALUE, INCREMENT_BY, LAST_NUMBER

FROM USER_SEQUENCES;

=DESCRIBE USER_IND_COLUMNS;

SELECT INDEX_NAME, COLUMN_NAME, TABLE_NAME

FROM USER_IND_COLUMNS

WHERE INDEX_NAME = ‘EMP_DEPARTMENT_IX’ ;

ADD COMMENTS TO A TABLE ::

COMMENT ON TABLE EMP

IS ‘EMPLOYEE INFORMATION’ ;

= COMMENT ON COLUMN EMP . LAST_NAME

IS ‘LAST_NAME OF THE EMPLOYEE’ ;

= SELECT * FROM ALL_COL_COMMENTS;

SELECT * FROM USER_COL_COMMENTS;

SELECT * FROM ALL_TAB_COMMENTS;

SELECT * FROM USER_TAB_COMMENTS;

MANIPULATE DATA BY USING SUBQUERIES ::

Can use subqueries in DML :

- Retrieve data by using an inline view


- Update data in one table based on the values of another table
- Copy data from one table to another
- Delete rows from one table based on rows in another table.

RETRIEVING DATA USING SUBQUERY AS SOURCE ::

- Use subquery in FROM clause of a SELECT, which is similar to how views are used.
- Subquery in FROM clause is Inline View
- DB view can be of simple or complex subquery
- When the DB view is created the SELECT is stored in data dictionary.
= SELECT DEPATMENT_NAME, CITY

FROM DEPARTMENTS

NATURAL JOIN

(SELECT L. LOCATON_ID , [Link], L.COUNTRY_ID

FROM LOCATONS L

JOIN COUNTRIES C

ON ( L . COUNTRY_ID = C.COUNTY_ID)

JOIN REGIONS USING ( REGION_ID)

WHERE REGION_NAME = ‘EUROP’ ) ;

--

INSERTING DATA USING SUBQUERY AS TARGET ::

- Can use subquery in a place of table name in the INTO clause of INSERT
- Select list should match with values of columns
- Any rules in table should be followed while doing this kind of insert
- This way creating a new view for the purpose of insert can be avoided.
----copy data from one table to another- Inserting using subquery as a target
INSERT INTO
(SELECT L . LOCATION_ID, L . CITY , L . COUNTRY_ID
FROM LOCATIONS L
JOIN COUNTRIES C
ON ( L . COUNTRY _ ID = C . COUNTRY _ ID )
JOIN REGIONS USING ( REGION_ID)
WHERE REGION_NAME = ‘Europe’ )
VALUES ( 3300, ‘Cardiff’ , ‘ UK’ ) ;

----
USING WITH CHECK OPTION :: with check option keyword prohibits from changing rows that
are not in the subquery
- Specifying the WITH CHECK OPTION keyword to indicate that if the subquery is used in place
of a table in an INSERT , UPDATE or DELETE,no changes that produce rows that are not
included in the subquery are permitted to that table.

= CREATE OR REPLACE VIEW EUROPEAN_CITIES

AS

SELECT L . LOCATION_ID, L . CITY, L . COUNTRY_ID

FROM LOCATION L

JOIN COUNTRIES C

ON ( L . COUNTRY_ID = C. COUNTRY_ID)
JOIN REGIONS USING (REGION_ID)

WHERE REGION_NAME = ‘Europe’

WITH CHECK OPTION;

INSERT INTO EUROPEAN_CITIES

VALUES (3400, ‘New York’ , ‘US’ ) ;

== SPECIFY EXPLICIT DEFAULT IN INSERT AND UPDATE ::

- Use the DEFAULT keyword as a column value where the default column value is desire
- This allows the user to control where and when the default value should be applied to data
- Explicit defaults can be used in INSERT and UPDATE statements, if no default is given , a null
value is used.
- Do not use the values clause in copying data from another table

=default in insert

INSERT INTO DEPT ( DEPARTMENT_ID, DEPARTMENT_NAME, MANAGER_ID, LOCATION_ID)

VALUES ( 280, ‘Charity’ , DEFAULT, 1700);

= default with update

UPDATE DEPT

SET MANAGER_ID = DEFAULT

WHERE DEPARTMENT_ID = 270;

--- Copying rows from another table :

INSET INTO EMP(EMPLOYEE_ID, LAST_NAME, SALARY, COMMISSION_PCT)

SELECT EMPLOYEE_ID, LAST_NAME, SALARY , COMMISSION_PCT

FROM EMPLOYEES

WHERE JOB_ID LIKE ‘&REP&’ ;

FEATURES OF MULTI-TABLE INSERTS ::

Multitable INSERT – you insert result set of sub query into one or more tables

- These are useful in DWH scenarios, where the data load happens on regular basis for
business analysis.
- The data will be copied from different sources and loaded into DWH, this process is called as

ETL ( Extract, Transformation , and Load)

ETL and Multitable INSERT


- During Extraction, the desired data must be identified and extracted from many different
sources ( DB and Applications) .
- After extractions, the data must be physically transported to the target system or an
intermediate system for further processing.
- NOTE : Depends on the mode of transport, if SQL , then SELECT statement can concatenate
the column values and transport.
- After load, Data transformations through SQL is done. A multitable INSERT is one such
technique of Data Transformation.

---

WITH and WITHOUT MULTITABLE INSERT ?

- WITHOUT- “n” independent INSERT….SELECT statement , processing the same source data
“n” times and increasing the transformation workload “n “ times
- WITH – fast performance, single DML for multiple tables
- Each record from input stream ( non – relational DB), can now be converted into multiple
records for a more relational DB table environment.

---

TYPES OF MULTI-TABLE INSERTS ::

- Unconditional INSERT – for each row returned by the subquery , a row is inserted into each
of the target tables
- Conditional INSERT ALL – for each row returned by the subquery , a row is inserted into each
target table if the specified condition is met
- Pivoting INSERT – it’s a special case of unconditional INSERT ALL
- Conditional INSERT FIRST- for each row returned by the subquery , a row is inserted into the
very first target table in which the condition is met.

---

UNCONDITIONAL INSERT ::

ALL into clause ::

- Specify ALL followed by multiple insert_ into_clauses to perform an unconditional


multitables INSERT.
- Oracle server executes each insert_into_clause once for each row returned by the subquery.

== unconditional insert all ::

INSERT ALL

INTO DEPT ( DEPARTMENT_ID, DEPARTMENT_NAME, MANAGER_ID, LOCATION_ID) VALUES


(DEPTID, DEPARTMENT, MGR, LOC)

INTO DEPT 1 (DEPARTMENT_ID, DEPARTMENT_NAME, MANAGER_ID, LOCATION_ID) VALUES


(DEPTID, DEPARTMENT, MGR, LOC)

SELECT DEPARTMENT_ID, DEPTID, DEPARTMENT_NAME DEPARTMENT, MANAGER_ID MGR,


LOCATION_ID LOC
FROM DEPARTMENTS

WHERE DEPARTMENT_ID>60 );

 CONDITIONAL INSERT :
- Conditional_ insert_ clause : : specify the conditional _ insert_ clause to perform a
conditional multitable INSERT.
- Oracle server filters each insert_ into _ clause through the corresponding WHEN condition,
which determines whether theat insert_ into _ clause is executed.
- A single multitable INSERT can have 127 WHEN clauses.
--- ALL :: Oracle server evaluates each WHEN caluse regardless of the results of the
evaluation of any other WHEN clause.
- For each WHEN clause condition is true, oracle executes corresponding INTO clause list.
----- FIRST :: Oracle server evaluates each WHEN in the order in which it appears in statement
- If the first WHEN clause evaluates to true, oracle executes the corresponding INTO clause
and skips subsequent WHEN clause for the given row.

----- ELSE clause : - If not WHEN clause evaluates to true, and if specified the ELSE clause, then
oracle executes the INTO clause list associated with ELSE clause.

- If not specified the ELSE clause, then oracle takes no action for that row.

Conditional insert all ::

CREATE TABLE EMP_HISTORY ( EMPLOYEE_ID NUMBER ( 6 , 0 ) , HIRE_DATE DATE, SALARY NUMBER (


8, 2 ) ) ;

CREATE TABLE EMP_SALES ( EMPLOYEE_ID NUMBER (6, 0 ) , SALARY NUMBER ( 8, 2) ,


COMMISSION_PCT NUMBER ( 2, 2 ) ) ;

INSERT ALL

WHEN HIREDT < ’01- JAN -95’ THEN INTO EMP_HISTROY VALUES ( EMPID, HIREDT, SAL)

WHEN COMN IS NOT NULL THEN INTO EMP_SALES VALUES ( EMPID, SAL, COMN)

SELECT EMPLOYEE_ID EMP_ID, HIRE_DATE HIREDT, SALARY SAL, COMMISSION_PCT COMN

FROM EMPLOYEES ;

--- conditional INSERT FIRST :

CREATE TABLE SAL_LOW ( EMPLOYEE_ID NUMBER (6, 0 ) , LAST_NAME VARCHAR ( 20 ) , SALARY


NUMBER ( 8, 2) ) ;

CREATE TABLE SAL_MID ( EMPLOYEE_ID NUMBER ( 6, 0 ) , LAST_NAME VARCHAR ( 20 ) , SALARY


NUMBER ( 8, 2) ) ;

CREATE TABLE SAL_HIGH ( EMPLOYEE_ID NUMBER ( 6, 0 ) , LAST_NAME VARCHAR ( 20 ) , SALARY


NUMBER ( 8, 2) ) ;
INSERT FIRST

WHEN SALARY < 5000 THEN INTO SAL_LOW VALUES ( EMPLOYEE_ID , LAST_NAME, SALARY )

WHEN SALARY BETWEEN 5000 AND 10000 THEN INTO SAL_MTD VALUES ( EMPLOYEE_ID,
LAST_NAME, SALARY )

ELSE INTO SAL_ HIGH VALUES ( EMPLOYEE_ID, LAST_NAME, SALARY )

SELECT EMPLOYEE_ID , LAST_NAME , SALARY

FROM EMPLOYEES;

---- conditional INSERT with ELSE

CREATE TABLE MANAGERS ( LAST_NAME VARCHAR2 (20) , JOB_ID VARCHAR2 ( 20) , SALARY
NUMBER ( 8, 2) ) ;

CREATE TABLE RICHPEOPLE ( LAST_NAME VARCHAR2 ( 20) , JOB_ID VARCHAR2 (20 ) , SALARY
NUMBER ( 8 , 2 ) ) ;

CREATE TABLE POORPEOPLE ( LAST_NAME VARCHAR2 ( 20 ) , JOB_ID VARCHAR2 ( 20 ) , SALARY


NUMBER ( 8, 2 ) );

INSERT ALL

WHEN JOB_ID IN ( SELECT JOB_ID FROM JOBS WHERE JOB_TITLE LIKE ‘ &Manager&’ ) THEN INTO
MANAGERS ( LAST_NAME, JOB_ID, SALARY) VALUES ( LAST_NAME, JOB_ID, SALARY )

WHEN SALARY > 10000 THEN INTO RICHPEOPLE ( LAST_NAME, JOB_ID, SALARY ) VALUES
( LAST_NAME, JOB_ID , SALARY )

ELSE INTO POORPEOPLE VALUES ( LAST_NAME, JOB_ID, SALARY )

SELECT * FROM EMPLOYEES;

 PIVOTING INSERT :: for each value we create an insert .

CREATE TABLE SALES_SOURCE_DATA

(EMPLOYEE_ID NUMBER ( 6),

SALES_MON NUMBER ( 8 , 2) ,

SALES_TUE NUMBER ( 8, 2 ) ,

SALES_WED NUMBER ( 8, 2) ,

SALES_THU NUMBER ( 8, 2) ,

SALES_FRI NUMBER ( 8, 2) );

CREATE TABLE SALES_INFO


( EMPLOYEE_ID NUMBER ( 6) ,

WEEK NUMBER ( 2) ,

SALES NUMBER ( 8, 2 ) );

INSERT INTO SALES_SOURCES_DATA VALUES ( 1786, 1750, 2200, 1500, 1500, 3000) ;

INSERT ALL

INTO SALES_INFO VALUES ( EMPLOYEE_ID , WEEK_ ID , SALES_MON)

INTO SALES_INFO VALUES ( EMPLOYEE_ID, WEEK_ID, SALES_TUE)

INTO SALES_INFO VALUES ( EMPLOYEE_ID, WEEK_ID, SALES_WED)

INTO SALES_INFO VALUES ( EMPLOYEE_ID, WEEK_ID, SALES_THU)

INTO SALES_INFO VALUES ( EMPLOYEE_ID, WEEK_ID, SALES_FRI)

SELECT EMPLOYEE_ID, WEEK_ID, SALES_MON, SALES_TUE, SALES_WED, SALES_THU, SALES_FRI

FROM SALES_SOURCE_DATA;

==

MERGE :: Provides the ability to conditionally update, insert , or delete data into a DB table

- Performs an UPDATE if the row exists and as INSERT if it is a new row:


 Avoids separate updates
 Increases performance and ease of use
 Is useful in DWH applications
- Deterministic , cannot update the same row of the target table multiple times in the same
MERGE statement
- Alternative is in PLSQL , multiple DML statements.

CREATE TABLE EMPCY AS SELECT * FROM EPLOYEES WHERE SALARY < 10000;

MERGE INTO EMPCPY EC

USING ( SELECT * FROM EMPLOYEES ) E

ON ( EC. EMPLOYEE_ID = E. EMPLOYEE_ID )

WHEN MATCHED THEN

UPDATE SET

EC. FIRST_NAME = E. FIRST_NAME,

EC. LAST_NAME = E. LAST_NAME,

EC. EMAIL = E. EMAIL,


EC. PHONE_NUMBER= E. PHONE_NUMBER,

EC. HIRE_DATE = E. HIRE_DATE,

EC. JOB_ID = E. JOB_ID,

EC. SALARY = E. SALARY * 2,

EC. COMMISSION_PCT = E. COMMISSION_PCT,

EC. MANAGER_ID = E. MANAGER_ID,

EC. DEPARMENT_ID = E. DEPARTMENT_ID

DELETE WHERE ( E. COMMISSION_PCT IS NOT NULL )

WHEN NOT MATCHED THEN

INSERT VALUES ( E. EMPLOYEE_ID,

E. FIRST_NAME,

E. LAST_NAME,

E. EMAIL,

E. PHONE_NUMBER,

E. HIRE_DATE,

E. JOB_ID,

E. SALARY * 2,

E. COMMISSION_PCT,

E. MANAGER_ID ,

E. DEPARTMENT_ID ) ;

FLASHBACK VERSTION QUERY ::

THE VERSIONS clause does not change the plan of the query.

- Running a query on a table that uses the index access method, the same query on same
table with VERSIONS clause continues to use IAM.
- The VERSIONS clause has no effect on the transactional behaviour of a query.
- The default VERSIONS clause can be specified as VERSIONS BETWEEN {SCN|TIMESTAMP}
MINVALUE AND MAXVALUE.
- Can have DML and DDL that use a VERSIONS clause within subqueries.
- Changes made by current active transactions are not returned.
- The row access for a version query can be defined in two categories.
 ROWID- based row access- Here all versions of the specified ROWID are returned irrespective
of the row content. This means that all versions of the slot in the block indicated by the
ROWID are returned
 All other row access- here all version of the rows are returned.
SELECT SALARY FROM EMP WHERE EMPLOYEE_ID = 107;

UPDATE EMP SET SALARY = SALARY * 1.30 WHERE EMPLOYEE_ID = 107;

COMMIT

SELECT SALARY FROM EMP

VERSIONS BETWEEN SCN MINVALUE AND MAXVALUE

WHERE EMPLOYEE_ID = 107 ;

You might also like