Sie sind auf Seite 1von 93

Video B1

Oracle 2 1979
Oracle 10g 2004
Oracle 11g 2007
Oracle 12c 2014
Oracle 7 is first RDBMS

Oracle 8i and 9i were first to interact with internet without using browser

Oracle 10g and 11g means great computing


Many pcs together form a server

Oracle 12c means cloud

Data- a fact
Information- collection of meaningful data
Database- collection of inter-related data in a physical storage
Database management- communication to and from the db server
It Includes-
Reading data (select)
Write (insert for new, delete, for existing)
Manipulation (modify, update for existing)
Sorting of data

SQL

To communicate with DB
Environment needed like Sqlplus or sqldeveloper
Structured query language
Non procedural language
There is no program or code
Multiple outputs possible for a query

Example-
Select columnname from tablename;
If table is not there- table does not exist
If table is there but column is not there- invalid identifier
If table and column exist but table is empty- no rows selected
If everything is in order- we get data

Volatile language (non historic)


Case insensitive
Commands cant be abbreviated
Commands can span multiple lines
Sql is ANSI standard (American National Standards Institute)

Maximum number of columns in a table can be thousand in Oracle 8i onwards.


Till Oracle 7 this value was 255 __________________________________
__________________________________
Video B2
SQl commands

DDL
CREATE ALTER DROP TRUNCATE
FLASHBACK PURGE COMMENT
RENAME
DML
INSERT UPDATE DELETE MERGE
DRL
SELECT
DCL
GRANT REVOKE SET ROLE
TCL
COMMIT ROLLBACK SAVEPOINT SET
TRANSACTION
__________________________________________
__________________________________________
Video B3 and B4
DDL- Create Alter Drop Truncate Rename Flashback Purge Comment

Auto commit

Commit - Always
DDL
Commit - Depends on success of command
________________________________________
ALTER
Alter functions-

Add column (with/without constraints)


Drop column
Hide column
Rename column
Rename constraint
Modify datatype
Modify column size (with/without data)
Add/Drop constraint (w/wo constraint name)
Enable/disable constraints

Command options with alter-

1 ADD - constraint or column

Single column-
Alter table tablename
Add columnname datatype(size)
Or
Alter table tablename
Add (columnname datatype(size) )

Multiple column-
Alter table tablename
Add (Colummname1 Datatype(size),
Colummname2 Datatype(size) )

2 MODIFY - column size or datatype


Single column-
Alter table tablename
Modify Colummname datatype(size)
Or
Alter table tablename
Modify (Colummname datatype(size))

Multiple column-
Alter table tablename
Modify (Colummname1 datatype(size).
Colummname2 datatype (size) )

3 DROP - constraint or column

Single column
Alter table tablename
Drop Colummname datatype(size)
Or
Alter table tablename
Drop (Colummname datatype(size) )

Multiple column-
Alter table tablename
Drop (Colummname1 datatype(size),
Colummname2 datatype(size) )

DROP CONSTRAINT-
Alter table tablename
Drop constraint constraintname;

4 RENAME - constraint or column

ALTER TABLE table_name


RENAME TO new_table_name;

ALTER TABLE table_name RENAME COLUMN old_name TO new_name

Alter table tablename


Rename constraint oldname to newname

5 SET UNUSED - hide a column


Once hidden, cant be unhidden
Logically hides the column
Used since drop takes long time
Another column by same name can be added
Single column-
Alter table tablename
Set unused column (columnname)
Or
Alter table tablename
Set unused (Colummname)
Multiple column-
Alter table tablename
Set unused (Colummname1, Colummname2)

6 ENABLE - enable constraint like foreign key

ALTER TABLE tablename


ENABLE CONSTRAINT constraint_name

7 DISABLE - disabl constraint like foreign key

ALTER TABLE table_name


DISABLE CONSTRAINT constraint_name
__________________________________________
FLASHBACK

Flashback- back from recyclebin

Select * from recyclebin:


Flashback table tablename to before drop;
Flashback table tablename to before drop rename to newtablename;

Alter session set recyclebin = ON/OFF


__________________________________________
PURGE

Purge- empty recyclebin


Purge table tablename;
Purge recyclebin;
Drop table tablename purge; direct delete

From 10g onwards... Dropped table is in recyclebin.... Before that cudnt be recovered ...);
_________________________________________
COMMENT

Comment- max 4000 characters


Comment on column tablename.columnname is 'Text';
To drop comment, set as ' '
Comment on column tablename.columnname is ' ';

Comment on table-
Comment on table tablename is 'Text';

View comment from data dictionary-


User_Tab_Comments;

Comments are overriden... If we insert comment on a table/column already having a column


___________________________________________
DROP

Drop table if exists tablename


___________________________________________
TRUNCATE
Permanently delete data/records

Truncate table tablename


___________________________________________
CREATE

Create table tablename


(Colname datatype(size) constraint)
___________________________________________
___________________________________________
Video B5 and B6
DML

Explicit commit only

DML ---> BUFFER


IF COMMIT ----> WRITE TO DATABASE
ELSE ROLLBACK ----> NO CHANGE TO DB

Types of DML-

1 DRL - data read/retrieve


Select

2 DWL - data write

INSERT UPDATE DELETE MERGE


___________________________________________
INSERT

Insert into tablename


(C1, C2, C3)
Values
(V1, V2, V3)

If no of values provided = no of columns & order of values is in same order


Column names can be skipped

Insert into tablename


Values
(V1, V2, V3)

When no of values < no of columns

Insert into tablename


(C1, C2, C3)
Values
(V1, V2, V3)

Using substitution variables-

Insert into tablename


(C1, C2, C3)
Values
('&C1', '&C2', '&C3')

Slash is execution symbol for Sql and Pl/Sql


& is default substitution variable

Multiple rows from another table-

If structure and column names and datatypes match exactly-

Insert into tablename2


Select * from tablename1

If only datatypes match-


No of columns and name can differ....

Insert into tablename2 (col1, col2, col3)


Select (C1, C2, C3) from tablename1
___________________________________________
SELECT

Order of display is in physical storage order...


___________________________________________
UPDATE

Single column and all records-


Update tablename
Set C1 = V1

Multiple column and all records-


Update tablename
Set C1 = V1,
C2 = V2

Single column and particular records-


Update tablename
Set C1 = V2
Where C1 = V1

Multiple column and particular records-


Update tablename
Set C1 = V2,
C2 = V3
Where C1 = V1
___________________________________________
DELETE

All records-
Delete from tablename
Or
Delete tablename
Particular records-
Delete from tablename
Where C1 = V1
Or
Delete tablename
Where C1 = V1
__________________________________________
MERGE

If we write a Pl/Sql block to check w field


And perform operations like
Delete if it is obsolete
Insert if it is not present
and update if it is present
Then its a time consuming process.

Merge can help here.

In Oracle 9i -
Only insert + update was possible
Single insert - ×
Single update - ×

In Oracle 10g -
Insert + Update + Delete ✓
Insert + Update ✓
Update + Delete ✓
Insert ✓
Update ✓
Insert + Delete ×
Delete ×

Operations to take place in Target table.


Target Table must be one
Source table can be more than 1
Table
Inline view
Query
Global temporary table

If we use inline view/ query as source table, the table, i.e the query must be given an alias name.

We can't use JOIN in source table in 9i. Must be a single table.

MERGE INTO employees e


USING hr_records h
ON (e.id = h.emp_id)
WHEN MATCHED THEN
UPDATE SET e.address = h.address
WHEN NOT MATCHED THEN
INSERT (id, address) VALUES (h.emp_id, h.address);
MERGE INTO employees e
USING
(SELECT * FROM hr_records
WHERE start_date > ADD_MONTHS(SYSDATE, -1)) h
ON (e.id = h.emp_id)
WHEN MATCHED THEN
UPDATE SET e.address = h.address
WHEN NOT MATCHED THEN
INSERT (id, address) VALUES (h.emp_id, h.address);

Merge into table1


Using table 2

Or
Merge into table1
Using (Select * from table2)

Second method is method since we can choose which columns to load into memory and save memory.

Also, we can bring data from multiple tables (10g onwards)


___________________________________________
TRUNCATE vs DELETE vs DROP

TRUNCATE is a DDL command

TRUNCATE is executed using a table lock and whole table is locked for remove all records.

We cannot use WHERE clause with TRUNCATE.

TRUNCATE removes all rows from a table.

Minimal logging in transaction log, so it is faster performance wise.

TRUNCATE TABLE removes the data by deallocating the data pages used to store the table data and records only the
page deallocations in the transaction log.

Identify column is reset to its seed value if table contains any identity column.

To use Truncate on a table you need at least ALTER permission on the table.

Truncate uses less transaction space than the Delete statement.

Truncate cannot be used with indexed views.

TRUNCATE is faster than DELETE

DELETE

DELETE is a DML command.

DELETE is executed using a row lock, each row in the table is locked for deletion.
We can use where clause with DELETE to filter & delete specific records.

The DELETE command is used to remove rows from a table based on WHERE condition.

It maintain the log, so it slower than TRUNCATE.

The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row.

Identity of column keep DELETE retains the identity.

To use Delete you need DELETE permission on the table.

Delete uses the more transaction space than Truncate statement.

Delete can be used with indexed views.

DROP

The DROP command removes a table from the database.

All the tables' rows, indexes and privileges will also be removed.

No DML triggers will be fired.

The operation cannot be rolled back.

DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command.

DELETE operations can be rolled back (undone), while DROP and TRUNCATE operations cannot be rolled back
___________________________________________
___________________________________________
Video B7 and B8
DCL

Auto commit

Commit - Always
DDL
Commit - Depends on success of command

Faster

Privilege

System privilege-
Available to DBA and app developer

Object privilege-
On a particular object (table)

Object privilege can be given by object owner to other users...


Ex owner of a schema
Grant
Revoke
Set role

PRIVILEGE LIST:
SELECT INSERT UPDATE DELETE ALTER
CONNECT RESOURCES ALL

SHOW USER- displays current username


___________________________________________
GRANT

Grant connect, resources to user identified by password

Single privilege to single user-


Grant select on tablename to username;

All privilege given to user-


Grant all on tablename to username;

Multiple privilege & multiple users-


Grant select, insert on tablename
to username1, username2;

We can't give privilege on multiple objects in one statement-


Grant select on tablename1, tablename2
to username; ×

If username A gives privilege to B, B cant give privilege to C...


Unless With Grant option is used while A gives privilege to user B

Grant Select on tablename to username with grant;

C ---> Select * from B.tablename ×


B is not owner, A is owner
So C has to execute
Select * from A.tablename ✓
___________________________________________
REVOKE

A ---> Revoke select on tablename from C ×


A has not given permission to C so A cant revoke, B can.
A can remove from B user and automatically privilege will be removed from C user
A ---> Revoke select on tablename from B ✓

Revoke role-
Revoke Connect, Resource from username

Single privilege to single user-


Revoke select on tablename to username;

All privilege given to user-


Revoke all on tablename to username;

Multiple privilege & multiple users-


Revoke select, insert on tablename
to username1, username2

We can't give privilege on multiple objects in one statement-


Revoke select on tablename1, tablename2
to username; ×

Transitive-
Revoke select on tablename from C ×
A cant execute this as privilege to C was given by B, not A
___________________________________________
SET ROLE

Role is a group of privileges...


Used to solve problem of giving multiple privilege on different objects in one statement.

Different level users have different privilege set.


Freshers may have less privilege on less objects.
Managers may have more privilege on more objects.

A role identifies a group of people who will have similar privileges

Now, if can add/remove a user from the role and his privileges will be changed.
No need to execute multiple statement for all tables when a user is added or deleted from the group.

Create role rolename;

With password-
Create role rolename identified by password;

Without password-
Create role rolename not identified

Grant P1, P2, ....Pn to R1;

Grant R1 to U1, U2,...Un;

To add/change password to role-


Alter Role rolename identified by password

To remove password-
Alter role rolename not identified

Give default role to a user (same as grant role)


Alter user username default role rolename

Now, we can give privilege on a table to role-


Grant select on tablename to rolename;

Set role command-

Set role rolename; setting role to current user

To enable all roles granted to you for the current session-


Set role all;

To enable all roles granted to you except one-


Set roll all except rolename;

To disable all roles granted to you for the current session-


Set role none;

Set role rolename identified by password

If the role has a password, we must specify it while setting it to a user


___________________________________________
___________________________________________
Video B9 and B10
TCL

Transaction control language

Transaction is a set of DML operations with a commit or rollback is a transaction.

Transaction should begin with write operations


Insert, Update, Delete or Merge

Transaction should end with commit or rollback... Either implicit or explicit...

Commit
Rollback
Savepoint
Set transaction
___________________________________________
COMMIT

To make DML changes permanent.


Until we commit, data is stored in buffer.
Current user sees the modified data but all other users see existing data.

Commit Operations-

Create implicit

Insert
Update
Commit explicit

Insert
Alter implicit
Since alter is a DDL statement and there is an implicit commit before it, the DML comment insert is also committed,
implicitly.

Insert
Commit explicit

Insert
Delete
Drop implicit

Since Drop is a DDL statement and there is an implicit commit before it, the DML comments insert and delete are
also committed, implicitly

Insert
Delete
Select
Commit explicit

Select
Insert
Delete
Commit explicit

Starting point of this transaction is Insert not select.... Only write operations count as start of transaction. Select can
be a part of transaction, but not the starting point.
___________________________________________
ROLLBACK

To revert changes.
Buffer content gets removed.
It is like control + z

SQL commands cant be written in short form


Only command that can be written in shirt form is roll back..
Short form is roll. DONT USE ; WITH ROLL... DOESN'T WORK

Insert
Insert
Rollback explicit

Inset
Update
Rollback explicit

Insert
Update
Alt + F4 implicit

Since, alt + F4 closes the terminal, it is abnormal disconnect, so it is implicit rollback


___________________________________________
SAVEPOINT
It is a temporary commit
A temporary saving point within a transaction
Savepoint stored in buffer only, not DB
Multiple savepoints can be present in a transaction
Unique names should be used for savepoints in a transaction
If we use duplicate name, previous savepoint is overriden
We need to remember savepoint names sice they are not saved in DB

Insert
Insert
Savepoint S1
Delete
Savepoint S2
Select
Savepoint S3
Insert -> wrong insert so rollback
Rollback to S3

If we use only rollback, then it will find previous commit and all changes are lost.
So if we rollback to S3, changes after S2 are removed and all savepoints after S3 are also removed

In above example, S2 and S3 savepoints are same, since only select statement is there between them and it is not a
write (DML) statement
___________________________________________
SET TRANSACTION

It must be first statement of the transaction

Set transaction read, write;

We can perform R/W ops


Insert, update, delete, merge, select

Set transaction read only;

only read

Transaction finished with commit or rollback

Set transaction read write ✓ (successful)


Set transaction read only × (fails)
Commit:

Isolation level- to define which data we see, modified or the one present before transaction began.

Types-
Read committed
Serializable

By default, isolation level of transaction is read committed, i.e. if we commit within a transaction session, modified
data is shown to a user
If we want to see existing data before starting transaction level, use serializable

To change-
Set transaction isolation level serializable
____________________________________
____________________________________
Video B11
SQL DATA TYPES

Till Oracle 8i-


Char(s)
Varchar(s)
Varchar2(s)
Nchar(s)
Nvarchar2(s)
Number
Date
Raw(s)
Long
Long raw
Rowid
Urowid
BLOB
CLOB
NCLOB
BFILE

9i onwards-

Timestamp
Timestamp with timezone t
Timestamp with local timezone
Interval year to month
Interval day to second
___________________________________
CHAR(size)

Fixed length character dataset


Max size is 2000 byte/char
Size is optional
Size can be specified in byte/char
Default size is 1 byte
Characters allowed A-Z a-z 0-9 special char

For char(5)
If entry is abc rest 2 empty spaces are added
on right hand side since CHARACTER DATA IS LEFT ALIGNED

Char(1) means 1 byte


Char(1 char) means 1 char

Difference between byte and char in size


Byte can take only single byte character data
Syntax char(n) or char(n byte)

Size char can take multibyte character data


Syntax char(n char)
Max size allowed in char is 4 byte
____________________________________
Varchar2(size)

Variable length character data type


Maximum size is 4000 byte/characters
Size is mandatory
Size can be specified in byte/char
Characters allowed A-Z a-z 0-9 special char

Varchar and varchar2 are same.


Varchar2 is original.
Varchar functionality may be changed in future
LONG
Similar to varchar2 data type but max size is 2 GB
Long column not allowed in where clause
Only DEFAULT AND NOT NULL CONSTRAINT CAN BE DEFINED ON IT
Stores single byte variable length character data
NOTE: Only one long type column is allowed per a table.
It has been deprecated after LOB introduction
Still supported to support backward compatibility
Display width is 80
Change width
Set long = 120 (default is 80)
Max width we can set is 2000000000
____________________________________Number (P,S)

Precision from 1 to 38
Scale from -84 to + 126

Allows numeric data


Precision is the total number of digits in the number (integer part plus decimal part)
Scale is the total number of digits in the decimal part
This data type is right aligned
Default numwidth is 10
Size is optional and default precision is 38
Size can be specified in byte or char
Total 13 Characters allowed 0-9 . - +

Syntax

Number
Number(P)
Number(P , S)

If we try to input more characters than specified in scale then there will be no error but the the data stored will be
rounded off
If we try to input more characters than specified in precision then there we get error message

If we dont specify precision, default value of 38 is taken.


Even though the maximum precision allowed is 38, 40 digits are stored without error and 41st digit onwards, the
last digits are automatically rounded off to zero

Scale can be greater than precision, most commonly when e notation is used. When scale is greater than precision,
the precision specifies the maximum number of significant digits to the right of the decimal point. For example, a
column defined as NUMBER(4,5) requires a zero for the first digit after the decimal point and rounds all values past
the fifth digit after the decimal point.
The case where Scale is larger than Precision could be summarized this way:
Number of digits on the right of decimal point = Scale
Minimum number of zeroes right of decimal = Scale – Precision
SELECT CAST(.0000123 AS NUMBER(6,9)) FROM dual; -- prints: 0.0000123; .000|012300
SELECT CAST(.000012345 AS NUMBER(6,9)) FROM dual; -- prints: 0.0000123; .000|012345
SELECT CAST(.123456 AS NUMBER(3,4)) FROM dual; -- ERROR! must have a 1 zero (4-3=1)
SELECT CAST(.013579 AS NUMBER(3,4)) FROM dual; -- prints: 0.0136; max 4 digits, .013579 rounded to .0136
_________________________________
Date data type
Display Format DD-MON-YY
Default format DD-MON-YYYY / DD-MON-YY
Size is 7 byte
Internal storage format
AD DD-MON-YYYY HH-MI-SS AM
Date range allowed-
01-Jan-4712 BC to 31-Dec-9999 AD
Month can be in upper case, lower case or mixed case
Year 0000 does not exist

Select sysdate from dual;

Select to_char
(sysdate, 'BC DD-MON-YYYY HH:MI:SS AM) from dual;

Insert custom time

Insert into table


(id date)
values
(10, to_date(’AD 10-JAN-2016 08:40:12 AM’ , 'AD DD-MON-YYYY HH:MI:SS AM) );

Select sysdate, length(sysdate) , vsize(sysdate) from dual;

Length gives no of characters


Vsize gives storage size
____________________________
Nchar datatype

The NCHAR data type stores fixed-length character data.


The data can be a string of single-byte or multibyte letters, digits, and other symbols that are supported by the code
set of the database llocal
Max size is 1000 byte
Size is optional
Default size is 1 byte
Characters allowed a-z A-Z 0-9 special characters

NVARCHAR2 DATATYPE

The NVARCHAR2 datatype was introduced by Oracle for databases that want to use Unicode for some columns
while keeping another character set for the rest of the database (which uses VARCHAR2). The NVARCHAR2 is a
Unicode-only datatype.
One reason you may want to use NVARCHAR2 might be that your DB uses a non-Unicode character set and you
still want to be able to store Unicode data for some columns without changing the primary character set

Variable length multibyte character set


Max size is 2000 byte
Size is mandatory
Characters allowed a-z A-Z 0-9 special characters

Binary Data types

For binary and hexadecimal data

 RAW(size) It is used to store binary data like images, thumb impressions, logos and so on.
Max size is 2000 bytes < 2 KB
Size is mandatory
It allows single
 LONG RAW It is similar to RAW data type but max size is 2 GB.

NOTE: Only one longraw type column is allowed per a table.


It has been deprecated after LOB introduction
Still supported for backward compatibility
LONG RAW column not allowed in where clause
Only default and NOT NULL CONSTRAINT can be defined on it
No index, primary key, foreign key, etc
Long and long row not allowed in a table together

It will accept binary and hexadecimal only

Insert into tablename (col1, long raw column)


Values
(1 , 111) × expected binary got number
(1 , '111’) ✓ character accepted
(2, 'AA') ✓ hexadecimal accepted
(5, 'aa') ✓ hexadecimal accepted
(3, 'abcd') ✓ hexadecimal accepted
(4, 'G') × Invalid hex number

All no from 0 to 9 and A to F are accepted


For G-Z, invalid hex number error thrown
ONLY IN SINGLE QUOTES
Else expected binary got number error thrown
Not allowed In where clause- illegal use of long datatype error is thrown

Create table tablename


(C1 int, C2 long default 'ABC'); ✓

Create table tablename


(C1 int, C2 long default 'ABC' not null); ✓

Create table tablename


(C1 int, C2 long not null default 'ABC'); ×

Default has higher priority, will come first


__________________________________
LOB--Large Objects It is used to store higher volumes of data and max size is 4 GB.
No restrictions of no of columns per table
LOB TYPES -- 3
CLOB--CHAR LOB--used to store character data (single byte character data)
BLOB-- BINARY LOB-- Used to store binary data
NCLOB—Multibyte CLOB Fixed length multi char large objects
Used to store both binary and char data
ROWID

To support rows of data


18 character length provided by database server
UNIVERSAL ROW ID OR U ROWID
Types-
Restricted row id –
follows hexadecimal no system
16 character length

Extended row id –
Follows base 64 no system
18 character length
___________________________________
BFILE
NO MAX SIZE LIMIT
DATA IS STORED IN OPERATIONS SYSTEM NOT IN DB
Oracle directly having path of OS is needed to use BFILE

B28 VIDEO
SQL DATATYPES PART 5

RAW datatype –

Can store binary (0 and 1) and hexadecimal (0-9 , A-F or a-f) data
Must be ENCLOSED IN SINGLE QUOTES
MAXIMUM SIZE IS 2000 BYTES
Each character in binary or decimal data 100 only how byte 2000 bytes is equal to a maximum of 4000 characters.
Data is left aligned
It is allowed in where close unlike long RAW and LONG

Create table tablename


( Eno number,
Cl raw(20) );

Insert into tablename


Values
( 2 , '0101’); ✓

Insert into tablename


Values
( 2 , '0AFB01’); ✓

Insert into tablename


Values
( 2 , 0101); ×
Error – expected binary got number
______________________________
ROWID
IT ALLOWS 18 BIT LONG ROW ID
Uses base64 number system so there will be 64 different digits in the row ID value
VALUES THAT CORRESPOND TO ORACLE TABLE ROW IDS.
IT HAS BEEN DEPRECATED AFTER THE THE ADVENT OF UROWID.
HOWEVER BACKWARD SUPPORT IS STILL AVAILABLE
Only accepts extended row id

UROWID
It is universal row id
Uses base64 number system so there will be 64 different digits in the row ID value
It accepts both restricted row ID and extended row ID
If we enter restricted row ID it is converted to extended row ID INTERNALLY
Extended row id is divided into 4 parts-
First 6 characters
Next 3 Characters
Next 6 Characters
Last 3 Characters ( ACTUAL ROW NO)

We do not need to create row IDS these are created internally

CREATE TABLE TABLENAME


(ENo number,
C1 rowid(2) ); ×

CANT GIVE SIZE IT IS FIXED


Error – missing right parenthesis

CREATE TABLE TABLENAME


(ENo number,
C1 rowid ); ,✓

Insert into tablename


Values
(1 , '1234’); ×
Error Invalid rowid

Insert into tablename


Values
(1 , 'AAAAAAAAAAAAAAAAAA); ✓

Extended row id is created


______________________________
BLOB BINARY LARGE OBJECT
It is extension of RAW and long RAW
MAXIMUM SIZE 4GB
STORES UNSTRUCTURED BINARY AND HEXADECIMAL DATA
No limit of one column per table

CLOB CHARACTER LARGE OBJECT


MAXIMUM SIZE 4GB
STORES UNSTRUCTURED CHARACTER DATA

NCLOB MULTIBYTE CHARACTER LARGE OBJECT


Maximum size 4GB
Stores unstructured multibyte character data

Bfile BINARY FILE LARGE OBJECT


NO MAXIMUM SIZE
Stores unstructured data like images graphs graphics animation movies sounds, etc
Data will be stored outside database

Create table tablename


(C1 number,
C2 BLOB,
C3 CLOB,
C4 NCLOB) ; ✓

Insert into tablename


Values
(1, '0101’, 'abcd124’, 1236a’); ✓

Insert into tablename


Values
(Null , empty_blob() , null , ' ') ; ✓

Empty_BLOB function was used for null values to be entered in BLOB type data type. Later on, it was deprecated
(with backward support) and null values can directly entered using null keyword.
Directly null value or empty spaces can also be inserted into BLOB data type

Create table tablename


(C1 number,
C2 BLOB DEFAULT 'AA',
C3 CLOB DEFAULT ‘B12’,
C4 NCLOB DEFAULT '1010A’) ; ✓
Create table tablename
(C1 number,
C2 BLOB NOT NULL,
C3 CLOB,
C4 NCLOB) ; ✓

Default and not null constraints can be defined on LOB data types but not check, unique, foreign or primary key
constraint

Create table tablename


(C1 number,
C2 BLOB UNIQUE,
C3 CLOB,
C4 NCLOB) ; ×

Error thrown is column of data type LOB cannot be unique or primary key
_____________________________
_____________________________
B29 VIDEO
SQL DATA TYPES PART 6
BFILE

DATA IS STORED OUTSIDE THE DATABASE


DIRECTORY PRIVILEGE IS NEEDED TO USE

Create table tablename


(C1 number,
C2 Bfile) ; ✓

Use bfilename function to insert values in bfile data type column


It accepts 2 parameters
1 directly location
2 filename

into tablename
Values
(1 , BFILENAME('DIR1' , ‘ABC.TXT'));

Insert into tablename


Values
(1 , BFILENAME(null , ‘null)); ✓

Insert into tablename


Values
(1 , BFILENAME(' ' , ‘ ')); ✓

Insert into tablename


Values
(1 , null); ✓
Insert into tablename
Values
(1 , ' '); ✓

Direct null values, spaces, null values and spaces inside Bfile are allowed

The insert statement does not create a file at the specified directory path.
We have to move or create a file with tha name given in the BFile column at the specified path.
We don’t need to specify the file path inside a directory because that is already stored in data dictionary.
Bfile lacks Data integrity because anybody can delete the file from the physical directory and when the database
tries to retrieve the file it will throw error.

Select C2 from tablename;

Column or attribute type cannot be displayed by sqlplus

Insert into tablename


Values
(Null , empty_blob());

Error – inconsistent data type expected FILE got BLOB

Number character and blob data types are not accepted in BFILE

Insert into tablename


Values
(Null , 'A.A’));
__________________________________
B15 Video
SQL IDENTIFIER

It is user defined name


It can be tablename, columnname, cursorname, view, index, column alias ,etc

Direct Rules-
Identifier is not case sensitive
Max length can be 30 characters
Alpha numeric characters allowed
Some special characters allowed like _ $ #
First character must be alphabet
Keywords cant be used as identifier

Indirect rules-
With double quotes, max length is still 30 not 28
With double quotes, any specific character is allowed for identifier name
Eg “$abc”
With double quotes, identifiers are case sensitive
Eg “abc” != “ABC”
With double quotes, keywords are allowed as identifier
Eg “Table”
IF WE USE DOUBLE QUOTES IN IDENTIFIER,
IDENTIFIER NAME IS TAKEN AS EXACTLY AS ENTERED.
If not, it is taken in capslock
We cant use single quotes

Select 'abhi' as name from dual;

NAME
Abhi

Select 'abhi' as “NaMe” from dual;

NaMe
Abhi

If we use double quotes, we have to use them every time we use double quotes
B16 Video
SQL CLAUSES PART 1

MANDATORY
SELECT FROM

OPTIONAL
WHERE- Restricting rows
GROUP BY- Forming groups
HAVING- Restricting groups
ORDER BY- Sorting

ALWAYS EXECUTED IN BUFFER


___________________________________
Where-
Has highest priority
Must be first optional clause
Evaluated before all other clauses
Eliminates non matching records
GROUP FUNCTION NOT ALLOWED IN WHERE CLAUSE
LONG COLUMN NOT ALLOWED IN WHERE CLAUSE

USED WITH-
SELECT UPDATE DELETE
MERGE (In update and delete part not insert)
INSERT (WHEN COPYING FROM OTHER TABLE)

Select * from tablename where C1 = V1;


Update tablename set C1 = V2 where C2= V3;
Delete from tablename where C1=V1;

Insert into tablename2


Select C1 , C2 from tablename1 where C3 = V1;

Merge into emp1 a


Using emp2 b
On (a.ENo = b.ENo)
When matched then
Update set Ename = b.Ename, Sal = b.Sal
Delete where sal = 2000
When not matched then
Insert (ENo , Ename, DOB, Sal)
Values
(B.ENo , B.Ename, B.DOB, B.Sal);

Merge into emp1 a


Using
(Select * from emp2 b where dno = 20) b
On (a.Eno = b.Eno)
When matched then
Update set Ename = b.Ename, Sal = b.Sal
Delete where sal = 2000
When not matched then
Insert (ENo , Ename, DOB, Sal)
Values
(B.ENo , B.Ename, B.DOB, B.Sal);

GROUP BY

Evaluated after where clause


Forms groups
Records of same groups will be grouped together

Select C1 , C2 from T1
Group by C1;

In 9i and 11g–
Data displayed in ascending order
In 10g –
Data displayed in descending order

Select C1, C2 from T1


Where C1 = V1
Group by C1;

Except group functions, all columns in select clause must be present in group by clause
Else error- not a group by expression

However, group by clause can have extra columns. All columns in group by clause need not be present in select
clause

Ex
Select ename, eno
From T1
Group by eno, ename, dept; ✓

Select ename, eno, dept


From T1
Group by ename, dept; ×
____________________________________
HAVING CLAUSE

FOR RESTRICTING GROUPS


ALWAYS USED WITH GROUP BY CLAUSE
CAN PRECEDE OR SUCCEED GROUP BY CLAUSE
EVALUATED AFTER FORMING OF GROUPS
ELIMINATES NON MATCHING GROUPS
WE CANT USE GROUP FUNCTION IN WHERE CLAUSE SO WE USE HAVING CLAUSE TO ELIMINATE GROUPS
___________________________________
___________________________________
B17 SQL CLAUSES PART 2

Select C1, Sum (C2) from T1


Group by C1 where sum(C2) > 5000; ×

Select C1, Sum (C2) from T1


Where sum (salary) > 5000
Group by C1; ×

Select C1, sum (C2) from T1


Having sum (C2) > 5000
Group by C1; ✓

Select C1, sum (C2) from T1


Group by C1
Having sum (C2) > 5000; ✓

Select C1, sum (C2) from T1


Where C2> 5000
Group by C1
Having sum (C2) > 10000; ✓

Order of operations –
Data is copied to buffer
Group by is applied
Groups formed in buffer
Aggregate function applied
Having clause applied
Non matching groups are eliminated
Matching groups remaining in buffer are displayed

Order-
Group by
Aggregate function
Having
____________________________________
ORDER BY CLAUSE

USED FOR SORTING DATA IN ASC Or DESC ORDER


DEFAULT IS ASC ORDER
LEAST PRIORITY
LAST CLAUSE IN SELECT STATEMENT
CAN HAVE SINGLE OR MULTIPLE COLUMNS
POSITION OF COLUMN CAN BE USED IN ORDER BY CLAUSE

Single column –

Select * from T1
Order by C1 asc;

Multiple column –

Select * from T1
Order by C1 desc, C2 asc, C3 desc;

Cant use bracket –

Select * from T1
Order by (C1 , C2) desc; ×

Using column no –

Select C2, C3 from T1


Order by 1;

This 1 is the position in current select statement not the whole table so 1 refers to C2 not C1

Treatment of null values –

In asc order, nulls are at the end (unknown so may be bigger)


In desc order, nulls are at beginning
____________________________________
Processing order-

Where
Group by
Aggregate function
Having
Order by

Syntax –

Where
Having
Group by
Order by ✓

Or

Where
Group by
Having
Order by ✓
___________________________________
___________________________________
B18 VIDEO
SQL CLAUSES PART 3
Example –

Select Dno, sum (sal) from emp


Where sal >= 1000
Group by Dno
Having sum(sal) >= 5000
Order by Dno desc;

Execution –

1 All Data taken to buffer


2 Unwanted columns are eliminated i.e all columns except sal and Dno
3 Where clause is applied and non matching records are eliminated
4 Processing of Group by
5 Aggregate fn i.e. sum of sal applied
6 Having clause is applied and non matching groups are eliminated
7 Order by clause applied from left order by clause condition towards right
____________________________________
____________________________________
B19 Video
SQL FUNCTIONS

A FUNCTION WHEN INVOKED RETURNS A VALUE TO US

TYPES –
Single row functions –
act on one record and produce one result per row
Can be nested upto any level

Multiple row functions –


acts on a group of records and produces one result for each group
Can be nested upto 2 levels

Type of functions –

Character fn
Number fn
Date fn
Conversion fn
General fn
Timestamp fn

Group fn & number fn are multiple row fns.. rest all are single row fns
____________________________________
CHARACTER FNS

CASE MANIPULATION FNS


1 UPPER (Col / Char string)
Converts mixed or lower case data to upper case

Select upper ('Oracle Server') as upper from dual;


O/P ORACLE SERVER

2 LOWER (Col / Char string)


Converts mixed or uppercase data to lowercase

Select lower ('Oracle Server') as lower from dual;


O/P oracle server

3 INITCAP (Col / Char string)


Only first character of each word will be uppercase rest all will be lower case
Words identified by space, special characters and period.
All words after a period, space and special characters are initialized

Select initcap ('this is’oracle server’. correct') as initcap from dual;


O/P This Is Oracle Server. Correct

Select initcap ('a b c:d$ent) as initcap from dual;


O/P A B C D Ent
____________________________________
STRING MANIPULATION FNS

1 LENGTH (COL / STRING)


Character function that gives number output and not string output
O/P is right aligned so it is number
Calculates the length of a string
Single Quotes are not counted in length
DOUBLE QUOTES ARE COUNTED IN LENGTH

Select length ('Oracle server') as length_op from dual;

O/P 13
____________________________________
B20 VIDEO
SQL FUNCTIONS PART 2

2 CONCAT (COL1 / STRING1 , COL2/ STRING2)


Accepts only 2 character Data input and joins them
If we pass 3 arguments – error is invalid no of arguments

Select concat ('I am' , 'a man') as concat_op from dual;

O/P I am a man

HOW TO JOIN 3 STRINGS?

1 USE CONCATINATION OPERATOR ||


Each operator takes 2 arguments
Select 'Oracle' || 'Server' || 'Abcd' as concat_op from dual;

O/P OracleServerAbcd

2 USE CONCAT FN WITH NESTED FN


Inner concat function gives a string which is concatenated with outside string

Select concat('Come, (concat('on' , 'now') ))as concat_op on dual;

O/P Comeonnow

Operator provides faster performance than function as more decision making is needed

3 LPAD
To all extra characters on left size
Accepts 3 parameters.
Given value
Total Characters
Character to be added (OPTIONAL)
IF NOT GIVEN SPACE IS TAKEN BY DEFAULT

Select lpad ('Oracle' , 20 , '+') as lpad_op from dual;

O/P ++++++++++++++Oracle
Oracle is 6 Characters long.. 20 – 6 = 14 so 14 + added to left size

Select lpad ('Oracle' , 20 ) as lpad_op from dual;


O/P Oracle

14 spaces followed by oracle

Select lpad ('Oracle' , 6 , '+') as lpad_op from dual;


O/P Oracle
Since Oracle is 6 Characters long, no + added

4 RPAD
To all extra characters on RIGHT size
Accepts 3 parameters.
Given value
Total Characters
Character to be added (OPTIONAL)
IF NOT GIVEN SPACE IS TAKEN BY DEFAULT

Select Rpad ('Oracle' , 20 , '+') as rpad_op from dual;

O/P Oracle ++++++++++++++

Q…. Print $$$$ORACLE$$$$

Select rpad((lpad (‘Oracle' , 10 , '$’)) , 14 , '$’) as pad_op from dual;

O/P $$$$Oracle$$$$
5 LTRIM
REMOVE UNWANTED CHARACTERS FROM LEFTMOST SIDE
If leftmost Characters are multiple and adjacent, all are removed
Character search is Character by Character and not by whole string
Upper case and lower case are different entities
ACCEPTS TWO VALUES
GIVEN VALUE
AND VALUE TO BE TRIMMED

Select ltrim('Oracle' , 'O') as ltrim_op from dual;

O/P racle

Select ltrim('Oracle' , 'X') as ltrim_op from dual;

O/P Oracle

Select ltrim('Oracle' , 'Ora') as ltrim_op from dual;

O/P cle

Select ltrim('Oracle' ,’r') as ltrim_op from dual;

O/P Oracle

Select ltrim('OOOOOOracle' , 'O') as ltrim_op from dual;

O/P racle

It removes all O, like a loop it keeps checking

Select ltrim('Oooooracle' , 'O') as ltrim_op from dual;

O/P ooooracle

Select ltrim('RAOcle' , 'ORA') as ltrim_op from dual;

O/P racle
Checks left most Character in given string… Is it one of needed Characters (ORA)
IF YES, REMOVE
CHECK SECOND LEFT
IF NOT STOP

6 RTRIM
REMOVE UNWANTED CHARACTERS FROM RIGHTMOST SIDE
If rightmost Characters are multiple and adjacent, all are removed
Upper case and lower case are different Character search is Character by Character and not by whole string
ACCEPTS TWO VALUES
GIVEN VALUE
AND VALUE TO BE TRIMMED

Select rtrim('Oracle' ,'e') as rtrim_op from dual;


O/P Oracl

Seltrim rtrim('Oracleserver' ,'ver') as rtrim_op from dual;

O/P Oracles
R is removed then e then v then r then e stops at s

7 TRIM
TO REMOVE CHARACTERS ON EITHER LEFT OR RIGHT OR BOTH SIDES
Both keyword is optional
Only one Character can be checked and removed
O✓
OA ×
OO ✓

Select trim(BOTH 'O' from 'OOORACLESERVEROOO' ) as trim_op from dual:


Or
Select trim( 'O' from 'OOORACLESERVEROOO' ) as trim_op from dual:

O/P RACLESERVER

Or COMBINATION OF LEFT AND RIGHT TRIM CAN BE USED

Select ltrim(rtrim ('OOORACLESERVEROOO' , 'O' ) , 'O' ) as trim_op from dual;

O/P RACLESERVER

To trim SPACE –

Select trim (' ' from ' ORACLE SERVER ' )FROM DUAL;
OR
Select trim ( ' ORACLE SERVER ') from dual;

O/P ORACLE SERVER

Trim only left side using TRIM

Select trim (leading ' ' from ' ORACLE SERVER ') as trim_op from dual;

O/P ORACLE SERVER


Right side space is not removed

Trim only right side using TRIM

Select trim (trailing ' ' from ' ORACLE SERVER ') as trim_op from dual;

O/P ORACLE SERVER


Left side space is not removed

TO REMOVE MULTIPLE DISTINCT CHARACTERS, USE LTRIM AND RTRIM OR


NESTED TRIM

SELECT TRIM(LEADING 'A' FROM (TRIM (LEADING ‘R’ FROM ( TRIM (LEADING 'O' FROM 'ORACLESERVER ))))) FROM
DUAL;

O/P CLESERVER

8 TRANSLATE
TRANSLATE AND REPLACE GIVE SIMILAR O/P BUT INTERNAL WORKING IS DIFFERENT

TAKES 3 PARAMETERS
GIVEN VALUE
FIELDS TO CHANGE
NEW VALUE FOR THE CHANGED FIELDS

It is Character by Character replacement not string by string

No of Characters in 2nd and 3rd parameters must be same


If 2nd parameter has more Characters, the extra Characters are changed to null
If 3rd parameter has more Characters, the extra Characters remain unused
If a Character in 2nd parameter is not present in given string, it makes no effect
Select translate ('ORACLE SERVER' , 'OEL, '123’) from dual;

O/P 1RAC32 S2RV2R

Select translate ('ORACLE SERVER' , 'OEL' , '12’) from dual;

O becomes 1 E becomes 2 and L becomes null


O/P 1RAC2 S2RV2R

Select translate ('ORACLE SERVER' , 'OEL' , '1234’) from dual;

O becomes 1 E becomes 2 L becomes 3 AND 4 REMAINS UNASSIGNED


O/P 1RAC32 S2RV2R

8 REPLACE
String by string replacement i.e.only if entire string present in 2nd parameter is available in 1st parameter, change is
made.
No of parameters in 2nd and 3rd parameters need not be same

TAKES 3 PARAMETERS
GIVEN VALUE
FIELDS TO CHANGE
NEW VALUE FOR THE CHANGED FIELDS

Select replace (‘ORACLE SERVER' , 'ER' , '12’)


FROM DUAL;

O/P ORACLE S12V12

Select replace (‘ORACLE SERVER' , AE , '12’)


FROM DUAL;
O/P ORACLE SERVER

Select replace (‘ORACLE SERVER' , 'ER' , '12345’)


FROM DUAL;

O/P ORACLE S12345V12345V12


____________________________________
____________________________________
B21 VIDEO
SQL FUNCTIONS PART 3

9 SUBSTR
Used to take part of a string

3 parameters
Input
Starting position – can be + , - or 0
No of characters

If second parameter is zero, treat it as 1


If second parameter is -ve, start counting from right side of string

3rd parameter is optional


If not specified, it goes till string ends

Select SUBSTR ('ORACLE' , 1 , 4) from dual;

O/P ORAC

Select SUBSTR ('ORACLE' , 4 , 4) from dual;

O/P CLE

Select SUBSTR ('ORACLE' , 0 , 4) from dual;

O/P ORAC
0 is same as 1 for starting position

Select SUBSTR ('ORACLE SERVER' , 4) from dual;

O/P CLE SERVER

Select SUBSTR ('ORACLE SERVER' , -5 , 4) from dual;

O/P ERVE
Start from right end… 5th from right end is 1st E in SERVER. FROM E, take 4 Characters to right
___________________________________
10 INSTR
To search if a given Character or Group of Characters is present within a given value
If the Character or group of characters is present, fn returns position of the Character
If not present, fn returns zero

4 parameter
Given input
Characters or grp of characters to search
Starting position OPTIONAL
No of Occurrences OPTIONAL

If starting position is not given it is considered as 1


Starting position can be positive or negative
If negative, searching starts from right side
Occurrence must be greater than zero
If occurrence is not specified it is considered as one
If starting position is 0, O/P is zero
If occurrence is 0, error is thrown as argument out of range

Select instr( 'ORACLE SERVER' , 'O' , 1 , 1) from dual;

O/P 1

Select instr( 'ORACLE SERVER' , 'E' , 1 , 1) from dual;

O/P 6

Select instr( 'ORACLE SERVER' , 'E' , 1 , 2) from dual;

O/P 9

Select instr( 'ORACLE SERVER' , 'E' ) from dual

O/P 6

Select instr( 'ORACLE SERVER' , 'X' , 1 , 1) from dual;

O/P 0

Select instr( 'ORACLE SERVER' , 'E' , 7 , 3) from dual;

O/P 0

Select instr( 'ORACLE SERVER' , 'E' , -1 , 1) from dual;

O/P 12 searching from right end but POSITION COUNTED FROM LEFT ALWAYS

Select instr( 'ORACLE SERVER' , 'E' , -2 , 2) from dual;

O/P 9

11 REVERSE function – reverses string

Select reverse('oracle') from dual;

O/P elcaro
____________________________________
NUMERIC FUNCTIONS
Manipulate numeric values and return numeric values as a result
I/P is always number and O/P is always a number

ABS CEIL FLOOR POWER MOD SQRT SIGN LOG LN EXP ROUND TRUNC

TRIGONOMETRIC FNS
SIN ASIN SINH

STATISTICAL FNS
STDDEV VARIANCE

GROUP/AGGREGATE FNS
MIN MAX SUM AVG COUNT DISTINCT UNIQUE
____________________________________

1 ABS FUNCTION
GIVES ABSOLUTE VALUE

Select abs(-123) , abs(123) , abs(0) from dual;

O/P 123 123 0

2 CEIL FUNCTION
Immediate next highest integer value for a decimal no
Same integer given for integer value

Select ceil(-123.45) , ceil(123.45) , ceil(123) from dual;

O/P -123 124 123

3 FLOOR FUNCTION
Immediate lower integer for decimal no
Same integer for integer no

Select floor(-123) , floor(123) , floor(-123.45) , floor(123.45) from dual;

O/P -123 123 -124 123

4 POWER FUNCTION
ACCEPTS 2 PARAMETERS
FIRST VALUE RAISED TO POWER OF SECOND VALUE

Select power(2,3) , power(-2,3) , power(1,1) , power(1.5, 2.4) from dual;

O/P 8 -8 1 2.64617800….

Select power(2,0) , power(-45,0) , power(0,0) , power(0,2) from dual;

O/P 1 1 1 0

5 SIGN FUNCTION
POSITIVE VALUE GIVES +1
NEGATIVE VALUE GIVES -1
ZERO GIVES ZERO
DECIMAL NO ALSO ACCEPTED

Select sign(123) , sign(-123) , sign(0) from dual;

O/P 1 -1 0

6 MOD FUNCTION
Gives remainder

Select mod(2,2) , mod(5,2) , mod(15,3), mod(0,0) , mod(5,0), mod(0,5) from dual;

O/P 0 1 0 0 5 0

7 SQRT FUNCTION
GIVES SQUARE ROOT
I/P should be 0 or greater than 0

Select sqrt(4) , sqrt(0) , sqrt(3) , sqrt(1.3) from dual;

O/P 2 0 1.73205081 1.14017…..

Select sqrt(-4) from dual;

O/P Error- Value out if range

8 LOG FUNCTION
2 PARAMETERS
FINDS LOG OF 2nd INPUT TO 1st INPUT AS BASE

Select log(0,0) , log(0,1) , log(10,0) from dual;

Argument 0 is out of range

Select log(5,5) , log(10,100) from dual;

O/P 1 2

9 EXP
Finds e to the power x
X is the I/P parameter

Select exp(2) , exp(1) , exp(0) , exp(-2) from dual;

O/P 7.3890561 2.718 1 1.1353

10 LN
NATURAL LOG

LN AND EXP are recipocal of each other

Select ln(7.3890561) , ln(1) from dual;


O/P 2 0

11 TRUNC
2 PARAMETERS
FIRST IS I/P
Second is no of digits in decimal part to remain after truncation (OPTIONAL)
If 2nd parameter is not given we remove complete decimal part
2nd parameter can be –
0  remove complete decimal
1  leave 1 decimal digit
2  leave 2 decimal digit
-1  remove decimal and make 1 digit before decimal as 0
2  remove decimal and make 2 digit before decimal as 0

Select trunc(123.45) , trunc(123.45 , 0) , trunc (123.45, 1) , trunc(123.45 , 2), trunc(123.45 , 3) from dual;

123 123 123.4 123.45 123.45

Select trunc(123.45 , -0) , trunc(123.45 , -1) , trunc (123.45, -2) , trunc(123.45 , -3), trunc(123.45 , -4) from dual;

123 120 100 0 0

12 ROUND
TAKES 2 PERIMETERS
2ND IS OPTIONAL
SAME FUNCTIONING AS TRUNC BUT DATA IS ROUNDED OFF AS WELL

Select round(123.45) , round(123.45 , 0) ,


Round(123.45 , 1) , round(123.45 , 2) ,
Round(123.12 , 1) from dual;

123 123 123.5 123.45 123.1

Select round(123.45 , -1) , round(123.45 , -2) ,


Round(123.45 , -3) , round(127.45 , -1) ,
Round(153.12 , -2) from dual;

120 100 0 130. 123.1 200


____________________________________
TRIGONOMETRIC FUNCTIONS

1 SIN

Select sin(30) from dual;

O/P -0.9880316

Here 30 is not 30 degree but 30 radian

2 ASIN
SIN INVERSE FUNCTION
Argument range
Sine -1 to 1
Cose -1 to 1
Tan -infinity to + infinity

SELECT ASIN(30) FROM DUAL;

O/P error argument out of range

Select asin(1) , acos(1) , atan(1) from dual;

O/P 1.5707 0 0.785

3 SINH
Sine hyperbolic fn

Select sinh(30) from dual;

O/P 5343237290762.2310
____________________________________
STATISTICAL FUNCTIONS

1 STDDEV

SELECT STDDEV(25) FROM DUAL;

O/P 0

2 VARIANCE

SELECT VARIANCE(234) FROM DUAL;

O/P 0
____________________________________
____________________________________
B22 VIDEO SQL FUNCTIONS PART 4

GROUP/AGGREGATE FUNCTIONS
I/P IS MULTIPLE VALUES AND O/P IS ONE VALUE FOR EACH GROUP

Table column salary

950
1100
1250
1250
1300
1500
1600
2450
2500
2850
2975
3000
3000
5000

Select max(sal) min(sal) , count(sal) , sum(sal) , avg(sal) from tablename;

5000 950 14 30725 2194.64286

Select unique(sal) from tablename;

950
1100
1250
1300
1500
1600
2450
2500
2850
2975
3000
5000

12 rows selected

Select distinct(sal) , unique(sal) from tablename;

O/P Error missing expression

WE CANT TAKE DISTINCT AND UNIQUE TOGETHER IN AN EXPRESSION


_________________________________
_________________________________
B23 VIDEO
SQL FUNCTIONS PART 5

DATE FUNCTIONS

SYSDATE
CURRENT_DATE
ADD_MONTHS(Date , +-N)
LAST_DAY(Date)
NEXT_DAY(Date)
MONTHS_BETWEEN(Date1 , Date2)
NEW_TIME(Date , this ,that)
TRUNC
ROUND
EXTRACT
TO_CHAR

Let date be 08-OCT-2013

1 SYSDATE
Date from server system
Select sysdate from dual;

O/P 08-OCT-13

2 CURRENT_DATE
Date from client system

Select current_date from dual;

O/P 08-OCT-13

Select sysdate , add_months(sysdate , 6) ,


Add_months(sysdate , -6)
From dual;

O/P 08-OCT-13 08-APR-14 08-APR-13

3 LAST_DAY
It gives last day of month

Select last_day(sysdate) from dual;

O/P 31-OCT-13

4 NEXT_DAY
2 PARAMETERS
1ST IS INPUT DATE
2ND IS THE DAY OF WEEK FOE WHICH WE NEED THE DATE
2ND PARAMETER CAN ACCEPT
MONDAY or MON or 2

If today is Tuesday and we use next day for Tuesday, we will get the date of Tuesday next week, not today

Sunday = 1 and Sat equals 7

Select next_day(sysdate , 'thu') from dual;

O/P 10-OCT-13

Select next_day(sysdate , 'thursday') from dual;

O/P 10-OCT-13

Select next_day(sysdate , 5) from dual;

O/P 10-OCT-13

5 NEW_TIME
To convert time from one time zone to another or compare

3 parameters
1st is input date
2nd is input time zone
3rd is output time zone

Select to_char(new_time(sysdate, PST , AST) , 'DD-MON-YYYY HH:MI:SS AM') from dual;

08-OCT-2013 07:34:04 PM

6 Months_between
Takes 2 PARAMETERS
Operation is first parameter – second parameter

Select months_between(sysdate , sysdate + 60 ) from dual;

O/P -1.967

7 TRUNC
No adjustment only truncation
2 PARAMETERS
1st is input date
2nd is level of truncation.
2nd parameter can take 3 values.
DAY goes to beginning of today i.e 12 am
MONTH
YEAR or YY or YYYY (capital or small or initcap)
HH or HH12 or HH24 removes minutes and MI removes seconds
We cant truncate seconds because sysdate doesn’t have fractional part of second.
Error thrown is bad precision specifier
W if 1st day of input date’s month is Tuesday, function takes input date and goes to the immediately previous Tuesday
Q Beginning of quarter
WY if first day of the year is Tuesday, the function goes to Tuesday immediately before the input date, that is
beginning of week for the beginning of year

Select trunc(sysdate, 'year') from dual;

O/P 01-JAN-2013

Select to_char(trunc(sysdate, ‘day) , 'DD-MON-YYYY HH:MM:SS AM) from dual;

O/P 08-OCT-2013 12:00:00 AM

Select trunc(sysdate, 'YY') from dual;

O/P 01-JAN-2013

Select trunc(sysdate, 'YYYY') from dual;

O/P 01-JAN-2013

Select trunc(sysdate, month) from dual;

O/P 01-OCT-2013

Select trunc(sysdate, ‘Q') from dual;


O/P 01-OCT-2013

Select trunc(sysdate, ‘W) from dual;

O/P 08-OCT-2013

Select trunc(sysdate, ‘WW) from dual;

O/P 08-OCT-2013

Select to_char(trunc(sysdate, ‘HH') , 'DD-MON-YYYY HH:MM:SS AM) from dual;

O/P 08-OCT-2013 10:00:00 AM

Select to_char(trunc(sysdate, ‘MI) , 'DD-MON-YYYY HH:MM:SS AM) from dual;

O/P 08-OCT-2013 10:45:00 AM

8 ROUND
Same as trunc but rounding off takes place.
For year, rounded by 6 months
For month, rounded by 15 days
For day, rounded by 12 pm
For second, rounded by 30 second

If O/P exceeds, O/P is next year beginning or next month beginning or next day beginning or next minute beginning

Select round(sysdate , 'YEAR') from dual;

O/P 01-JAN-2014

9 TO_CHAR
Convert date to century day month year hour minute second am/pm form

Things we can extract using to_char

AD/BC/A.D/B.C/ad/bc/a.d/b.c
AM/PM/A.M/P.M/am/pm/a.m/p.m
D/d  day of the week ( 1 to 7)
DD/dd  day of the month (1 to 31)
DDD/ddd  day of the year (1 to 366)
J/j  Julian day (no of days from 01-Jan-4712 BC)
DY/Dy/dy  first 3 char of dayname eg sun
Q/q  quarter of year
YYYY/yyyy  full year
YYY/yyy  3 digit year
YY/yy  2 digit year
Y/y  1 digit year
YEAR/Year/year  full year
HH/hh/HH12/hh12  12 hr format
HH24/hh24  24 hr format
MI/mi  Minutes
SS/ss  seconds
Select to_char(sysdate , 'YEAR') from dual;

O/P
TWENTY THIRTEEN

Select to_char(sysdate , ‘year’) from dual;

O/P
TWENTY THIRTEEN
Twenty thirteen

Select to_char(sysdate , 'Year') from dual;

O/P
Twenty Thirteen

Select to_char(sysdate , ‘Y’) from dual;

O/P
3

Select to_char(sysdate , 'YY') from dual;

O/P
13

Select to_char(sysdate , ‘YYY’) from dual;

O/P
013

Select to_char(sysdate , ‘DD’) from dual;

O/P
8

Select to_char(sysdate , ‘DDD’) from dual;

O/P
280

Select to_char(sysdate , ‘Q) from dual;

O/P
4
________________________________
CONVERSION FUNCTIONS

TO_CHAR  no to char and date to char


TO_DATE  char to date (not always poss)
Format of Character data must be of date format
TO_NUMBER char to no (not always pos)
The Character must be numeric data
TO_TIMESTAMP  char to timestamp
TO_TIMESTAMP_TZ  char to timestamp with timezone
TO_YMINTERVAL  char to year to month interval

Date to number and number to date is never possible

Char to no example 
123 ✓
01-mar-13 ×
1@3 ×

Char to date example 

123 ×
010212 ✓
01-mar-14 ✓
20150102 ✓
01mar13 ✓
__________________________________
__________________________________
B24 VIDEO
SQL FUNCTIONS PART 6

10 EXTRACT FUNCTION
We can EXTRACT FROM SYSDATE
DAY MONTH YEAR

We can EXTRACT FROM SYSTIMESTAMP


DAY MONTH YEAR HOUR MINUTE SECOND

Select extract (day from sysdate) from dual;

O/P 08-OCT-2013

Select extract (Month from sysdate) from dual;

O/P 10

Select extract (Hour from sysdate) from dual;

O/P Error invalid extract field

SET NUMFORMAT 999,999,99;


To set viewing format

Select to_timestamp('01-JAN-2012 10:38:56.111 AM') from dual;

O/P
01-JAN-12 10.38.56.111000000 AM

IF WE ADD DAYS TO A TIMESTAMP VALUE, THE RESULT IS DATE


Select to_timestamp('01-JAN-2012 10:38:56.111 AM') + 1 from dual;

O/P
02-JAN-12

Select to_timestamp('01-JAN-2012 10:38:56.111 AM') + interval '1’ year


from dual;

O/P
01-JAN-13 10.38.56.111000000 AM

Select to_timestamp('01-JAN-2012 10:38:56.111 AM') + interval '1’ Month


from dual;

O/P
01-FEB-12 10.38.56.111000000 AM

Select to_timestamp('01-JAN-2012 10:38:56.111 AM') + interval '0.111’ second


from dual;

O/P
01-JAN-13 10.38.56.222000000 AM
_________________________________
_________________________________
B25 SQL CONSTRAINTS PART 1

A constraint is a business rule.


Can be defined at column level, or a group of columns or at table level
Defined to maintain data integrity
All user constraints are stored in user_constraints table in data dictionary.
Total constraints are stored in all_constraints table in data dictionary.
If you don’t get name the constraint, a system generated name is generated for the constraint. SYS_C123456 (6 NUM
DIGITS)

Constraint type code in user_constraints table –


R- Referential integrity (foreign key)
P – Primary key
C – check constraint
U – unique key
V - with check option, on a view
O - with read only, on a view

Types of constraints-

DOMAIN INTEGRITY CONSTRAINTS


Default
Not null
Check
ENTITY INTEGRITY CONSTRAINTS
Unique
Primary key

REFERENTIAL INTEGRITY CONSTRAINTS


Foreign key
__________________________________
Domain integrity constraints-

Domain means a group of values in a single column so these are defined at column level on a single column only.

PRIORITY ORDER –
1 DEFAULT
2 CHECK AND NOT NULL HAVE EQUAL PRIORITY

DEFAULT
It is not exactly constraint can be used as one
If we define a default value, then if you do not enter a value for that attribute the default value is taken by itself
A TABLE CAN HAVE MULTIPLE DEFAULT COLUMNS

Create table emp


( Eno number,
Ename varchar(5) ,
Sal number,
Dno number default 10
);

Create table emp


( Eno number,
Ename varchar(5) default 'ABC' ,
Sal number,
Dno number
);

Create table emp


( Eno number,
Ename varchar(5) ,
Dob date default sysdate,
Sal number,
Dno number
);

Create table emp


( Eno number,
Ename varchar(5) ,
Dob date default systimestamp,
Sal number,
Dno number
);

Not null constraint


Does not allow null values
One not null can be defined on one column only
Multiple not null constraint possible in a table with one on one mapping
can be defined at column level only

Create table emp


( Eno number constraints c1 not null,
Ename varchar(5) ,
Dob date default sysdate,
Sal number,
Dno number
);

Create table emp


( Eno number default 1 not null,
Ename varchar(5) ,
Dob date default sysdate,
Sal number,
Dno number
);

Create table emp


( Eno number not null default 1,
Ename varchar(5) ,
Dob date default sysdate,
Sal number,
Dno number
); ×××××××× missing right parenthesis error

Create table emp


( Eno number,
Ename varchar(5) ,
Dob date ,
Sal number,
Dno number,
Not null (Eno)
);

Error invalid identifier


CANT DEFINE NOT NULL AND DEFAULT AT TABLE LEVEL

If we don’t give constraints name, a system generated sequential constraint name is generated
Constraint names are not stored in table but in data dictionary views
__________________________________

Check constraint

Allows only a valid range of values


can be defined on one column only
can be defined at column level or table level

Create table emp


( Eno number,
Ename varchar(5) ,
Dob date default sysdate,
Sal number,
Dno number check (Dno in (10,20,30))
);

Create table emp


( Eno number,
Ename varchar(5) ,
Dob date default sysdate,
Sal number,
Dno number check (Dno = 20 )
);

Check and not null together-


Create table emp
( Eno number,
Ename varchar(5) ,
Dob date ,
Sal number,
Dno number check (Dno is not null)
);

Check and not null together-


Create table emp
( Eno number,
Ename varchar(5) ,
Dob date ,
Sal number,
Dno number check(Dno = 10) not null)
); ✓

Check and not null together-


Create table emp
( Eno number,
Ename varchar(5) ,
Dob date ,
Sal number,
Dno number check (Dno is not null)
); ✓

CHECK CONSTRAINT AT TABLE LEVEL


Create table emp
( Eno number,
Ename varchar(5) ,
Dob date ,
Sal number,
Dno number,
check (Dno in (10, 15, 20))
); ✓
OR

CHECK CONSTRAINT AT TABLE LEVEL


Create table emp
( Eno number,
Ename varchar(5) ,
Dob date,
Sal number,
Dno number,
Constraint Cc2 check (Dno in (10, 15, 20))
); ✓

All 3 constraint on a table –

Create table emp


( Eno number,
Ename varchar(5) ,
Dob date ,
Sal number,
Dno number default 10 not null check (Dno in (10, 15, 20))
); ✓
_________________________________
Entity integrity constraints
An automatic index is assigned for these

1 UNIQUE
2 PRIMARY KEY

UNIQUE
Does not allow duplicate values
ALLOWS NULL VALUES
Can be defined on one or more columns as a composite key
Can be defined at column level or table level
Below default in priority
When we assign unique constraint on any column a unique index is automatically created for that column in backend

The name of the unique index will be same as the name we give for the unique constraint
Before 10g version using index keyword had to be used for index to be generated for unique constraint but now it is
automatically generated

PRIMARY KEY
Does not allow duplicate values
Does not allow null values
Can be defined on one or more columns as a composite key
Can be defined at column level or table level
Only 1 primary key can be present in a table
On creation of a primary key unique index is automatically created on that column
__________________________________
_________________________________
B26 VIDEO
SQL CONSTRAINTS PART 2
UNIQUE AT COLUMN LEVEL

Create table emp


( Eno number constraint E1 unique,
Ename varchar(5) ,
Dob date ,
Sal number,
Dno number); ✓

UNIQUE AT TABLE LEVEL

Create table emp


( Eno number,
Ename varchar(5) ,
Dob date ,
Sal number,
Dno number,
Constraint E1 unique(Eno)); ✓

Unique constraint on multiple columns at column level–

Create table emp


( Eno number constraint C1 unique,
Ename varchar(5) constraint c2 unique ,
Dob date ,
Sal number,
Dno number); ✓

Unique constraint as a composite key which is always at table level –

Create table emp


( Eno number,
Ename varchar(5) ,
Dob date,
Sal number,
Dno number,
Constraint E1 unique(Eno , Ename)); ✓

Eno is leading column


Ename is non leading column

Unique plus not null is not the same as primary key because we can have multiple columns of unique plus normal in
the table but there can be only one primary key.
If primary key and unique plus not null are defined as composite keys on two columns the difference between
primary key and unique + not null is that in primary key both columns cannot have null value for a particular record
both fields cannot be null and null. However unique plus not null does not have this restriction. In unique plus not
null, both columns can have null values because null is not equal to null.

SINCE 10G VERSION THE INDEX ON primary key constraint and UNIQUE CONSTRAINT IS AUTOMATICALLY
GENERATED AND IT HAS THE SAME NAME AS THE NAME WE GIVE TO THE primary key or UNIQUE CONSTRAINT
HOWEVER WE CAN GIVE THE INDEX A NAME OF OUR CHOICE
Create table emp
( Eno number constraint C1 unique using index(create index T1 on emp),
Ename varchar(5) ,
Dob date,
Sal number); ✓

Primary key at column level

Create table emp


( Eno number constraint C1 primary key,
Ename varchar(5) ,
Dob date,
Sal number,
Dno number); ✓

Primary key at table level –

Create table emp


( Eno number,
Ename varchar(5) ,
Dob date,
Sal number,
Dno number,
Constraint C1 primary key(Eno)); ✓

Primary key on two columns i.e as a composite key

Create table emp


( Eno number,
Ename varchar(5) ,
Dob date ,
Sal number,
Dno number,
Constraint E1 primary key(Eno, Ename)); ✓
_________________________________
REFERENCIAL INTEGRITY CONSTRAINT
An automatic index is not assigned for this (i.e. for foreign key)

Meaning of referential integrity


if there is a parent child relationship between any two tables, then the child table having the foreign key can only
have those values which are present in the primary key column of the parent table.
If we try to delete a value from the primary key column of the parent table and that value is present it in the foreign
key column of the child table, WE ARE NOT ALLOWED TO DELETE THAT VALUE AND ERROR WILL BE THROWN UNLESS
WE USE ON DELETE CASCADE

FOREIGN KEY CONSTRAINT

It allows the values present in referenced column only


It allows duplicate values
It allows null values
It can be define on more than one columns as a composite key but for this the referenced columns must also be a
composite key
Can be defined at both column and table level
It can reference either primary key constraint or unique constraint
The referenced column may be present in same table or different table
It can refer to self that is the same column on which it is defined i.e. same column can be the primary key as well as
the foreign key
It can be used with ON DELETE CASCADE
It can be used with ON DELETE SET NULL
On delete set default is not available in Oracle

A table which the foreign key is referred to as child table or detail table and the table with the primary key is called
as master table or parent table

Create table emp1


( Eno number constraint C1 primary key ,
Ename varchar(5) ,
Dob date default sysdate,
Sal number,
Dno number,); ✓

Create table emp2


( Eno number constraint C2 primary key ,
Ename varchar(5) ,
Dob date default sysdate,
Sal number,
Dno number,); ✓

EXAMPLE OF FOREIGN KEY REFERENCING A PRIMARY KEY COLUMN IN ITS OWN TABLE AND A COLUMN IN ANOTHER
TABLE, AT COLUMN LEVEL

Create table emp3


( Eno number constraint C3 primary key ,
Ename varchar(5) ,
Dob date default sysdate,
Sal number,
Mgr_id varchar(20) constraint F1 references emp3(Eno),
Dno number constraint F2 references emp2(Dno)); ✓

_________________________________
B27 SQL CONSTRAINTS PART 3

FOREIGN KEY REFERENCING UNIQUE CONSTRAINT

Create table emp1


(Eno number constraint C1 unique ,
Ename varchar(5) ,
Dob date default sysdate,
Sal number,
Dno number,); ✓

Create table emp2


( Eno number constraint C2 unique ,
Ename varchar(5) ,
Dob date default sysdate,
Sal number,
manager_id constraint F1 references emp1(Eno),
Employee_id constraint F2 references emp2(Eno),
Dno number,); ✓

Foreign key referencing itself –


IT IS DEFINED AT TABLE LEVEL

With Primary key –


Null values are not allowed
Duplicate values are not allowed
Functionally it will be serving as a primary key and not as a foreign key until primary key constraint is removed

Create table emp1


( Eno number constraint C1 primary key ,
Ename varchar(5) ,
Dob date default sysdate,
Sal number,
Dno number,
Constraint F1 foreign key (Eno) references emp(Eno)); ✓

With unique-
Null values are allowed
Duplicate values are not allowed since unique has higher priority
Even the foreign key is present it will be in sleeping mode until unique constraint is removed

Create table emp1


( Eno number constraint C1 unique ,
Ename varchar(5) ,
Dob date default sysdate,
Sal number,
Dno number,
Constraint F1 foreign key (Eno) references emp(Eno)); ✓

ON DELETE CASCADE FUNCTIONING

If we delete a primary key record from the parent table and a corresponding value is present in the foreign key
column of child table as well. With ON DELETE CASCADE, the record is DELETED from both the tables and error is
not thrown.

Create table emp1


( Eno number ,
Ename varchar(5) ,
Dob date default sysdate,
Sal number,
Dno number constraint C1 primary key); ✓

Create table emp2


( Eno number constraint C2 primary key ,
Ename varchar(5) ,
Dob date default sysdate,
Sal number,
Dno number constraint F1 references emp1(Dno) ON DELETE CASCADE); ✓

ON DELETE SET NULL


IF YOU DELETE A PRIMARY KEY ENTRY FROM THE PARENT TABLE AND THE CORRESPONDING VALUE IS FOUND IN
THE FOREIGN KEY COLUMN OF THE CHILD TABLE THEN WITH ON DELETE SET NULL OPTION THE VALUE OF THE
DELETED FIELD IS SET AS NULL IN THE CHILD TABLE.
THE ENTIRE RECORD REMAINS AS IT IS, ONLY THE FOREIGN KEY COLUMN WITH THE MATCHING VALUE IS SET AS
NULL

Create table emp1


( Eno number ,
Ename varchar(5) ,
Dob date default sysdate,
Sal number,
Dno number constraint C1 primary key); ✓

Create table emp2


( Eno number constraint C2 primary key ,
Ename varchar(5) ,
Dob date default sysdate,
Sal number,
Dno number constraint F1 references emp1(Dno) ON DELETE SET NULL); ✓

For example, if we delete a department and terminate all employees from that department we can use on delete
cascade, however if you are placing them on the bench and in the near future they will be getting a new department
id we don’t need to delete the records only the department number, so we will use on delete set null

On delete cascade and on delete set null are not used family in real time business applications because if we delete
a parent record then its effect will be in all the child records.

ON DELETE SET DEFAULT


NOT AVAILABLE IN ORACLE

Create table emp2


( Eno number constraint C2 primary key ,
Ename varchar(5) ,
Dob date default sysdate,
Sal number,
Dno number constraint F1 references emp1(Dno) ON DELETE SET DEFAULT 100);
_________________________________
COMPOSITE KEY

IT IS A KEY DEFINED ON MULTIPLE COLUMNS


ONLY UNIQUE, PRIMARY KEY AND FOREIGN KEY CAN BE COMPOSITE KEYS
ALSO KNOWN AS CONCATENATED KEY
We can create composite key on a maximum of 32 columns.
MAXIMUM NUMBER OF COLUMNS EXCEEDED ERROR WILL BE THROWN
CAN ONLY BE DEFINED AT TABLE LEVEL
_________________________________
_________________________________
B31 VIDEO
SQL OPERATORS PART 1

AN OPERATOR IS A KEYWORD
IT HAS A MEANING AND A FUNCTIONALITY THAT IS PREDEFINED FOR THE COMPILER

And operator is a character or a reserved word used in an expression to perform an operation on the elements of
the expression
If any operator receives even 1 null value, the result is always null. THE ONLY OPERATOR WHICH DOES NOT FOLLOW
THIS RULE IS CONCAT.
Operators of same priority are evaluated from left to right

Types of operators-

Unary operators P1
Binary operators P2
Set operators P3

Unary operators –

Work with only one operand


Always on left side of operand
They have the highest i.e. 1st priority
Syntax – Operator operand
There are 2 unary operators…..
+(Unary) - makes operand positive
-(Unary) - makes operand negative

Select +4 from dual;


Select -3 from dual;
__________________________________

BINARY Operator –

Work with 2 operands


They have 2nd highest priority
Syntax - Operand1 Operator Operand2

Types-

Arithmetic Operator P1
Concatenation Operator P2
Relational/Comparison Operator P3
Single value/row
Multiple value/row
Other relational Operator P3
Logical Operator P4

Priority order within Binary operators –

Arithmetic
Concatenation
Relational
Logical

ARIITHMETIC OPERATORS –

Multiplication * P1
Division / P1
Addition + P2
Subtraction - P2

If / And * are together, they are processed from left to right or top to bottom since their priority is equal

CONCATENATION OPERATOR –

|| Parallel pipe symbol


Used for concatenation of two strings
If one value is null, the result is the value of the remaining expression.
Output is null only when both inputs are null

Ex select 'Oracle' || 'Server’ from dual;

RELATIONAL OPERATORS –

Single row/value relational operators –

= Equal to
!= , <> , ^=, (~=) Not equal to (only Pl/Sql)
> Greater than
< Lesser than
>= Greater than or equal to
<= Lesser than or equal to

Multiple row/value relational operators –

IN – CHECKS A VALUE IN A SET OF VALUES


NOT IN –

ALL – FOR MULTIPLE VALUES


HIGHEST PRIORITY
ANY – FOR MULTIPLE VALUES

<ALL >ALL =ALL


<ANY >ANY =ANY

LIKE – MATCHES A PATTERN FROM A COLUMN AND IS USED WITH WILD CARDS
NOT LIKE –

Wild cards –
% - matches any no of char
_ - matches a single char

EXISTS – TRUE OR FALSE


NOT EXISTS
BETWEEN – CHECKS A VALUE WITHIN A RANGE
NOT BETWEEN
Limiting values are also included

LOGICAL OPERATORS –

NOT – DISPLAYS THE ROW IF THE CONDITION IS FALSE


HIGHEST PRIORITY

AND – DISPLAYS ROW ONLY IF BOTH CONDITIONS ARE TRUE

OR – DISPLAYS ROW EVEN IF ONE OF THE CONDITIONS IS TRUE

SET OPERATORS –

All set operators have equal precedence


They have 3rd highest priority
The combine the result-set of two or more query results
THE RESULT SET OF TWO TABLES CAN BE COMBINED USING JOINS BUT THE RESULT SET OF TWO QUERIES CANNOT
BE COMBINED USING JOINS DIRECTLY (EXCEPT THROUGH SUB QUERIES)
WHICH IS WHY WE NEED SET OPERATORS WHICH CAN COMBINE TWO OR MORE QUERIES
With the exception of union all, order by is not needed if you want to sort the data on the basis of first column since
it is already sorted in ascending order on the basis of first column of first query

Properties of Set operators –

After Union operation is performed the resultant output is sorted in ascending order based on first column (except
in case of UNION ALL)
Column names of both queries need not be same but the column names of first query are displayed in output
Number of columns in both the query should be equal
If the number of columns is not equal in both the queries, use null column to compensate and make number of
columns equal
Do not use null column in the first query i.e. take the query with the lesson number of columns as a second query
because column headings are taken from first query (otherwise if first query has the null column then use alias name
for the null columns)
Data types of corresponding column should match

UNION –
Combines the result set of two or more queries without duplication
Sorts data in ascending order based on first column
column names of first query are used as output headings
Number of column should match and their corresponding data types should match
Use null column to make columns equal and use null columns in second query preferably
A union B equals B union A

UNION ALL –
Combine the result set of two or more queries with duplication
There is no sorting of data
Column names of first query are displayed as column headings
Number of column should match and their corresponding data types should match
Use null column to make columns equal and use null columns in second query preferably
A union all B does not equal B Union all A because data is sorted on the basis of the query which comes first. The
data will be same but the positioning of records will vary

INTERSECT –
Fetches common records from two or more queries without duplication
Sorts data in ascending order based on first column
column names of first query are used as output headings
Number of column should match and their corresponding data types should match
Use null column to make columns equal and use null columns in second query preferably
A intersect B and B intersect A give identical results.

MINUS –
Resultant rows of the first query after eliminating the common rows of the second query
Sorts data in ascending order based on first column
column names of first query are used as output headings
Number of column should match and their corresponding data types should match
Use null column to make columns equal and use null columns in second query preferably
A minus B is not equal to B minus A
__________________________________PRACTICALS –

Unary operators –

Select +3 from dual;


O/P 3

Select -3 from dual;


O/P -3

Select 3- from dual;


Error missing expression

Binary Operators –

Arithmetic Operators –

Select 2 + 3 from dual;


O/P 5
____________________________________________________________________
B32 VIDEO
SQL OPERATORS PART 2

Select 9/3 fron dual;


O/P 3

No modular division operator is available in SQL

Select 25/0 from dual;


O/P Error Divisor is equal to zero

Select 2 + 3 – 5 – 6 + 45 + 25 – 26 fron dual;


O/P 38
+ And – have same priority so processing is from left to right above

Select 9 * 2 / 9 from dual;


O/P 2
Same priority

Select 2*
3*
5/
6/
45*
25 from dual;

O/P 2.777
Top down approach since equal priority Operators are present

Select 2+ 3 * 5 / 3 – 25
O/P -18

First solve * and / from left to right


Next + and – from left to right

Select 2 + 5 + null from dual;


O/P null

Select 5 * (35 + 45) / (15 + 5) from dual;


O/P 20

BRACKET HAS HIGHEST PRIORITY.


IT IS USED TO MODIFY SIMPLIFICATION SO WE CAN CHOSE WHICH OPERATION TO PERFORM FIRST
SQUARE AND CURLY BRACES ARE INVALID

CONCATENATION OPERATORS –

Select 'ABC' || NULL from dual;


O/P ABC

Select null || null from dual;


O/P Null

Select 'ABC' || 'YOU' || 'OK' from dual;


O/P ABCYOUOK

Select 2 + 3 || 5 + 3 from dual;


O/P 58
Relational followed by concat

RELATIONAL OPERATORS –

SINGLE ROW –

Select * fr tablename
Where C1 = 1000;

Select * fr tablename
Where C1 != 1000;
__________________________________
__________________________________
B33 VIDEO
SQL OPERATORS PART 2

MULTIPLE ROW –

Select * from emp


Where C1 in (100 , 200 ,300);

Or

Select * from emp


Where C1 = 100 or C1 = 200 or C1 = 300;
_______
Select * from emp
Where C1 not in (100 , 200);

Or

Select * from emp


Where C1 <> 100 and C1 <> 200;
___________
Select * from Emp
where C1 between 100 and 200;

Or

Select * from emp


Where C1 >= 100 and C1 <= 200;
__________
Select * from emp
Where C1 < All ( 100 , 200 , 300);

Or

Select * from emp


Where C1 < 100 and C1 < 200 and C1 < 300;

VALUE LESS THAN ALL 3 VALUES SO LESS THAN 100


______________
Select * from emp
Where C1 > All ( 100 , 200 , 300);

VALUE GREATER THAN ALL 3 VALUES SO GREATER THAN 300

Or

Select * from emp


Where C1 > 100 and C1 > 200 and C1 > 300;
____________
Select * from emp
Where C1 < Any ( 100 , 200 , 300);

Or

Select * from emp


Where C1 < 100 or C1 < 200 or C1 < 300;

VALUE LESS THAN ANY VALUE SO LESS THAN 300


_______________
Select * from emp
Where C1 > Any ( 100 , 200 , 300);

VALUE GREATER THAN ANY OF THE 3 VALUES SO GREATER THAN 100

Or

Select * from emp


Where C1 > 100 or C1 > 200 or C1 > 300;
_________________
Select * from emp
Where C1 = Any ( 100 , 200 , 300);

VALUE AMONG ANY OF THE 3 VALUES

Or

Select * from emp


Where C1 in (100, 200, 300);
_________________
Select * from emp
Where C1 <>ALL ( 100 , 200 , 300);

VALUE NOT AMONG ANY OF THE 3 VALUES

Or

Select * from emp


Where C1 not in (100, 200, 300);

Or

Select * from emp


Where C1 <> 100 and C1 <> 200 and C1 <> 300;
____________
Select * from emp
Where C1 <>ANY ( 100 , 200 , 300);

VALUE NOT AMONG ANY OF THE 3 VALUES

Or
Select * from emp
Where C1 <> 100 or C1 <> 200 or C1 <> 300;
_________________

Select * from emp


Where C1 = ALL (100 ,200 ,300);
O/P no rows selected
NO VALUE CAN BE EQUAL TO ALL THREE
_____________
BETWEEN + AND

Select * from emp


Where C1 between 100 and 200;

Or

Select * from emp


Where C1 >= 1000 and C1 <= 200;
_____________
LIKE OPERATOR

Select * from emp


Where C1 like 'K%’;

Select * from emp


Where C1 like '_K%’

Select * from emp


Where C1 like '%A%’

Select * from emp


Where C1 like '%a%’
_________________
EXISTS OPERATOR
It is like a true or false operator or a Boolean operator

Select * from emp


Where exists (select sal from emp where sal = 3000);

If inner query is true, nor just matching records but all records will be displayed.

Select * from emp


Where exists (select 1 from emp where sal = 3000);

If a salary of value 3000 exists then sub query returns one that is holds true and outer query is executed

BY USING SELECT ONE WE HAVE INCREASED PERFORMANCE OF QUERY BECAUSE DATA IS NOT BEING FETCHED
FROM THE SUBQUERY.
IN THIS WAY THE PERFORMANCE OF EXISTS IS BETTER THAN IN BECAUSE THERE IS NO FETCHING OF DATA

Select * from emp


Where not exists (select 1 from emp where sal = 3000);
Negation of not is true so if the inner query is not met then this time the outer query is executed
__________________________________
__________________________________
B34 VIDEO
SQL OPERATORS PART 4

LOGICAL OPERATORS

OR
AND
NOT

Select * from emp where C1 = 100 or C2 = 'Dep';

Both records are displayed since it is or

Select * from emp where C1 = 100 and C2 = 'Dep';

Records are displayed when both conditions are true

Select * from emp


Where C1 is not null;
_________________________________
SET OPERATORS

UNION

Select * from emp


Where sal < 3000
UNION
Select * from emp
Where sal > 2000;

Or

Select * from emp


Where sal > 2000
UNION
Select * from emp
Where sal < 3000;

Internal Steps –
Fetch 1st query results
Fetch 2nd query result
Join result of 2nd query at end of 1st query
Remove the duplicates
Arrange data on the basis of first column
_____________________________

UNION ALL

Select * from emp


Where sal < 3000
UNION ALL
Select * from emp
Where sal > 2000;

Or

Select * from emp


Where sal > 2000
UNION ALL
Select * from emp
Where sal < 3000;

Internal Steps –
Fetch 1st query results
Fetch 2nd query result
Join result of 2nd query at end of 1st
Query
__________________________________
__________________________________
B35 VIDEO
SQL OPERATORS PART 5

INTERSECT OPERATOR

Select * from emp


Where sal < 3000
INTERSECT
Select * from emp
Where sal > 2000;

Or

Select * from emp


Where sal > 2000
INTERSECT
Select * from emp
Where sal < 3000;

Internal Steps –
Fetch 1st query results
Fetch 2nd query result
Join result of 2nd query at end of 1st
Query
Take common records from the data set and eliminate the rest
Arrange in ascending order of first column of first query
__________________________________
MINUS

Select * from emp


Where sal < 3000
MINUS
Select * from emp
Where sal > 2000;
Or

Select * from emp


Where sal > 2000
MINUS
Select * from emp
Where sal < 3000;

Internal Steps –
Fetch 1st query results
Fetch 2nd query result
Join the results of query to at the end of first query results
If any records from query two are present in query 1 results, those records are eliminated
the results are sorted on the basis of first column of first query
_______________________________

Null column usage with SET operators –

Select C1 , C2 ,C3 from T1


Union
Select C1 , C2 from T2; ×

O/P Error Query block has incorrect number of result columns

Select C1 , C2 ,C3 from T1


Union
Select C1 , C2, null from T2; ✓

Null column in first query

Select C1 , C2 , null from T2


Union
Select C1 , C2 , C3 from T1;

O/P We will get the output but column 3 will have the heading null. Solution is to either use null column in second
query or use an alias name

Select C1 , C2 ,null as C3 from T2


Union
Select C1 , C2, C3 from T1;

Data types of corresponding column should match –

Select ename , C2 from T1


Union
Select eno , C2 from T2; ×

Or

Select 1 from dual


Union
Select 'A' from dual; ×

If datatypes don’t match, error is thrown saying expression must have same datatype of corresponding expression
_________________________________
SET OPERATION ON MORE THAN TWO QUERIES

DEFAULT ORDER –
QUERY 1 UNION QUERY 2 UNION QUERY 3

FIRST QUERY IS JOINED WITH SECOND QUERY AND THE COMBINED RESULT IS JOINED WITH THE THIRD QUERY
We don't need bracket for default operation.
IF YOU WANT SECOND QUERY TO BE JOINED WITH THIRD QUERY AND THEN THE RESULT TO BE JOINED WITH FIRST
QUERY THEN WE NEED BRACKET

Select C1 , C2 ,C3 from T1


Where C1 = 1000
Union
(Select C1 , C2, C3 from T2
Where C2 = 2000
Intersect
Select C2, C2, C3 from T3
Where C3 = 3000);
__________________________________
__________________________________
DINESH ORACLE JOINS PART 1

TYPES OF JOINS

1 Physical Join

This is established through the use of integrity constraints between two tables. A foreign key referencing
a primary key is an example of a physical join

2 Logical Join – to get data from multiple tables

A To get combined data


USING SET OPERATORS
We must have same data type and selected number of columns must be selected

B To get combination of data


We can select different data types and different number of columns

IF YOU SELECT STAR FOR TABLES YOU WHILE USING JOIN OPERATION THEN THE COMMON COLUMNNS IN BOTH
TABLES ARE REPEATED IN THE OUTPUT SET AND THE REPEATED COLUMN HAS THE SAME NAME AS THE ORIGINAL
COLUMN NAME FOLLOWED BY UNDERSCORE 1
EVEN THE JOINING KEY IS REPEATED IN SUCH A SCENARIO

Types of JOIN –

CROSS JOIN
EQUI JOIN
INNER JOIN
SELF JOIN
OUTER JOIN –
LEFT OUTER JOIN
RIGHT OUTER JOIN
FULL OUTER JOIN
_______________________________
CROSS JOIN
It is a Cartesian product, i.e. combination of data between tables.
It displays all possible combinations, both valid and invalid combinations

Let set A = {a , b, c , d}
Let set B = {10 , 20}

A × B = (a , 10) , (a , 20) , (b , 10) , (b , 20), (c , 10) , (c , 20) , (d , 10) , (d , 20)

Now, if A is employee set and B is department set, in business scenario either a is in 10 or 20. So cross join will give
valid + invalid data
CROSS JOIN GIVES VALID DATA IN MANY TO ONE MAPPING ONLY
FOR MANY TO MANY MAPPING CROSS JOIN GIVES VALID + INVALID DATA
TO GET ONLY VALID DATA WE USE EQUI JOINS

CROSS JOIN SYNTAX –

Select A.Column1, A.Column2, B.Column3.


From table A , table B
Where < Cond >
Order by ……..

Many to one mapping meaning?


If we do not use where clause in CROSS JOIN, data will be valid + invalid
By using where clause, we can establish many to one mapping by specifying the condition for the columns we want
to select

Ex

Select A,C1 , B.C1


From A, B
Where A.C1 in (a , b)
And B.C1 = 20;

Now we don’t get invalid data.

THERE IS NO SORTING OF DATA FOR CROSS JOINS.


IN THE OUTPUT, THE FIRST ROW OF FIRST TABLE IS MATCHED WITH FIRST ROW OF SECOND TABLE, FOLLOWED BY
SECOND ROW OF FIRST TABLE BEING MATCHED WITH FIRST ROW OF SECOND TABLE AND SO ON TILL ALL THE ROWS
OF FIRST TABLE ARE MATCHED WITH THE FIRST ROW OF SECOND TABLE.
NOW, FIRST ROW OF FIRST TABLE IS MATCHED WITH SECOND ROW OF SECOND TABLE FOLLOWED BY SECOND ROW
FIRST TABLE BEING MATCHED WITH SECOND ROW OF SECOND TABLE, AND SO ON.
__________________________________
EQUI JOIN
A CROSS JOIN WITH A JOIN CONDITION SPECIFIED BY THE USE OF = OPERATOR IS AN EQUI JOIN

JOIN CONDITION?
TO LINK COMMON COLUMNS

TABLE1.PRIMARY KEY = TABLE2.FOREIGN KEY

EQUI JOIN SYNTAX –

Select A.Column1, A.Column2, B.Column3.


From table A , table B
Where < Filter Cond >
AND
<JOIN CONDITION>
Order by ……..

First we should write where condition and then join condition. This increases the performance of the query by
limiting or filtering data.

JOIN FOLLOWED BY FILTER


If table A has 100 records and table B has 10 records, then 1000 comparisons are made. The filter will perform 100
comparisons.
Total comparisons = 1100

FILTER FOLLOWED BY JOIN


If after filtering there are only 20 records then total number of comparisons are 20 into 10 = 200
200 + 100 = 300 comparisons
MUCH LESSER

Example –

Select p.prodname , c.compname


From prod p , comp c
Where p.compid = c.compid;

FOR EQUI JOINS, IF THE TWO TABLES BEING JOINED ARE JOINED ON THEIR PRIMARY KEY AND FOREIGN KEY
COLUMNS, THE OUTPUT DATA IS SORTED IN ASCENDING ORDER OF THE JOINING FIELD THAT IS THE PRIMARY KEY /
FOREIGN KEY FIELD
OTHERWISE THE DATA REMAINS UNSORTED

__________________________________
__________________________________
ORACLE JOINS BY DINESH PART 3

INNER JOIN
the output of an inner join is same as that of an equi join. The way we write the query is what differs.
KEYWORD ON IS USED TO SPECIF inY JOIN CONDITION

INNER JOIN Syntax –


Select …..
From table 1 INNER JOIN table 2
ON
Table1.Column1 = Table2.Column2
INNER JOIN Table 3
ON
Table2.Column2 = Table3.Column1
Where <Filter Cond> ;

Differences between equi join and inner join –


Where condition can only be specified at the end in the case of inner join
Inner join can be applied on multiple tables, but only on two tables at once

FOR INNER JOINS, IF THE TWO TABLES BEING JOINED ARE JOINED ON THEIR PRIMARY KEY AND FOREIGN KEY
COLUMNS, THE OUTPUT DATA IS SORTED IN ASCENDING ORDER OF THE JOINING FIELD THAT IS THE PRIMARY KEY /
FOREIGN KEY FIELD
OTHERWISE THE DATA REMAINS UNSORTED
________________________________
SELF JOIN
A table which is joined itself is known as self join.
In this case we can use two alias names for single table. Here the alias names are temporary.

It is used where we need data from a table based on the condition on a column in the same table.

If we are applying where condition on the first table, then the data must be fetched from the second table

Syntax –

Select B.Col1 , B.Col2


From Table 1 A, Table 1 B
Where A.Col3 = < >
And A.Col1 = B.Col1;

THE TOTAL NUMBER OF ROWS IN A TABLE WITH SELF JOIN AND HAVING NO WHERE CONDITION IS EQUAL TO THE
SQUARE OF THE NUMBER OF ROWS IN THE INDIVIDUAL TABLE
__________________________________
__________________________________
DINESH ORACLE VIDEOS
ORACLE JOINS PART 5

OUTER JOIN

If you need the output of equi join with outer join, we should USE INNER JOIN AND NOT EQUI JOIN BECAUSE EQUI
JOIN SUPPORTS WHERE CLAUSE BUT OUTER JOIN SUPPORTS ONLY ON CLAUSE. So they both will be incompatible

Outer join + inner join ✓


Outer join + equi join ×

OUTER JOIN DISPLAYS ALL DATA FROM ONE TABLE AND ONLY MATCHING DATA FROM THE SECOND TABLE.
JOIN CONDITION IS SPECIFIED USING ON CLAUSE

THERE ARE 3 TYPES OF OUTER JOINS –

1 LEFT OUTER JOIN OR LEFT JOIN –


We get all data from left table and only matched data from right table

2 RIGHT OUTER JOIN OR RIGHT JOIN –


We get all data from right table and only matched data from left table
3 FULL OUTER JOIN OR FULL JOIN –
Displays 3 types of data in following order–

A Matched data from both tables


B Unmatched data from left table
C Unmatched data from right table

Full outer join is a combination of data from left outer join + right outer join - inner join

Syntax –

Select Col 1, Col 2


From Table 1
LEFT/RIGHT/FULL JOIN
Table 2
On < Join Cond >
Where < Filter Cond >
Order by …..

Examples –

/*LEFT OUTER JOIN */


SELECT P.*,C.*
FROM PROD_DTLS P
LEFT OUTER JOIN COMP_DTLS C
ON
P.PROD_COMP_ID=C.COMP_ID;

/*RIGHT OUTER JOIN */


SELECT P.*,C.*
FROM PROD_DTLS P
RIGHT OUTER JOIN COMP_DTLS C
ON
P.PROD_COMP_ID=C.COMP_ID;

/*FULL OUTER JOIN */


SELECT P.*,C.*
FROM PROD_DTLS P
FULL OUTER JOIN COMP_DTLS C
ON
P.PROD_COMP_ID=C.COMP_ID;

IN LEFT OUTER JOIN, THE DATA IS SORTED IN THE OUTPUT, ON THE BASIS OF THE PRIMARY KEY OF THE LEFT SIDE
TABLE IRRESPECTIVE OF THE JOINING KEY

IN RIGHT OUTER JOIN, THE DATA IS SORTED IN THE OUTPUT, ON THE BASIS OF THE PRIMARY KEY OF THE RIGHT SIDE
TABLE IRRESPECTIVE OF THE JOINING KEY

IN FULL OUTER JOIN, THE DATA IS SORTED IN THE OUTPUT, ON THE BASIS OF THE PRIMARY KEY AND NOT THE
JOINING KEY
__________________________________
B36 VIDEO + DINESH ORACLE VIDEOS
SQL SUBQUERY PART 1
SUBQUERIES ARE USED WHEN WE WANT TO BUILD THE QUERY DYNAMICALLY, ON UNKNOWN INPUT VALUE

WHY DO WE NEED SUBQUERIES WHEN WE HAVE JOINS?


IF WE NEED TO SELECT RECORDS FROM ONLY ONE TABLE ON THE BASIS OF CONDITIONS FROM MULTIPLE TABLES,
SUBQUERIES GIVE MORE OPTIMISED PERFORMANCE

Get the department name for empid 101 –

USING JOIN –

Select d.dname from dept d, emp e


Where e.empno = 101 AND
e.deptno = d.deptno;

Now, if dept table has 14 records and dept id of empno 101 is (say) 4. This field is compared with all 14 rows of the
department table.

USING SUBQUERY –

Select d.dname from dept


Where deptno = (Select deptno from emp where empno = 101);

THIS IS MORE EFFICIENT AS LESSER READS ARE NEEDED

Subqueries can be used in any DML statement like select, insert, update and merge

ORDER BY CLAUSE CANNOT BE USED WITHIN A SUBQUERY

Subquery is also called a nested query or inner query


It is used in a clause of another query
Subquery is used to dynamically build a search condition for the main query
A single query may be made up of multiple sub queries
A SUBQUERY CAN BE RETURNED IN THE WHERE CLAUSE OR HAVING CLAUSE OF ANOTHER QUERY
A SUBQUERY IS PROCESSED BEFORE THE MAIN QUERY
A subquery may contain another subquery
Subqueries may contain join queries and search conditions of their own
A subquery can retrieve information from more than one table
A subquery can refer two tables in main query (correlated subquery)
A subquery can return single or multiple values

Precautions while using subqueries –

Subqueries are only included in where or having clause of main query


A proper relational operator must be used based on the output of the subquery
If subquery produces no values then the output of the main query is also null, i.e. no rows returned
We can use DISTINCT to force subquery to generate a single value in some cases
Use aggregate functions without group by clause to generate a single value
We can use subqueries that produce any number of rows if we use multi row relational operators
Placed inside parenthesis

Order of execution of subquery –


1 Execution of subquery
2 Subquery gives a result
3 The result of the subquery is used by the main query
4 Execution of main query using the result of subquery
5 Production of final output by the main query

Types of subqueries –

1 Scalar /Single row /Single value subquery


Returns exactly one value of one column
2 Multi value / Multi row subquery
Returns more than one rows of 1 column
3 Multi column subquery
Returns more than one columns
4 Inline view
A query used in Select ,Group by, From or Order by clause
5 Correlated subquery
Subquery depends on main query for execution
__________________________________

SCALAR or SINGLE ROW or SINGLE VALUE SUBQUERY –

A SUBQUERY THAT RETURNS A SINGLE VALUE I.E. SINGLE ROW OF A SINGLE COLUMN ONLY
WE CAN USE SINGLE ROW RELATIONAL OPERATORS OR MULTI ROW RELATIONAL OPERATORS WITH SINGLE VALUE
SUBQUERY

Select * from emp


where sal > (Select sal from emp where ename = 'SCOTT');
__________________________________
__________________________________
B37 VIDEO + DINESH ORACLE VIDEOS
SQL SUBQUERY PART 2

MULTI VALUE or MULTI ROW SUBQUERY –

THIS SUBQUERY RETURNS MULTIPLE ROWS BUT ONLY ALL THE ROWS BELONG TO ONE COLUMN ONLY

Select * from emp


Where sal > (Select sal from emp where sal = 3000) ;

O/P Error single row subquery returns more than one row

Select * from emp


Where sal >ALL (Select sal from emp where sal = 3000) ;

O/P All rows where employees have salary greater than 3000 are returned

Select * from emp where sal IN (Select sal from emp where job = 'CLERK');

O/P All rows where employees are clerks are returned


__________________________________

MULTI COLUMN SUBQUERY


SUBQUERY RETURNS VALUES OF MULTIPLE COLUMNS I.E. ONE OR MORE ROWS OF MULTIPLE COLUMNS
WE USE SINGLE ROW RELATIONAL OPERATORS IF SUBQUERY PRODUCES OUTPUT OF SINGLE ROW ONLY
WE HAVE TO USE MULTI ROW RELATIONAL OPERATORS IF SUBQUERY PRODUCES OUTPUT OF MULTIPLE ROWS

Select * from emp where sal, comm = (Select sal, comm from emp where ename = 'WARD');

O/P Error Invalid relational operator

Select * from emp where (sal, comm) = (Select sal, comm from emp where ename = 'WARD');

OR

Select * from emp where sal = (Select sal from emp where ename = 'WARD')
And comm = (Select comm from emp where ename = 'WARD');

In the multi column subquery, i.e. salary and commission are selected together in one subquery, which results in
better performance since only one subquery is being executed in contrast to two separate subqueries being
executed for salary and commission respectively in the second query
__________________________________

INLINE VIEW

A QUERY USED IN ANY OTHER CLAUSE BESIDES THE WHERE CLAUSE AND HAVING CLAUSE IS CALLED AS AN INLINE
VIEW
AN INLINE VIEW IS A QUERY USED IN ONE OF THE FOLLOWING CLAUSES –
SELECT
FROM
GROUP BY
ORDER BY CLAUSE

Select * from (Select * from emp where deptno = 10);

O/P All rows with deptno = 10 are returned

Select empno, ename, sal,


(Select nvl2(comm, sal + comm, sal)
from emp
where empno = a.empno) tot_sal
From emp a;

O/P We get Empno Ename Sal and Total_Sal as O/P fields

INLINE VIEW WITH INSERT STATEMENT-

Insert into dept (deptno, dname, loc)


Values ((Select max(deptno) + 10) from dept), 'IT', 'INDIA');
__________________________________

CORRELATED SUBQUERY

A NESTED QUERY WHICH DEPENDS ON THE MAIN QUERY IS A CORRELATED SUBQUERY


IT IS EXECUTED REPEATEDLY, ONCE FOR EACH ELIGIBLE ROW OF THE MAIN QUERY
(CALLED AS CANDIDATE ROW)

Order of execution of a correlated subquery –

1 A candidate row is selected by the main query


2 The subquery will be executed once for the candidate rows selected by main query
3 The subquery will produce a result
4 The main query will use the result given by the subquery
5 The main query will execute once for the result of the subquery
6 Main query decides whether the candidate rows selected area is eligible for the final result or not
7 The second candidate row from main query is selected and so on…

Select * from emp a


Where sal in (Select sal from emp where a.sal = b.sal);

WHY SHOULD CORRELATED SUBQUERY AVOIDED UNLESS ABSOLUTELY NECESSARY?


THE MAIN QUERY IS EXECUTED ONCE, FOLLOWING WHICH THE SUBQUERY IS EXECUTED AND BASED ON THE
RESULT, THE MAIN QUERY IS EXECUTED ONCE AGAIN. SO, THE MAIN QUERY IS EXECUTED TWICE HENCE, REQUIRING
MORE COMPUTATIONAL POWER

No of read operations on the DB disk for a correlated subquery –

A Main query has 10 rows and correlated subquery has 5 rows

B Main query has 5 rows and correlated subquery has 10 rows

In case A, the first candidate row from main query is selected. Now, for this query, 5 reads of subquery take place.
Similarly, for second candidate row, 5 reads of subquery take place. Since there is a grand total of 10 candidate rows,
this operation is repeated five times.

Total reads = (1 × 10 ) + (5 × 10) = 60 reads


Candidate reads + Subquery reads

In case B, the first candidate row from main query is selected. Now, for this query, 10 reads of subquery take place.
Similarly, for second candidate row, 10 reads of subquery take place. Since there is a grand total of 5 candidate rows,
this operation is repeated five times.
Total reads = (1 × 5 ) + (5 × 10) = 55 reads
Candidate reads + Subquery reads

SINCE THE TOTAL NUMBER OF DISK READS IS LESSER IN CASE B, IT IS THE MORE OPTIMISED QUERY.
IN OTHER WORDS, WHEN WE WRITE A CORRELATED SUBQUERY, WE SHOULD PLACE THE TABLE WITH THE LESSER
NUMBER OF ROWS/RECORDS IN THE MAIN QUERY AND GREATER NUMBER OF RECORDS IN THE SUBQUERY FOR THE
MOST OPTIMISE OUTPUT.

REAL TIME USE OF CORRELATED SUBQUERY –


USED TO WRITE REVERSE BUSINESS PROCESS INFORMATION

Ex. If a company has certain products and now the company wants to find out which are the products which have
not been bought by even a single customer, then a correlated subquery will be used.

Or
Ex. A company has eliminated certain departments. Now, the company wants to know if there are any department
which have at least one employee or if there are any departments which have absolutely no employees.

OPERATORS of Subquery –

1 EXISTS –

If at least one output value is generated from the subquery, then EXIST operator returns true and the outer query
will display the output.

If no output value is generated from the subquery, then EXISTS operator returns false and the outer query will not
display the output.

2 NOT EXISTS –

It is the exact opposite of EXISTS.

If no output value is generated from the subquery, then not exists operator returns true and the outer query will
display the output

If at least one output value is generated from the subquery, then NOT EXISTS operator returns false and the outer
query will not display the output

Ex. Get dept details of the dept having at least one employee.

Select d.* from dept d where exists


(Select e.empno from emp e
Where e.deptno = d.deptno);

Or

Select d.* from dept d where exists


(Select 1 from emp e
Where e.deptno = d.deptno);

The first department number from department table is selected from the main query and is feeded to the subquery.
Now, if the department number in employee table matches the department number provided by the main query,
then EXIST condition holds true and the department details for the candidate department number are given an
output.

Ex. Get dept details of the dept having no employees.

Select d.* from dept d where not exists


(Select e.empno from emp e
Where e.deptno = d.deptno);

Or

Select d.* from dept d where not exists


(Select 1 from emp e
Where e.deptno = d.dept);

JOIN + CORRELATED SUBQUERY –


Ex. Three tables are there –
1 Customer details table cust_dtls
2 Account types table act_types
3 Customer account details cust_act_dtls

Find the account name, account type, account no & customer no of all the male customers

Select act.*, cad.actno, cad.act_open_date, cad.cno


From act_types act inner join cust_act_dtls cad
On
Act.act_type = cad.act_type
Where cad.cno in
(Select cno from cust_dtls where gender = 'M');

__________________________________

VIEW
It is a DB object which contains logical copy of data
it is a virtual/imaginary table and does not actually contain any data and does not occupy physical disc space EXCEPT
MATERIALIZED VIEW
It will fetch live data at current database instance
It contains a select statement which fetches data from the base table
It is stored in the data dictionary all_views and user_views
All successful write operations performed on a view are written on to the base table as well
A view maintains data dynamically (i.e. the data fetched reflects latest database instance)

To see the status of a database object, like a view, from user_objects data dictionary, the following query can be
executed –

Select object_name, object_type, status from user_objects where object_name = 'VF_EMP’;

IT IS ALSO CALLED A STORED SELECT STATEMENT BECAUSE THE SELECT STATEMENT USED IN THE VIEW STORED IN
THE DATA DICTIONARY

Need of VIEW?

1 To increase security –
In organizations such as banking and insurance sector, where data information is highly sensitive, we do not want
the entire table data to be made available to every user. Each user must have access to only data specific to him.
This is where we views come in handy. We can deselect attributes with sensitive information in the view we create
(Data hiding).

2 To increase DB performance –
When we query the database, the Oracle engine check whether the table is existing by referring the data dictionary
block ok of the database if the table exists then the data is fetched from the actual data block back to the user. If
this operation is performed 100 times that there are 100 hits on data.
To remove this burden on database we can use views. A logical copy of frequently query data is stored in view. When
we fetch the data from the view, on first transaction the view get the data from the database but from second time
onwards, the view fetches the data from cache memory. If some changes are made to the table before cache
memory refresh, those records are also automatically added to the view.
EFFECT OF STRUCTURE MODIFICATIONS ON BASE TABLE ON VIEW –
If we create a view on a table, the data structure of the view and table is identical.
Now, if we add another column to this table by using the alter statement, the structure of the view will not change.
Since, in the user_views data dictionary, the columns present in the text field are the only the ones that were
available at the time the view was created.

If we delete a base table, the status of the corresponding view in user_objects Data dictionary becomes invalid
automatically

If we delete a column from the base table after the view has been created, the view becomes invalid

ALTER STATEMENT IS NOT ALLOWED WITH THE VIEW WE CANNOT CHANGE THE STRUCTURE OF A VIEW ONCE IT
HAS BEEN CREATED

Alter view v10 add(C2 date);

O/P Error missing or invalid option

Types of views –

1 Simple/Updatable view
2 Complex/Composite view
3 Force view
4 Read only view
5 With check option view

Materialized view is not a type of view but a different object in itself.

Syntax –

SYNTAX –

CREATE VIEW VIEWNAME AS


SELECT ………
FROM …..
Where < Cond >
Order by ……

Ex Create view v_emp


As select * from emp;

Error – insufficient privileges

By default, developers do not have privilege to create views. DB Admin has to grant Access for the same.

CONN SYS/ORCL AS SYSDBA;

GRANT CREATE VIEW TO SCOTT;

CONN SCOTT;

Create view v_emp


As select * from emp;
O/P VIEW CREATED

Each view must have a unique name.


If you try to create a view with a name that is already in use for another view or object (like synonyms), we get an
error saying name is already used by an existing object

If we want to create a view whether name is already in use for an object we can use REPLACE command
Not compatible with Table

Create or replace view v_emp as


Select * from emp;

O/P View created

RENAME A VIEW – ✓

Rename v_emp to v1_ emp;


O/P Table renamed (it says table not view)

DROP A VIEW – ✓

Drop view v_emp;


O/P View dropped

TRUNCATE A VIEW – ×

Truncate view v_emp;


O/P Error invalid truncate command

COMMENT ON VIEW – ✓

Comment on view v_emp is 'Text'; ×


O/P invalid object category for comment command

Comment on table v_emp is 'Text'; ✓


O/P comment created (USE KW TABLE)

Select data from view –


We can select entire data or particular data or specific records.
Functions or group by clause or having clause or order by clause or where clause can be used

Select * from v_emp;

Select empno, ename, sal from v_emp;

Select empno, ename, sal from v_emp


Where sal <= 5000;

Select empno, ename, sal from v_emp


Where sal <= 4000 group by deptno;
Select empno, ename, sal from v_emp
Where sal <= 4000 group by deptno having sum(sal) >= 5000;

Select empno, ename, sal from v_emp


Where sal <= 4000 order by empno;

CREATE A VIEW WITH LIMITED DATA FROM THE TABLE TO HIDE SENSITIVE DATA–

Create or replace view v_emp as


Select empno, ename, job, deptno from emp;

OR

Create or replace view v_emp as


Select empno “Emp No”, ename “Emp Name”, job, deptno from emp;

O/P View created

CREATE VIEW BASED ON ANOTHER VIEW –

Create view vv_emp as


Select * from v1_emp;

The select clause can bring data from table, view, global temporary table, external table, synonym, materialized
view, etc.

To see the views created –

Select * from tab where tabtype = ‘VIEW’;

Select * from user_views;

DESC USER_VIEWS;

SELECT VIEW_NAME, VIEW_TYPE, TEXT_LENGTH, TEXT FROM USER_VIEWS;

Text is the data in the select statement from which data is fetched into the view
Text length is the length of this text
Even if you select * from tablename while creating the view, the text field displays the total columns being selected
and not select *

INTERNAL WORKING OF THE VIEW, I.E. HOW IT BRINGS DATA FROM THE BASE TABLE –

User writes –
Select * from v_emp;

There are 2 steps –

1 Internally, the database data dictionary finds the select query that is referred to by the view v_emp and the query
is converted as –

Select * from (Select text from user_views where view_name = 'V_EMP’);


2 The text basically refers to the list of columns that the select query supposed to fetch so this text is then converted
into the following –

Select * from
(Select empno, ename, sal from emp);
__________________________________

SIMPLE VIEW –
A VIEW THAT IS CREATED BASED ON A SIMPLE TABLE WITHOUT USING THE FOLLOWING –
GROUP BY CLAUSE
ORDER BY CLAUSE
GROUP/AGGREGATE FUNCTION
JOIN
SUBQUERY

All DML (Read + Write) operations are possible on a simple view

Ex –
Create view v_emp
As select * from emp; ✓

Or

Create view v_emp


As select * from emp
Where empid < 200; ✓
__________________________________

COMPLEX VIEW –
A VIEW CREATED BASED ON A SINGLE TABLE BUT WHICH ONE OF THE FOLLOWING CLAUSES –
GROUP BY CLAUSE
ORDER BY CLAUSE
GROUP/AGGREGATE FUNCTION
JOIN
SUBQUERY

OR

A VIEW BASED ON MULTIPLE TABLES

All Read operations are possible but all write operations may or may not be possible depending on the scenario

In live environment, we generally dont have permission to perform any other operation other than select/read
operation on complex views, hence, they are also known as READ ONLY VIEWS in live environment.

Complex view with aggregate function –


Create view v4 as select deptno, sum(sal) as total_sal from emp group by deptno;

Select * from v4;

DEPTNO TOTAL_SAL
40 78000
30 5000
10 7450

Delete from v4 where deptno = 10;

O/P Error data manipulation operation not legal on this view

Insert into v4 values (50, 2500);

O/P Error virtual column not allowed here

Update v4 set deptno = 20 where deptno is null;

O/P Error data manipulation operation not legal on this view

Complex view with join of two tables –


Create view v6 as select * from emp join dept using (deptno);

Delete from v6 where deptno = 10;

O/P 2 rows deleted.

Since the data is deleted from both the tables operation is successful

Complex view of 2 tables with inner join –


Create or replace view v6 as
select empno, ename, sal, dept, deptno, dname
from emp JOIN dept
ON
emp.deptno = dept.deptno;

Delete from v6;

O/P all matching rows get deleted from emp table but no data is deleted from dept table

Insert into v6 values


(1, 'A', 1000, 10, 'D1');

O/P cannot modify more than one base table through a join view

Since the data is being selected from two tables, we cannot insert data directly in a complex view that uses join.
WE CAN UPDATE AND DELETE OPERATION BUT NOT INSERT DATA

Update v6 set sal = 2000


Where empno = 7345;

O/P 1 row updated

Complex view using a subquery –


Create or replace view v7 as
select * from emp where sal >
(Select sal from emp1 where ename = 'FORD');
SELECT, DELETE, UPDATE AND INSERT OPERATIONS ARE ALLOWED ON THIS VIEW

Compress view using a single table but group by clause –

Create view v8 as select deptno, sum(sal) from emp group by deptno;

O/P Error must name this expression with a column alias is thrown for sum(sal) column

Create view v8 as select deptno, sum(sal) as sum_sal from emp group by deptno; ✓
__________________________________

FORCE VIEW –
IT IS A VIEW CREATED ON A BASE TABLE WHICH IS NOT PRESENT IN THE DATABASE
VIEW IS INVALID AND WILL BE CREATED WITH ERRORS
THIS FEATURE IS AVAILABLE FROM ORACLE 9I ONWARDS

Create view vf_emp as select * from emp5;

O/P Table or view does not exist

Create force view vf_emp as select * from emp5;

O/P Warning : view created with compilation errors

Select * from vf_emp;

O/P Error at LINE 1


View scott.vf_emp has errors

Desc vf_emp;

O/P Invalid object for describe

Select view_name, text_length, text from user_views;

VF_EMP 18 SELECT * FROM EMP5

The text field says select * and not select column names because the table emp5 doesn't exist

If the base table is made available (created) after the view has been created, the status of the view in user_objects
data dictionary still remains invalid.
When we try to access the view, the database checks whether the base table is available and find that yes the table
is available and then the view becomes valid and we get the result

Till Oracle 9I, the below statement had to be executed after table creation to make the view valid. Not needed
anymore.

Alter view viewname compile;

If we delete the table, the status of the view in user_objects Data dictionary becomes invalid automatically

Drop table emp5;


Select object_name, object_type, status from user_objects where object_name = 'VF_EMP’;

O/P VF_EMP VIEW INVALID


__________________________________

READ ONLY VIEW


AVAILABLE SINCE ORACLE 9I ONWARDS
ONLY READ OPERATION I.E. SELECT OPERATION IS POSSIBLE ON THIS VIEW

Create view vr_emp as


Select * from emp WITH READ ONLY;

UPDATE VR_EMP SET SAL = 111 WHERE SAL = 1250;

O/P Virtual column not allowed here

Delete from vr_emp;

O/P cannot delete from view without exactly one key-preserved table

__________________________________

WITH CHECK OPTION –


AVAILABLE SINCE ORACLE 9I ONWARDS
WHILE CREATING THE VIEW WE USE A SPECIFIC CONDITION IN THE WHERE CLAUSE ALONG WITH CHECK OPTION
WE CAN PERFORM WRITE OPERATIONS ON THIS VIEW SO LONG AS THE CHECK CONDITION IS NOT BEING VIOLATED

COMPLEX VIEW –
Create view vc_emp as
Select * from emp where deptno = 20;

UPDATE VC_EMP SET DEPTNO = 10 WHERE EMPNO = 2343;

O/P 1 ROW UPDATED

WITH CHECK OPTION –


Create view vc1_emp as
Select * from emp where deptno = 20 WITH CHECK OPTION;

UPDATE VC_EMP SET DEPTNO = 10 WHERE EMPNO = 2343;

O/P Error View with check option where clause violation

UPDATE VC_EMP SET SAL = 3000 WHERE EMPNO = 2343;

O/P 1 row updated

So long as the with check option is not violated, the update be successful

Create view vc2_emp as


Select * from emp where deptno = 20 and sal <= 3000 WITH CHECK OPTION;
Now, WITH CHECK OPTION IS ACTIVE ON BOTH DEPTNO AND SAL

UPDATE VC2_EMP SET DEPTNO = 10 WHERE EMPNO = 2343;

O/P Error View with check option where clause violation

UPDATE VC_EMP SET SAL = 1000 WHERE EMPNO = 2343;

O/P 1 row updated

Since we are updating the salary to 1000 and the with check condition allows salary to be less than or equal to 3000,
the WITH CHECK OPTION is not violated and the update is successful.
__________________________________

PERMISSIONS ON VIEWS –

Grant select on v1_emp to U1;

O/P Grant succeeded

Conn U1/U1;

Select * from Scott.v1_emp;

O/P DATA IS FETCHED


__________________________________

Simple View Complex View

Contains only one single base table or is created from only Contains more than one base tables or is created
one table. from more than one tables.

We cannot use group functions like MAX(), COUNT(), etc. We can use group functions.

Does not contain groups of data. It can contain groups of data.

DML operations could not always be performed


DML operations could be performed through a simple view.
through a complex view.

INSERT, DELETE and UPDATE are directly possible on a simle We cannot apply INSERT, DELETE and UPDATE on
view. complex view directly.

Simple view does not contain group by, distinct,


It can contain group by, distinct, pseudocolumn like
pseudocolumn like rownum, columns defined by
rownum, columns defined by expressions.
expressions.

NOT NULL columns that are not selected by simple


Does not include NOT NULL columns from base tables.
view can be included in complex view.

__________________________________

MATERIALIZED VIEW
Materialized Views in Oracle A materialized view, or snapshot as they were previously known, is a table segment
whose contents are periodically refreshed based on a query, either against a local or remote table.
Using materialized views against remote tables is the simplest way to achieve replication of data between sites.

MATERIALIZED VIEW DIFFERS FROM AN ORDINARY VIEW IN THE SENSE THAT IT ACTUALLY CONTAINS DATA AND AS
PHYSICAL STORAGE ALLOCATED TO IT ON THE DISK

CREATE MATERIALIZED VIEW emp_mv BUILD IMMEDIATE REFRESH FORCE ON DEMAND AS SELECT * FROM
emp@db1.world;
__________________________________
__________________________________
SEQUENCE AND SYNONYM

A sequential is initialized only when we select its next value. Until it is initialized, current value will not fetching data.

To create public synonyms DBA privileges are needed.

Conn system;

Grant create synonym to username;


O/P Grand succeeded

Conn username;

The data dictionary table for synonyms is user_synonyms

__________________________________
__________________________________
INDEX

Created on 1 or more columns (composite)


Uses rowid to fetch data
It decreases the no of verifications in table and decreases load on DB
A unique index is created automatically when we create unique or primary key constraint
Only 1 index can be created on a column
A max of 32 columns can be used in composite index
By default indexes are enabled
We can disable indexes

We cant select data from an index


Index is a 2 dimensional database object like a table containing row id and ordered data

If we delete a table, the index on it is deleted automatically

If a table contains an index, the control goes to index when we select data from that table based on column on which
index has been created

We get ordered data without using order by clause when we fetch data from a column on which there is an index

CONDITION IS VERIFIED FROM INDEX AND DATA IS FETCHED FROM THE TABLE
Select index_name from user_indexes where table_name = 'EMP';

The data of the column on which index is being created, is copied to the index. So there are two copies of data of
that column. One copy in data segment and one in index segment.
The row ID of the data in the index segment is active. The data segment in table also has same row IDs but they are
inactive.

The name of an index must not match with any database object like view.
If we try to create an index on a column which already has an index, error thrown is
Such column list already indexed

If we use DESC keyword while creating index , then index type in data dictionary is Function based index

Types of indexes –

1 B TREE 2 BITMAP

Normal/Regular/Non Unique
Ascending
Descending
Unique
Global
Local
Composite/Concatenated
Function based
Reverse key
Clustered
Index organized table (IOT)

B TREE MEANS BINARY TREE


IT MAY BE FULLY BALANCED OR PARTIALLY BALANCED OR UNBALANCED
BALANCED ONE HAS BETTER PERFORMANCE
__________________________________
Normal index –

Created on entire column and on all records of that column. There is no rearrangement of data

CREATE INDEX I1 ON EMP(empno);

DROP INDEX I1;


__________________________________
Ascending index –
Data is sorted in ascending order and then it is stored in index and row ids are generated accordingly
Thus, data searching is faster than normal index

CREATE INDEX I1 ON EMP(empno ASC);

DROP INDEX I1;


__________________________________
Descending index –
Data is sorted in descending order and then it is stored in the index and row ids are generated accordingly
Data searching is faster than normal index
CREATE INDEX I1 ON EMP(empno DESC);

DROP INDEX I1;


__________________________________
Unique index–
Automatically created for a column with unique constraint
We can explicitly create a unique Index on column but it must have unique values.
Unique Index can be composite having a maximum of 32 columns
ASC and DESC KEYWORDS ARE ALLOWED WHILE CREATING UNIQUE INDEXES

CREATE UNIQUE INDEX I1 ON EMP(empno);

CREATE INDEX I1 ON EMP(gender);


O/P Error cannot create unique index duplicate keys found

CREATE INDEX I1 ON EMP(empno ASC);

DROP INDEX I1;


__________________________________
Global index –
Global index is created on a column of a partitioned table but it can also be created for a normal table, irrespective
of the number of partitions on the table.
So one table has 1 global index only
BY DEFAULT IT IS ASCENDING

CREATE INDEX I1 ON EMP(empno) GLOBAL;

DROP INDEX I1;


__________________________________

Local index –
Local India’s can be created only on a column of a partition table and not a normal table
The index is treated as local to the partition on which it is created
Data is searched within the partition only

CREATE INDEX I1 ON EMP(empno) LOCAL;

O/P Error underlying table of a local partitioned index must be partitioned

DROP INDEX I1;


__________________________________
Composite index –
Can be created on a maximum of 32 columns
It may be ascending, descending, unique, global or local
By default, it is ascending
The very first column is called as the leading column and all the other columns are called as non-leading columns
If we're trying to use a table column on which a composite index has been created but the column in use is a non
leading column in the index, then the index on that column is not used to fetch data
If we still want to use the index for non leading column, then we have to force the index using hint

CREATE INDEX I1 ON EMP(empno, sal, job);


DROP INDEX I1;
__________________________________
Function based index-
Even if we have an index on a column, if you are using any function on that column, than the index is not used.
By default, it is ASC
We can create Unique Function based index as well

CREATE INDEX I1 ON EMP(UPPER(empno));

CREATE INDEX I1 ON EMP(sal + comm);

CREATE UNIQUE INDEX I1 ON EMP(sal + comm); ✓

DROP INDEX I1;


__________________________________
Reverse key index –
All the data is reversed and then stored in index segment and then row ids are generated
Helps in faster performance
Type of reverse index in Use_index dictionary is normal/rev

Ex –

Let data be as given below –


aaaa1 aaaa2 aaaa3 aaaa4

Range scanning is faster if data is –


1aaaa 2aaaa 3aaaa 4aaaa

CREATE INDEX I1 ON EMP(ename) REVERSE;


__________________________________
Clustered index-
It is created on a cluster
A cluster is a space where data of multiple blocks or multiple tables is stored
These tables are mostly those which are frequently used together in JOIN operations
Developers can’t create clustered Index because DBA privileges are needed to create a cluster.

To create a clustered index, we need to create a cluster, move tables or blocks of tables to that cluster and then we
can create the index.
CLUSTERED TABLES CAN’T BE USED BEFORE CLUSTER INDEX IS CREATED

Create cluster c1;

O/P Error missing left paranthesis

Create cluster c1(number);

Create table emp_c


(Empno number,
Ename varchar(10),
Job varchar(10),
Sal number) cluster c1(eno);

O/P Table created


Select * from emp_c;

O/P Error clustered tables cannot be used before the cluster Index is built

Insert into emp_c


Values(1, 'A', 1000, 100, 10);

O/P Error clustered tables cannot be used before the cluster Index is built

CREATE INDEX I1 ON CLUSTER C1;


__________________________________
Index Organization Table –
Index is created on the entire table
In a normal index, data stored in two places, the data segment and the index segment but here data is only stored
in the index segment and it is sorted in ascending order based on primary key column
A PRIMARY KEY IS MANDATORY FOR CREATING IOT

Create table emp


(Empno number,
Ename varchar(10),
Job varchar(10),
Sal number) organization index;

O/P Table created


__________________________________
BITMAP INDEX –

BITMAP CREATED ON COLUMN AT SEGMENT LEVEL


CREATED ON LOW CORDINIALITY COLUMNS
CORDINIALITY MEANS TOTAL NO OF DISTINCT COLUMNS (EX GENDER, RELIGION)
All male values are placed with one bitmap in a segment and all female values will be placed with another bitmap in
a different segment
Used when column is not modified very frequently

MAJOR DRAWBACK-
If we want to update any record in a segment, then the entire segment is locked. Other users cannot update any
other record in that segment until the first lock is released.
Thus, bitmap indexes are not generally used in OLTP systems
__________________________________
Data dictionary –
User_indexes

SELECT INDEX_NAME, INDEX_TYPE, TABLE_TYPE, UNIQUENESS, STATUS, DROPPED


FROM USER_INDEXES
WHERE TABLE_NAME = 'emp';

In user_indexes data dictionary we do not have the column name on which the index has been created and whether
the index is ascending or descending type
The column name and asc/desc order is present in user_ind_columns
User_ind_columns also has column position that is the position of the column on which the index has been created
If a composite index has been created on 1st, 5th and 7th columns respectively the column position is shown as 1,5,7
If the data in the table column is ascending by default and the index is of desc type, the user_ind_columns generates
a sequential column name for the column for the index to use since it is rearranging data in index.
For asc order, column names remain the same

To set number of fields in data dictionary view


COLUMN INDEX_NAME FORMAT A10;

We can join data from user_indexes a d user_ind_columns views –

Select index_name, index_type, table_name, column_name


From user_indexes join user_ind_columns
Using (Table_name, index_name)
Where table_name = 'emp';
__________________________________
__________________________________

PSEUDO COLUMNS –

1 Rownum
2 Rowid

Rownum and rowid are not present in table.

ROWNUM –

Rownum is not a physical column


Rownum maintains a serial no for the records in the table
The records can be duplicate but rownum is unique

Select rownum, sal from emp;

O/P ROWNUM SAL

1 1000
2 2000
3 500

Can we select data from table on the basis of rownum?

YES, BUT WE CAN ONLY SELECT THE FIRST n RECORDS. WE CAN USE < AND <= OPERATORS WITH ROWNUM.

> Or > = Or = Operator cant be used with rownum

Select ename, sal from emp


Where rownum <6; ✓

Select ename, sal from emp


Where rownum <=6; ✓

Select ename, sal from emp


Where rownum =6;

How to select record number 5 to 8?


We can use set Operator for this.

Select ename, sal from emp


Where rownum < 9
MINUS
Select ename, sal from emp
Where rownum <5; ✓

ROWID –

Contains physical address of each record

Select rowid, ename from emp;

Rowid Ename
AAADsiAABAAAKkSAAA SMITH
AAADsiAABAAAKkSAAA ALLEN
AAADsiAABAAAKkSAAC WARD

First 3 Characters are file id, i.e. table id


4 to 15 i.e. 12 Characters form a HEXADECIMAL number which refers to data block
16 to 18
Last 3 Characters are record number

All records of a table are stored in 1 data block.


Size of data block is 64 mb.
It can store thousands of records

Each record has a unique address in database


__________________________________

Das könnte Ihnen auch gefallen