Beruflich Dokumente
Kultur Dokumente
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
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
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-
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) )
Multiple column-
Alter table tablename
Modify (Colummname1 datatype(size).
Colummname2 datatype (size) )
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;
From 10g onwards... Dropped table is in recyclebin.... Before that cudnt be recovered ...);
_________________________________________
COMMENT
Comment on table-
Comment on table tablename is 'Text';
Types of DML-
All records-
Delete from tablename
Or
Delete tablename
Particular records-
Delete from tablename
Where C1 = V1
Or
Delete tablename
Where C1 = V1
__________________________________________
MERGE
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 ×
If we use inline view/ query as source table, the table, i.e the query must be given an alias name.
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.
TRUNCATE is executed using a table lock and whole table is locked for remove all records.
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.
DELETE
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.
The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row.
DROP
All the tables' rows, indexes and privileges will also be removed.
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)
PRIVILEGE LIST:
SELECT INSERT UPDATE DELETE ALTER
CONNECT RESOURCES ALL
Revoke role-
Revoke Connect, Resource from username
Transitive-
Revoke select on tablename from C ×
A cant execute this as privilege to C was given by B, not A
___________________________________________
SET ROLE
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.
With password-
Create role rolename identified by password;
Without password-
Create role rolename not identified
To remove password-
Alter role rolename not identified
Commit
Rollback
Savepoint
Set transaction
___________________________________________
COMMIT
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
Insert
Insert
Rollback explicit
Inset
Update
Rollback explicit
Insert
Update
Alt + F4 implicit
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
only read
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
9i onwards-
Timestamp
Timestamp with timezone t
Timestamp with local timezone
Interval year to month
Interval day to second
___________________________________
CHAR(size)
For char(5)
If entry is abc rest 2 empty spaces are added
on right hand side since CHARACTER DATA IS LEFT ALIGNED
Precision from 1 to 38
Scale from -84 to + 126
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
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 to_char
(sysdate, 'BC DD-MON-YYYY HH:MI:SS AM) from dual;
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
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.
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
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)
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
Default and not null constraints can be defined on LOB data types but not check, unique, foreign or primary key
constraint
Error thrown is column of data type LOB cannot be unique or primary key
_____________________________
_____________________________
B29 VIDEO
SQL DATA TYPES PART 6
BFILE
into tablename
Values
(1 , BFILENAME('DIR1' , ‘ABC.TXT'));
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.
Number character and blob data types are not accepted in BFILE
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
NAME
Abhi
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
USED WITH-
SELECT UPDATE DELETE
MERGE (In update and delete part not insert)
INSERT (WHEN COPYING FROM OTHER TABLE)
GROUP BY
Select C1 , C2 from T1
Group by C1;
In 9i and 11g–
Data displayed in ascending order
In 10g –
Data displayed in descending order
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; ✓
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
Single column –
Select * from T1
Order by C1 asc;
Multiple column –
Select * from T1
Order by C1 desc, C2 asc, C3 desc;
Select * from T1
Order by (C1 , C2) desc; ×
Using column no –
This 1 is the position in current select statement not the whole table so 1 refers to C2 not C1
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 –
Execution –
TYPES –
Single row functions –
act on one record and produce one result per row
Can be nested upto any level
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
O/P 13
____________________________________
B20 VIDEO
SQL FUNCTIONS PART 2
O/P I am a man
O/P OracleServerAbcd
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
O/P ++++++++++++++Oracle
Oracle is 6 Characters long.. 20 – 6 = 14 so 14 + added to left size
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
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
O/P racle
O/P Oracle
O/P cle
O/P Oracle
O/P racle
O/P ooooracle
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
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 ✓
O/P RACLESERVER
O/P RACLESERVER
To trim SPACE –
Select trim (' ' from ' ORACLE SERVER ' )FROM DUAL;
OR
Select trim ( ' ORACLE SERVER ') from dual;
Select trim (leading ' ' from ' ORACLE SERVER ') as trim_op from dual;
Select trim (trailing ' ' from ' ORACLE SERVER ') as trim_op from dual;
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
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
9 SUBSTR
Used to take part of a string
3 parameters
Input
Starting position – can be + , - or 0
No of characters
O/P ORAC
O/P CLE
O/P ORAC
0 is same as 1 for starting position
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
O/P 1
O/P 6
O/P 9
O/P 6
O/P 0
O/P 0
O/P 12 searching from right end but POSITION COUNTED FROM LEFT ALWAYS
O/P 9
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
2 CEIL FUNCTION
Immediate next highest integer value for a decimal no
Same integer given for integer value
3 FLOOR FUNCTION
Immediate lower integer for decimal no
Same integer for integer no
4 POWER FUNCTION
ACCEPTS 2 PARAMETERS
FIRST VALUE RAISED TO POWER OF SECOND VALUE
O/P 8 -8 1 2.64617800….
O/P 1 1 1 0
5 SIGN FUNCTION
POSITIVE VALUE GIVES +1
NEGATIVE VALUE GIVES -1
ZERO GIVES ZERO
DECIMAL NO ALSO ACCEPTED
O/P 1 -1 0
6 MOD FUNCTION
Gives remainder
O/P 0 1 0 0 5 0
7 SQRT FUNCTION
GIVES SQUARE ROOT
I/P should be 0 or greater than 0
8 LOG FUNCTION
2 PARAMETERS
FINDS LOG OF 2nd INPUT TO 1st INPUT AS BASE
O/P 1 2
9 EXP
Finds e to the power x
X is the I/P parameter
10 LN
NATURAL LOG
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;
Select trunc(123.45 , -0) , trunc(123.45 , -1) , trunc (123.45, -2) , trunc(123.45 , -3), trunc(123.45 , -4) from dual;
12 ROUND
TAKES 2 PERIMETERS
2ND IS OPTIONAL
SAME FUNCTIONING AS TRUNC BUT DATA IS ROUNDED OFF AS WELL
1 SIN
O/P -0.9880316
2 ASIN
SIN INVERSE FUNCTION
Argument range
Sine -1 to 1
Cose -1 to 1
Tan -infinity to + infinity
3 SINH
Sine hyperbolic fn
O/P 5343237290762.2310
____________________________________
STATISTICAL FUNCTIONS
1 STDDEV
O/P 0
2 VARIANCE
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
950
1100
1250
1250
1300
1500
1600
2450
2500
2850
2975
3000
3000
5000
950
1100
1250
1300
1500
1600
2450
2500
2850
2975
3000
5000
12 rows selected
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
1 SYSDATE
Date from server system
Select sysdate from dual;
O/P 08-OCT-13
2 CURRENT_DATE
Date from client system
O/P 08-OCT-13
3 LAST_DAY
It gives last day of month
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
O/P 10-OCT-13
O/P 10-OCT-13
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
08-OCT-2013 07:34:04 PM
6 Months_between
Takes 2 PARAMETERS
Operation is first parameter – second parameter
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
O/P 01-JAN-2013
O/P 01-JAN-2013
O/P 01-JAN-2013
O/P 01-OCT-2013
O/P 08-OCT-2013
O/P 08-OCT-2013
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
O/P 01-JAN-2014
9 TO_CHAR
Convert date to century day month year hour minute second am/pm form
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
O/P
TWENTY THIRTEEN
Twenty thirteen
O/P
Twenty Thirteen
O/P
3
O/P
13
O/P
013
O/P
8
O/P
280
O/P
4
________________________________
CONVERSION FUNCTIONS
Char to no example
123 ✓
01-mar-13 ×
1@3 ×
123 ×
010212 ✓
01-mar-14 ✓
20150102 ✓
01mar13 ✓
__________________________________
__________________________________
B24 VIDEO
SQL FUNCTIONS PART 6
10 EXTRACT FUNCTION
We can EXTRACT FROM SYSDATE
DAY MONTH YEAR
O/P 08-OCT-2013
O/P 10
O/P
01-JAN-12 10.38.56.111000000 AM
O/P
02-JAN-12
O/P
01-JAN-13 10.38.56.111000000 AM
O/P
01-FEB-12 10.38.56.111000000 AM
O/P
01-JAN-13 10.38.56.222000000 AM
_________________________________
_________________________________
B25 SQL CONSTRAINTS PART 1
Types of 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
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
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
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); ✓
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
EXAMPLE OF FOREIGN KEY REFERENCING A PRIMARY KEY COLUMN IN ITS OWN TABLE AND A COLUMN IN ANOTHER
TABLE, AT COLUMN LEVEL
_________________________________
B27 SQL CONSTRAINTS PART 3
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
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.
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.
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 –
BINARY Operator –
Types-
Arithmetic Operator P1
Concatenation Operator P2
Relational/Comparison Operator P3
Single value/row
Multiple value/row
Other relational Operator P3
Logical Operator P4
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 –
RELATIONAL OPERATORS –
= Equal to
!= , <> , ^=, (~=) Not equal to (only Pl/Sql)
> Greater than
< Lesser than
>= Greater than or equal to
<= Lesser than or equal to
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
LOGICAL OPERATORS –
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 –
Binary Operators –
Arithmetic Operators –
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
CONCATENATION OPERATORS –
RELATIONAL OPERATORS –
SINGLE ROW –
Select * fr tablename
Where C1 = 1000;
Select * fr tablename
Where C1 != 1000;
__________________________________
__________________________________
B33 VIDEO
SQL OPERATORS PART 2
MULTIPLE ROW –
Or
Or
Or
Or
Or
Or
Or
Or
Or
Or
Or
Select * from emp
Where C1 <> 100 or C1 <> 200 or C1 <> 300;
_________________
Or
If inner query is true, nor just matching records but all records will be displayed.
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
LOGICAL OPERATORS
OR
AND
NOT
UNION
Or
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
Or
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
Or
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
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
_______________________________
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
Or
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
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
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}
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
Ex
JOIN CONDITION?
TO LINK COMMON COLUMNS
First we should write where condition and then join condition. This increases the performance of the query by
limiting or filtering data.
Example –
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
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 –
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 DISPLAYS ALL DATA FROM ONE TABLE AND ONLY MATCHING DATA FROM THE SECOND TABLE.
JOIN CONDITION IS SPECIFIED USING ON CLAUSE
Full outer join is a combination of data from left outer join + right outer join - inner join
Syntax –
Examples –
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
USING JOIN –
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 –
Subqueries can be used in any DML statement like select, insert, update and merge
Types of subqueries –
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
THIS SUBQUERY RETURNS MULTIPLE ROWS BUT ONLY ALL THE ROWS BELONG TO ONE COLUMN ONLY
O/P Error single row subquery returns more than one row
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');
Select * from emp where sal, comm = (Select sal, comm from emp where ename = 'WARD');
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
CORRELATED SUBQUERY
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.
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.
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 –
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.
Or
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.
Or
Find the account name, account type, account no & customer no of all the male customers
__________________________________
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 –
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
Types of views –
1 Simple/Updatable view
2 Complex/Composite view
3 Force view
4 Read only view
5 With check option view
Syntax –
SYNTAX –
By default, developers do not have privilege to create views. DB Admin has to grant Access for the same.
CONN SCOTT;
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
RENAME A VIEW – ✓
DROP A VIEW – ✓
TRUNCATE A VIEW – ×
COMMENT ON VIEW – ✓
CREATE A VIEW WITH LIMITED DATA FROM THE TABLE TO HIDE SENSITIVE DATA–
OR
The select clause can bring data from table, view, global temporary table, external table, synonym, materialized
view, etc.
DESC 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;
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 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
Ex –
Create view v_emp
As select * from emp; ✓
Or
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
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.
DEPTNO TOTAL_SAL
40 78000
30 5000
10 7450
Since the data is deleted from both the tables operation is successful
O/P all matching rows get deleted from emp table but no data is deleted from dept table
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
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
Desc vf_emp;
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.
If we delete the table, the status of the view in user_objects Data dictionary becomes invalid automatically
O/P cannot delete from view without exactly one key-preserved table
__________________________________
COMPLEX VIEW –
Create view vc_emp as
Select * from emp where deptno = 20;
So long as the with check option is not violated, the update be successful
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 –
Conn U1/U1;
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.
INSERT, DELETE and UPDATE are directly possible on a simle We cannot apply INSERT, DELETE and UPDATE on
view. complex view directly.
__________________________________
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.
Conn system;
Conn username;
__________________________________
__________________________________
INDEX
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)
Created on entire column and on all records of that column. There is no rearrangement of data
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
Ex –
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
O/P Error clustered tables cannot be used before the cluster Index is built
O/P Error clustered tables cannot be used before the cluster Index is built
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
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
PSEUDO COLUMNS –
1 Rownum
2 Rowid
ROWNUM –
1 1000
2 2000
3 500
YES, BUT WE CAN ONLY SELECT THE FIRST n RECORDS. WE CAN USE < AND <= OPERATORS WITH ROWNUM.
ROWID –
Rowid Ename
AAADsiAABAAAKkSAAA SMITH
AAADsiAABAAAKkSAAA ALLEN
AAADsiAABAAAKkSAAC WARD