216
TABLE A Table is a database object. A Table is a logical representation of data present in the database. A Table is a unit of storage that holds data in the form of Rows & columns.

Oracle naveen Sql

  • Upload
    naveen

  • View
    2.211

  • Download
    0

Embed Size (px)

DESCRIPTION

this is sufficientt to study SQL their are all syntax and i may cover all selected area in dbms

Citation preview

Page 1: Oracle naveen   Sql

TABLE A Table is a database

object. A Table is a logical

representation of data present in the database.

A Table is a unit of storage that holds data in the form of Rows & columns.

Page 2: Oracle naveen   Sql

Data Definition Language (DDL)

Data Definition Language and the commands are used to create an object (eg. Table), alter the structure of the object and also to drop the object created.

The DDL commands are

Create, Alter, Truncate, Drop, Rename

Page 3: Oracle naveen   Sql

CREATE Command

Command to create a table.Syntax: create table <table name>

(column name1 datatype, column name 2 datatype, column name 3 datatype,….);

Message: table created

Page 4: Oracle naveen   Sql

CREATE Command Norms1. The first letter of the table

name should be an alphabet.

2. Oracle reserved words cannot be used for naming objects.

3. Length of a table name should not exceed 30 characters.

4. Two different tables cannot have the same name.

5. Blank spaces or single quotes cannot be used with the table names. Numerals & underscore can be used.

Page 5: Oracle naveen   Sql

ALTER Command

Command to Alter a table.Syntax: alter table <table name>

modify column name datatype;

alter table <table name> add column name datatype;

Message: table altered

Page 6: Oracle naveen   Sql

ALTER Command

Alter command can be used to

1. Add a new column to the table.

2. To change the datatype or the width of the datatype of column(s).

3. To include or drop constraints.

Page 7: Oracle naveen   Sql

ALTER Command Norms

1. The length of an existing column datatype can be reduced only if the table is empty or without records.

2. The length of an existing column datatype can be increased even if the table has records.

Page 8: Oracle naveen   Sql

TRUNCATE CommandCommand to

Truncate a table.Syntax: truncate table <table

name>;Message: table

truncated

Page 9: Oracle naveen   Sql

TRUNCATE Command

Truncate command delete’s all the rows/records from the specified table.

Adding ‘reuse storage’ to the truncate command delete’s all the records but reclaims the space used for the storage of the records.

Ex: truncate table <table name> reuse storage;

Page 10: Oracle naveen   Sql

DROP Command

Command to drop the table.

Syntax: Drop table <table

name>;Message: table

dropped

Page 11: Oracle naveen   Sql

DESC Command

Command to view the structure of the table.

Syntax: desc <table name>

Table structure will be displayed

Page 12: Oracle naveen   Sql

RENAME CommandCommand to Rename

the name of the table.Syntax: rename <table

name> to <New table name>;

Table renamed.

Page 13: Oracle naveen   Sql

Data Manipulation Language (DML)

Data Manipulation Language and the commands are used to Query and manipulate existing objects (Ex: Tables).

The DML commands are

Insert, Select, Update, Delete

Page 14: Oracle naveen   Sql

INSERT Command

Values while using the insert command must be seperated by commas.

Values of data type char,varchar2, raw, long & date must be enclosed in single quotes.

The values must be in the same order as they are defined in the table.

Page 15: Oracle naveen   Sql

INSERT Command

To populate the table with rows/records.

Syntax:Insert into <table name>

values (a list of data values);

Message: 1 row created

Page 16: Oracle naveen   Sql

INSERT Command

To insert multiple records using a single insert command.

Syntax:

Insert into <table name> values (& colu name 1, &colu name 2, &col name 3);

Oracle prompts for values

Enter the value for <colu name 1>:

Enter the value for <colu name 2>:

Enter the value for <colu name 3>:

Page 17: Oracle naveen   Sql

INSERT Command

To skip fields in a record while inserting a record.

The necessary fields should be explicitly mentioned.

Syntax:

Insert into <table name> (<Col name 1> ,<Col name 2>,…) values (list of values);

Message: 1 row created.

Page 18: Oracle naveen   Sql

INSERT Command

Another way of skipping one or more fields is to enter NULL value against the column name.

Syntax:Insert into <table name>

values (<value1>, <value2>, <value3>, Null, <value5>, Null, <value7>);

Message: 1 row created.

Page 19: Oracle naveen   Sql

SELECT Command

Used for Querying the Databade

Syntax:Select <colu name1>, <colu

name2> ……. From <table name1>, <table name2>…;

Output will be a set of rows & columns of the specified table(s)

Page 20: Oracle naveen   Sql

SELECT Command

We can display either all the columns in a table or only specific columns from the table.

The order of the column names in the select command specifies the order in which they should be displayed.

Page 21: Oracle naveen   Sql

SELECT Command with DISTINCT clause

Distinct clause in the select command is included to avoid selection of duplicate rows.

Syntax: Select distinct(<colu name>) from <table name>;

Output will be the specified column with its values.

Page 22: Oracle naveen   Sql

SELECT Command with WHERE & ORDER BY clause Where clause is included in the select command to select specific rows from a table. Rows which satisfy the where condition will only be retrieved.

Order by clause is used to arrange the displayed rows as per a pre defined order or in the ascending or descending order. Order by clause can also be used to arrange multiple columns.

Page 23: Oracle naveen   Sql

SELECT Command with WHERE & ORDER BY clauseSyntax:

Select <colu name>, <colu name>,… from <table name>,<table name>… [Where <condition(s)>]

[Order by <colu name1>, <colu name2>,….. asc/desc] ;

Page 24: Oracle naveen   Sql

UPDATE Command

Update command is used to reflect changes to the existing rows/records in a table.

A single or more than one column can be updated.

Specific rows can be updated based on conditions.

Page 25: Oracle naveen   Sql

UPDATE Command

Syntax:Update <table name> set

<column name> = <value>,…. Where <condition>;

Output:1 row updated

Page 26: Oracle naveen   Sql

DELETE Command

Syntax:Delete from <table

name> where <condition>;

Output:1 row deleted

Page 27: Oracle naveen   Sql

DELETE Command

One or more rows can be deleted using the delete command.

To delete specific rows the where clause is used with the delete command.

Where clause can also include a query.

The delete command can be used to delete all rows of a table while the structure remains unaltered.

Page 28: Oracle naveen   Sql

Transaction Control Language (TCL)

All changes made to a database can be referred to as transactions.

Transaction changes can be made permanent to a database by explicitly using the Transaction control commands.

When a DDL statement is used the transactions are implicitly made permanent to a database.

The transaction control commands are Commit, Savepoint & Rollback.

Page 29: Oracle naveen   Sql

SAVEPOINT COMMANDSyntax:

Savepoint <savepoint name>;

Savepoints are used to divide a very lengthy transsaction to smaller ones.

They are used to identify to a point in the transaction to which we can later rollback. Savepoint is used in conjuction with rollback.

Page 30: Oracle naveen   Sql

ROLLBACK COMMANDSyntax: Rollback; or

Rollback to Savepoint <SP name>;

Rollback command is used to undo the work in the current transaction.

Rollback to a particular savepoint to undo the transactions after the savepoint or roll back the entire transactions to undo the changes done.

Page 31: Oracle naveen   Sql

COMMIT COMMAND

Syntax: Commit; Commit command is used

to end a transaction. Only with the commit

command the transactions can be made permanent to the database.

This command erases all savepoint’s in the transactions.

Page 32: Oracle naveen   Sql

Data Control Language (DCL)

Provides users with privilege command.

The owner of the tables has sole command on them and can allow other users access to the tables or other objects.

Privileges once granted can also be withdrawn by the owner.

The data control commands are Grant & Revoke.

Page 33: Oracle naveen   Sql

GRANT COMMAND

Syntax: grant <privileges> on <object name> to <username>;

To grant privileges on particular columns:

Syntax: Grant <privileges>(col name1,col name2,..) on <table name> to <username>;

Owner A – grant - B & B - C. Then A has to follow the grant syntax allowing B to grant to C.

Syntax:Grant <privileges> on <object name> to <username> with grant option;

ALL to grant all the privileges .

Page 34: Oracle naveen   Sql

REVOKE COMMAND

Syntax: revoke <privileges> on <object name> from <username>;

To withdraw privileges from the user.

Page 35: Oracle naveen   Sql

Different Select StatementsCreating tables using select statements:

Create table emp1 as select * from emp; Or

create table emp2(id, name) as select empno,ename from emp;

Select Command to insert records:Insert into emp3 (select ename,job from

emp);

Defining column alias name using select statement:

Select empno id from emp; OrSelect empno, ename, sal*1.10 as

revised_sal from emp where sal>2000;

Page 36: Oracle naveen   Sql

OPERATORS IN SQL

Operators supported by SQL

o ARITHMETIC OPERATORS

o COMPARISON OPERATORS

o LOGICAL OPERATORS

Page 37: Oracle naveen   Sql

ARITHMETIC OPERATORS

They are included in SQL commands to perform calculations on number based values.

ARITHMETIC Operators are + (Addition) - (Subtraction) *(Multiplication) / (Division)

Precedence of Arithmetic operators

* / +-

Page 38: Oracle naveen   Sql

COMPARISON OPERATORSThey are used in conditions to compare one expression with another.

Comparison operators are = != < >

<= >=Between (to check between any

two values)In (to match with any of the

values in list)Like (to match a character

pattern)Is null (to check if it is null)Not between, not in, not

like, is not null

Page 39: Oracle naveen   Sql

COMPARISON OPERATORS

Using IN operator if we search for character values then the column name must match exactly with the values in the list.

Knowing the character value is not required for using the LIKE operator.

LIKE can use characters of % (to match zero or more

characters) _ (matches exactly one

character)

Page 40: Oracle naveen   Sql

LOGICAL OPERATORS

Used to combine the results of two conditions to produce a single result.

The logical operators are:

ANDNOTOR

Page 41: Oracle naveen   Sql

OPERATOR PRECEDENCE

1 - Arithmetic operators2 - Comparison operators3 - NOT Logical operator4 - AND Logical

Operator5 - OR Logical OperatorThe order of precedence

can be altered using parenthesis

Page 42: Oracle naveen   Sql

SQL * PLUS FUNCTIONS

Functions to perform operations using the DML commands.

A function takes one or more arguments and returns a value.

Functions can be classified into SINGLE ROW functions & GROUP functions.

Page 43: Oracle naveen   Sql

SINGLE ROW FUNCTIONS

DATE FUNCTIONS NUMERIC FUNCTIONS CHARACTER FUNCTIONS CONVERSION

FUNCTIONS MISCELLANEOUS

FUNCTIONS

DUAL: System table created by ORACLE with 1 column of varchar2 datatype & 1 row with value ‘x’.

Page 44: Oracle naveen   Sql

DATE FUNCTIONS

1. ADD_MONTHSReturns a date after adding a

specified date with the specified number of months.

Format: add_months (D,N)D - date N – number of monthsExample: select hiredate,

add_months(hiredate,4) from emp;

Page 45: Oracle naveen   Sql

DATE FUNCTIONS

2. LAST_DAYReturns the date

corresponding to the last day of the month.

Format: last_day (D)D - date Example: select sysdate,

last_day(sysdate) from dual;

Page 46: Oracle naveen   Sql

DATE FUNCTIONS

3. MONTHS_BETWEENTo find out the number of months

between two given dates.Format: months_between (D1,D2)

D1 – date1 D2 – date2

Output: numberIf D1 later than D2 – result – positiveIf D1 earlier than D2 – result -

negativeIf D1 & D2 - same date – result –

integer (result based on the 31 day month & time components)

Page 47: Oracle naveen   Sql

DATE FUNCTIONS

4. ROUND

The function returns the date which is rounded to the unit specified by the format model.

Format: round (date,‘format’)

Format options: year, month, day

Specifying the format is optional. If the format is not specified the date will be rounded to the nearest day.

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

Page 48: Oracle naveen   Sql

DATE FUNCTIONS

5. NEXT_DAYReturns the next date

corresponding to the day specified.

Format: next_day (D, ‘day’)D – date day – any week day

Example: Select next_day(sysdate,

‘Monday’) from dual;

Page 49: Oracle naveen   Sql

DATE FUNCTIONS

6. TRUNCATETruncate function returns the date

with the time portion of the day truncated to the unit specified by format model.

Format: trunc (date,‘format’)Format options: year, month, daySpecifying the format is optional. If

the format is not specified the date will be rounded to the nearest day.

Ex: Select sysdate, trunc(sysdate, ‘year’) from dual;

Page 50: Oracle naveen   Sql

DATE FUNCTIONS

7. GREATESTThis function returns the

latest date present in the argument.

Format: greatest (date1, date2, . . . )

Example:Select hiredate, sysdate,

greatest (hiredate, sysdate) from emp;

Page 51: Oracle naveen   Sql

DATE FUNCTIONS

8. NEW_TIMEThis function displays the time

& the date of a date column or literal date in other time zones.

Format: new_time (date,‘this’, ‘other’)

This – 3 letter abbreviation of the current time zone, Other – 3 letter abbreviation of the zone in which the date is wanted.

Ex: Select new_time(sysdate, ‘est’, ‘yst’) from dual;

Page 52: Oracle naveen   Sql

CHARACTER FUNCTIONS

Character Functions accept input & return either character or number values.

1. InitcapFormat : Initcap (‘char’)Example : select initcap(‘orbit’) from

dual;Output : Orbit

2. Lower Format : Lower (‘char’)Example : select lower

(‘STUDENTS’) from dual;Output : students

Page 53: Oracle naveen   Sql

CHARACTER FUNCTIONS

3. Upper

Format : Upper (‘char’)

Example : select upper (‘students’) from dual;

Output : STUDENTS

4. Ltrim

Format : Ltrim (‘char’, ‘set’)

Example : select ltrim (‘abcorbit’, ‘abc’) from dual;

Output : orbit

Page 54: Oracle naveen   Sql

CHARACTER FUNCTIONS5. Rtrim

Format : Rtrim (‘char’, ‘set’)Example : select rtrim (‘abcorbit’,

‘orbit’) from dual;Output : abc

6. Translate Format : Translate (‘char’, ‘from’,

‘to’)Example : select translate (‘mister’,

‘m’ , ‘s’) from dual;Output : sister

Page 55: Oracle naveen   Sql

CHARACTER FUNCTIONS7. Replace

Format : Replace (‘char’, ‘search string’, ‘replace string’)

Example : select replace (‘boke is bola’, ‘b’ , ‘c’) from dual;

Output : coke is cola

8. Substr Format : Substr (‘char’, m, n)Example : select substr (‘fraction’, 3 ,

6) from dual;Output : action

Page 56: Oracle naveen   Sql

CHARACTER FUNCTIONS

CHR Function : returns the character equivalent of the number that is specified.

Format : chr(number)Example : select chr (77)

from dual;Output : M

Page 57: Oracle naveen   Sql

CHARACTER FUNCTIONS

LPAD Function : Pads the value to the left of the given string

Format: lpad (‘String’, N, ‘S’)

String : Character string which has to be displayed with the left padding

N = number which indicates the total length of the return value

S = string with which the left padding has to be done

Example : select lpad (‘Oracle’, 10, ‘*’) from dual;

Output : ****Oracle

Page 58: Oracle naveen   Sql

CHARACTER FUNCTIONS

RPAD Function : Pads the value to the right of the given string

Format: rpad (‘String’, N, ‘S’)

String : Character string which has to be displayed with the left padding

N = number which indicates the total length of the return value

S = string with which the left padding has to be done

Example : select rpad (‘Oracle’, 10, ‘*’) from dual;

Output : Oracle ****

Page 59: Oracle naveen   Sql

CHARACTER FUNCTIONS

LENGTH Function : Returns the length of a string

Format: length (‘String’)Example : select

length(‘microsoft’) from dual;

Output : 9

Page 60: Oracle naveen   Sql

CHARACTER FUNCTIONS

DECODE Function : Value by value replacement.

Format: decode (value, if1, then1, if2, then2,….) from table_name;

Example : select empno, ename, decode (ename, ‘SMITH’, ‘MYTH’) from emp;

SOUNDEX Function: Compares words that are spelled different but sound alike.

Example : select ename from emp where soundex (ename) = soundex (‘MILER’);

Page 61: Oracle naveen   Sql

CONCATENATION OPERATORUsed to merge two or more

strings, or a string and a data value together.

Example : select (‘The date on which’||ename|| ‘joined this org is’ ||hiredate) join_date from emp;

Page 62: Oracle naveen   Sql

NUMERIC FUNCTIONS

Numeric functions accepts numeric input and returns numeric values a output

1. ABS Function : Ex: select abs(-10) from dual;Output : 102. CEIL Function: Format : ceil(n)Ex: select ceil(11.678) from dual;Output : 12

Page 63: Oracle naveen   Sql

NUMERIC FUNCTIONS

3. COS Function:

Format : cos(n)

Ex: select cos(116) from dual;

Output : integer

4. COSH Function:

Format : cosh(n)

Ex: select cosh(0) from dual;

Output : 1

Page 64: Oracle naveen   Sql

NUMERIC FUNCTIONS

5. EXP Function:

Format : exp(n)

Ex: select exp(2) from dual;

Output : integer

6. FLOOR Function:

Format : floor(n)

Ex: select floor(10.2) from dual;

Output : 10

Page 65: Oracle naveen   Sql

NUMERIC FUNCTIONS

7. POWER Function:

Format : power(m,n)

Ex: select power(5,2) from dual;

Output : 25

8. MOD Function:

Format : mod(m,n)

Ex: select mod(10,3) from dual;

Output : 1

Page 66: Oracle naveen   Sql

NUMERIC FUNCTIONS

9. ROUND Function:

Format : Round(m,n)

Ex: select round(100.256,2) from dual;

Output : 100.26

10. TRUNC Function:

Format : trunc(m,n)

Ex: select trunc(100.256,2) from dual;

Output : 100.25

Page 67: Oracle naveen   Sql

NUMERIC FUNCTIONS

11. SQRT Function:

Format : sqrt(n)

Ex: select sqrt(25) from dual;

Output : 5

12. LN Function: returns logarithmic value

Format : ln(n)

Ex: select ln(2) from dual;

Output : logarithmic value of 2

Page 68: Oracle naveen   Sql

NUMERIC FUNCTIONS

13. MOD Function: gives the remainder of value divided by another

Format : mod(m,n)

Ex: select mod(25,6) from dual;

Output : 1

14. SIGN Function: returns sign of a value without its magnitude

Format : sign(n)

Ex: select sign(-32) from dual; Output : -1

Page 69: Oracle naveen   Sql

CONVERSION FUNCTIONSConvert a value from one data type to another. Conversion functions are

A. To_char( )B. To_date ( )C. To_number ( )To_char ( ) function : Converts

date to a value of varchar2 datatype in the form specified by date format (fmt). If fmt is neglected then it converts date to varchar2 in the default format.

Page 70: Oracle naveen   Sql

CONVERSION FUNCTIONSFormat : To_char(date, ‘format’)

Ex: select to_char(sysdate, ‘ddth “of” fmmonth yyyy’) from dual;

Fill mode (fm) – format mask is used to avoid blank padding of characters and zero padding to numeric.

Page 71: Oracle naveen   Sql

CONVERSION FUNCTIONSTo_date ( ) function : Converts char or varchar2 datatype to date datatype in the form specified by character format (fmt).

Format : To_date(char, ‘format’)

Ex: select to_date(‘august 22 2004’ , ‘month-dd-yyyy’) from dual;

Select round(to_date( ‘27-jan-04’, ‘year’) from dual;

Page 72: Oracle naveen   Sql

CONVERSION FUNCTIONS

To_number ( ) function : Converts a string containing number into a number datatype on which arithmetic operators can be performed.

Format : To_number(char, ‘format’)

Ex: select to_number(‘100’) from dual;

Page 73: Oracle naveen   Sql

MISCELLANEOUS FUNCTIONSUID USER NVL

VSIZE

UID Function : this function returns the integer corresponding to the user currently logged in.

Ex: Select uid from dual;

USER Function : this function returns the users login name, which is in varchar2 datatype.

Ex: Select user from dual;

Page 74: Oracle naveen   Sql

MISCELLANEOUS FUNCTIONSNVL Function : is used in cases

where the null value has to be considered as zero.

Format : nvl (expression1,expression2)

o If exp1 is null, nvl will return exp2.

o If exp1 is not null, nvl will return exp1.

o If exp1 & exp2 are of different datatypes then oracle converts the datatype of exp2 to exp1 and then compares.

Ex: select sal,comm,nvl(comm,1000) from emp;

Page 75: Oracle naveen   Sql

MISCELLANEOUS FUNCTIONSVSIZE Function : it returns the

number of bytes in the expression. If the expression is null, it returns null.

Ex: select vsize(‘students’) from dual;

Page 76: Oracle naveen   Sql

GROUP FUNCTIONS

Group Function returns a result based on a group of rows.

1. AVG Function : will return the average value of column specified in the argument of the column.

Ex: Select avg(sal) from emp where deptno = 10;

2. SUM Function : used to obtain the sum of a range of values.

Ex: Select sum(sal) from emp;

Page 77: Oracle naveen   Sql

GROUP FUNCTIONS

3. MIN Function : will return the least of all values of the column present in the argument.

Ex: Select min(sal) from emp;

4. MAX Function : will return the maximum of all values of the column present in the argument.

Ex: Select max(sal) from emp;

Page 78: Oracle naveen   Sql

GROUP FUNCTIONS

5. COUNT Functions : used in order to count the number of rows.

A. Count(*) – counts all rows inclusive of duplicates & nulls.

Ex: Select count(*) from emp;

B. Count (col_name) – it counts the number of values present in the column without including the nulls.

Ex: Select count(comm) from emp;

Page 79: Oracle naveen   Sql

GROUP FUNCTIONS

C. Count (distinct col_name) – it counts the number of values present in the column without including the nulls but eliminates duplicate values without counting

Ex: Select count(distinct deptno) from emp;

Page 80: Oracle naveen   Sql

GROUP BY CLAUSE

If an SQL command consists of a ‘where’ clause and a ‘group by’ clause then group by must follow the where clause

Ex: Select max(sal) from emp group by deptno;

Page 81: Oracle naveen   Sql

HAVING CLAUSE

Having clause is used to specify certain conditions on rows, retrieved by using the group by clause. Having clause always follows the group by clause.

Ex: Select max(sal) from emp group by deptno having deptno != 10 ;

Arithmetic operators can also be performed in a group function.

Page 82: Oracle naveen   Sql

ADDITIONAL FUNCTIONS

STDDEV Function : gives the standard deviation of a norm of values.

Ex: select stddev(sal) from emp;

VARIANCE Function : gives the variance of a norm of values.

Ex: select variance(sal) from emp;

Page 83: Oracle naveen   Sql

SET OPERATORS

Set operators combine the result of two queries into a single one. Joining queries to retrieve rows.

o UNION o UNION ALL o INTERSECTo MINUS

Page 84: Oracle naveen   Sql

SET OPERATORSThe columns in the select statements

joined using the set operators should adhere to the rules:

1. The queries which are related by a set operator should have the same number of columns and the corresponding columns must be of the same datatype.

2. Such a query should not contain any column of long datatype.

3. The label under which the rows are displayed are those from the first select statement.

4. It is not required that the column names specified in the select statements be the same but the datatype must necessarily match.

Page 85: Oracle naveen   Sql

SET OPERATORS

UNIONo Union operator returns distinct

rows selected by both the queries.

o Neglects duplicate rows.

Ex: Select deptno from emp union select deptno from dept;

Select dname from dept union select ename from emp;

Page 86: Oracle naveen   Sql

SET OPERATORS

UNION ALLo Union operator select all rows selected

by either of the queries including the duplicates.

o Does not neglect duplicate rows.Ex: Select deptno from emp union all

select deptno from dept;Select dname from dept union

all select ename from emp; If an order by clause needs to be used

it should follow the last select statement and the order by can be a column or an integer(when column name are different in the select statements)

Page 87: Oracle naveen   Sql

SET OPERATORS

INTERSECTo Intersect operator returns only

rows that are common to both the queries.

Ex: Select deptno from emp intersect select deptno from dept;

Select dname from dept intersect select ename from emp;

Page 88: Oracle naveen   Sql

SET OPERATORS

MINUSo Minus operator returns all

distinct rows selected by the first query and not by the second query.

Ex: Select deptno from emp minus select deptno from dept;

Select dname from dept minus select ename from emp;

Page 89: Oracle naveen   Sql

JOINS

o Joins are used to combine the data spread across tables.

o Joins are performed by where clause.

o The table names to which the respective column belong should be specified in the join condition in the where clause.

o If a join involves more than 2 tables then the first 2 tables are joined based on the condition and then compares the result with the next table and so on.

Page 90: Oracle naveen   Sql

JOINSSIMPLE JOINRetrieves rows from two tables

having a common column.Simple Joins are classified in

EQUI Join & NON – EQUI Join.

EQUI JOIN:Combines the rows that have

equivalent values for the specified columns. Uses ( = ) operator in the condition.

Ex: Select * from emp,dept where emp.deptno = dept.deptno;

Page 91: Oracle naveen   Sql

JOINS

NON – EQUI JOINA non equi join specifies the

relationship between columns belonging to different tables by making use of the relational operators, other than the ( = )

Ex: Select e.ename, e.sal, g.grade from emp e, grade g where e.sal between g.losal and g.hisal;

Page 92: Oracle naveen   Sql

JOINS

SELF JOINJoining a table to itself is called a

self join. It joins one row in a table to another. It can compare each row of the table to itself and also with other rows of the same table.

Ex: Select a.ename, b.ename from emp a,

emp b where b.mgr = a.empno

Page 93: Oracle naveen   Sql

JOINS

OUTER JOINThe outer join returns all the rows

returned by simple join as well as those rows from one table that do not match any rows from the other table.

The symbol (+) represents outer join.

LEFT OUTER JOIN:

Ex : select e.ename , e.sal, d.dname, d.loc from emp e, dept d where d.deptno = e.deptno(+);

Left side table gets priority.

Page 94: Oracle naveen   Sql

JOINS

RIGHT OUTER JOIN:

Ex : select e.ename , e.sal, d.dname, d.loc from emp e, dept d where e.deptno(+) = d.deptno;

Right side table gets priority.

Page 95: Oracle naveen   Sql

SUBQUERIES

Nesting of queries, one within the other is termed as a subquery. Subqueries are used to retrieve data that depend on the values in the table itself.

Ex: Select * from emp where deptno = (select deptno from dept where dname = ‘SALES’);

Page 96: Oracle naveen   Sql

SUBQUERIESSubqueries which return multiple

values.A subquery can return more than one

value. In such cases we should include operators like any, all, in or not in between the comparison operator and the subquery.

Ex: Select * from emp where deptno = any

(Select deptno from dept where deptno = 30 and dname =‘SALES’);

Select * from emp where empno in (select distinct mgr from emp);

(=any) is equivalent to IN and (!=all) is equivalent to NOT IN.

Page 97: Oracle naveen   Sql

SUBQUERIES

MULTIPLE Subquery

Nesting of a query within a subquery is also allowed. The subqueries will retrieve information from more than one table and such information is passed on the main query.

Select deptno from dept where deptno = any (select deptno from emp where job = (select job from emp where sal = 1600));

Page 98: Oracle naveen   Sql

SUBQUERIESCORRELATED Subquery

Correlated subquery is evaluated once for every row processed by the parent statement.

Ex: select distinct(job) from emp e

Where 3<=(select count(job) from emp

where e.job = job);

If the subquery is selected from the same table as the main query, then the main query must define an alias for the table name, and the subquery must use the alias to refer to the column’s value in the main query.

Page 99: Oracle naveen   Sql

CONSTRAINTS

Integrity Constraints : An integrity constraint is a mechanism used by Oracle to prevent invalid data entry into the table. Constraints are used for enforcing rules that the column in a table have to conform with.

Types of Constraints:

o Domain integrity constraintso Entity integrity constraintso Referential integrity constraints

Page 100: Oracle naveen   Sql

Domain Integrity ConstraintsThese constraints set a range, and

any violations that take place will prevent the user from performing the manipulation that caused the breach.

Types of Domain Integrity Constraints:

o Not Null Constrainto Check Constraint

Page 101: Oracle naveen   Sql

NOT NULL CONSTRAINTo By default all columns in a table allow null values.

o When a ‘Not Null’ constraint is enforced though either on a column or a set of columns in a table , it will not allow null values. The user has to provide a value for the column.

o Not Null constraint can be defined using alter table command even when the table contains rows.

o One null is not equivalent to another null.

Page 102: Oracle naveen   Sql

NOT NULL CONSTRAINTEx: Create table student_master (sid

number(5), sname varchar2(25) constraint nn1 not null, add1 varchar2(25) constraint nn2 not null, add2 varchar2(20) not null, course varchar2(25) not null, phone number(8));

Providing a constraint name will be useful for any future reference. If a constraint name is not specified then oracle generates a unique code which is a set of alphanumeric characters.

The data dictionary is a set of tables that a user can query to obtain information on users and structures in the database. DD table user_constraints has to be queried to obtain the constraint name.

Page 103: Oracle naveen   Sql

NOT NULL CONSTRAINT

Altering a table to include Not Null constraint

If the records present in the table have null values in the column on which the constraint is to be defined the Oracle will not allow any modification on that column.

Ex: Alter table student_master modify phone not null;

Alter table student _master add add3 varchar2(25) constraint nn3 not null;

Page 104: Oracle naveen   Sql

CHECK CONSTRAINTS

Check constraints specify conditions that each row must satisfy.

These are rules governed by Logical or Boolean expressions.

Check conditions cannot contain subqueries.

Ex: create table pro_master(p_code varchar2(25), p_desc varchar2(20), p_cat varchar2(20), qty_hand number(5), re_level number(5), max_level number(5) constraint max check(max_level<500), p_rate number (9,2));

Page 105: Oracle naveen   Sql

CHECK CONSTRAINTS

Tables can be altered to add a check constraints only if the table is empty.

Ex: Alter table pro_master add constraint qty check (qty_hand <=1000);

Page 106: Oracle naveen   Sql

TABLE LEVEL & COLUMN LEVEL CONSTRAINTS

The table level constraint is a part of the table definition. An intergrity constraint defined at the table level can impose rules on any columns in the table whereas column level constraint being a part of the column definition can be imposed only on the column on which it is defined.

The NOT NULL constraint can be given only at column and not at table level. A column level definition can be done by any integrity constraint in the create table command but the alter table command allows only removal or addition of a not null constraint at the column level.

Page 107: Oracle naveen   Sql

Entity Integrity Constraints

Each entity represents a table and each row of a table represents an instance of the entity. Each row of a table can be uniquely identified using the entity constraint.

Entity integrity constraints are of two types.

o Unique constraints o Primary key constraints

Page 108: Oracle naveen   Sql

Unique Constraints

o Usage of the unique key constraint is to prevent the duplication of values within the rows of a specified column or a set of columns in a table.

o Columns defined with this constraint can also allow null values.

o If unique constraint is defined in combination of columns it is said to be a composite unique key. Those combination of columns cannot have duplicate values.

o Maximum combination of columns that a composite unique key can contain is 16.

Page 109: Oracle naveen   Sql

Unique Constraints

A composite unique key is applicable to all the columns included in the constraint clause. This kind of constraint can be applied only at the table level.

The entity integrity & referential integrity constraints can have composite keys.

Ex: create table pro_master(p_code varchar2(25), p_desc varchar2(20), p_cat varchar2(20), qty_hand number(5), re_level number(5), max_level number(5) constraint max check(max_level<500), p_rate number (9,2), constraint pro_uni unique (p_desc));

Page 110: Oracle naveen   Sql

Unique Constraints

Ex: alter table pro_master add constraint pro_uni unique (p_desc);

Composite:

Ex: alter table pro_master add constraint comb_uni unique(p_code,p_desc);

Page 111: Oracle naveen   Sql

Primary Key Constraints

The primary key constraint avoids duplication of rows and does not allow Null values, when enforced in a column or a set of columns. As a result it is used to identify a row. A table can have only one primary key. If a primary key constraint is assigned to a combination of columns it is said to be a composite primary key which can contain a maximum of 16 columns.

Primary key constraint cannot be defined in an alter table command when the table contains rows having null values.

Page 112: Oracle naveen   Sql

Primary Key Constraints

Defining at column level

Ex: create table student_detail(sid number(6) constraint stu_prim primary key, sname varchar2(25), course varchar2(25));

Defining at Table level

Ex: create table student_detail(sid number(6) , sname varchar2(25), course varchar2(25), constraint stu_prim primary key(sid));

Page 113: Oracle naveen   Sql

Primary Key Constraints

Altering a table to add constraint

Ex: alter table student_detail add constraint stu_prim primary key(sid);

Composite Primary Key

Ex: create table first (sno varchar2(4),city varchar2(20), status number(3), pno varchar2(4), qty number(6), constraint comb_prim primary key(sno,pno));

Page 114: Oracle naveen   Sql

Referential Integrity Constraints

To establish parent child relationship between two tables having a common column, we make use of referential integrity constraints. To implement this we should define the column in the parent table as primary key and the same column in the child table as a foreign key referring to the corresponding parent entity.

Page 115: Oracle naveen   Sql

Referential Integrity ConstraintsForeign Key: a column or a combination

of columns included in the definition of referential integrity which would refer to a referenced key.

Referenced key: it is a unique or a primary key which is defined on a column belonging to the parent table.

Child table: this table depends upon the values present in the referenced key of the parent table which is referred by a foreign key.

Parent table: this table determines whether insertion or updation of data can be done in child table. This table would be referred by child tables foreign key.

Page 116: Oracle naveen   Sql

Referential Integrity ConstraintsEx: Parent table:

Create table supplier_city(sno varchar2(5), city varchar2(25),constraint supp_prim primary key(sno));

Ex: Child table:

Create table parts(sno varchar2(5) constraint part_fk references supplier_city(sno), pno varchar2(5), qty number(6), constraint part_prim primary key(sno,pno));

Page 117: Oracle naveen   Sql

Referential Integrity ConstraintsThe foreign key ensures that all

values in the column sno of the table Parts have corresponding values in the parent table Supplier_city.

The referential integrity constraint does not use foreign key keyword to identify the columns that make up the foreign key. This is because the constraint is defined at column level. The foreign key is automatically enforced on the columns.

Page 118: Oracle naveen   Sql

Referential Integrity ConstraintsIt is possible to define the

referential integrity constraint at the table level.

Ex: create table city_status(city varchar2(25) constraint city_prim primary key, status number(3));

Ex: alter table supplier_city add constraint city_fk foreign key(city) references city_status(city);

(Foreign key word is optional. It is to simplify the syntax)

Page 119: Oracle naveen   Sql

On Delete Cascade

The On Delete Cascade clause specifies that Oracle maintains referential integrity by automatically removing dependent foreign key values if a referenced primary key value is removed.

Syntax: create table table_name (colu1 definition, colu2 datatype constraint cons_name references parent_table_name (colu_name) on delete cascade);

Page 120: Oracle naveen   Sql

On Delete Cascade

When a relation is created between two tables, it is permissible to delete records in the child table. But a vice-versa operation, deleting records from a parent table when it references another child table is not allowed. The on delete clause will override this and allows automatic deletion of child records when a parent record is deleted.

Page 121: Oracle naveen   Sql

Deferrable Constraints

Deferred constraint checking is possible in oracle. When a constraint is made deferrable, oracle leaves the checking until the transaction is committed.

Each constraint has two additional attributes to support deferred checking of constraints.

o It may be deferred or not deferred

o The initial state may be set to initially deferred or initially immediate

Page 122: Oracle naveen   Sql

Deferrable Constraints

The three conditions that can be set are

1. Deferrable initially immediate – this checks for constraint violation at the time of insert.

2. Deferrable initially deferred – this checks for constraint violation at the time of commit.

3. Non deferrable initially immediate – this is the default condition which need not be specified.

Page 123: Oracle naveen   Sql

Deferrable Constraints

Syntax for setting the condition.Alter table table_name add

constraint const_name foreign key(colu_name) references parent_table_name(colu_name) deferrable initially deferred.

o The above syntax when used will add a constraint which will by default only be checked at commit time. The constraint and the fact that it is checked at commit time, is both encapsulated within the definition of the table.

Page 124: Oracle naveen   Sql

Deferrable ConstraintsTo enable all constraintsSet constraints all immediate;To disable all constraintsSet constraints all deferred; SET CONSTRAINTS lasts for

the duration of the transaction.Enforcement is applied to any

future inserts or updates, but does not care about data already in the table.

Syntax: Alter table table_name enforce constraint const_name;

Page 125: Oracle naveen   Sql

Deferrable Constraints

To drop a constraint

Alter table table_name drop constraint const_name;

Dropping a constraint will allow future insertions or other manipulations without affecting existing data in the table.

Page 126: Oracle naveen   Sql

Concept Of Locking

Oracle automatically uses different types of locks to control concurrent access of data and to prevent destructive interaction between users. Oracle automatically locks a resource on behalf of a transaction. This is done to prevent other transactions from doing something also requiring exclusive access to the same resource. Throughout its operation, oracle automatically acquires different types of locks at different levels of restrictive ness depending on the resource being locked and the operation being preformed. The lock is released automatically when an event occurs so that the transaction no longer requires the resource.

Page 127: Oracle naveen   Sql

Concept Of Locking

The concept of locking can be better understood when two users are accessing the same rows on the same table at the same time it may end up in a situation where one user might delete the row where the other is trying to update the row. To overcome this situation Oracle incorporates a locking facility which permits or denies access to other users on a table or to certain rows in a a table, when a user is still is in the process of operating on them.

Page 128: Oracle naveen   Sql

Types of LocksLocks provide high degree of

data concurrency. Locks can be acquired at two different levels.

Row Level Lock (For a specific row)

The select command when used with “for update of clause” places an exclusive lock on one or more rows of a table. This command can be used to lock the rows that would be updated later. A row level lock is applied to prevent other users from manipulating the row till the update is completed.

Page 129: Oracle naveen   Sql

Types of Locks

Ex: select * from emp where sal = 1600 for update of job;

The next update command will be similar to:

Update emp set job = ‘MANAGER’ where sal = 1600;

Since the rows are locked by the ‘For update’ clause no other user can update the particular row till the lock is released. Users can manipulate the other rows in the table.

Page 130: Oracle naveen   Sql

Types of Locks

Table Level Lock (For entire table)

A table level lock will protect table data thereby guaranteeing data integrity when data is being accessed concurrently by multiple users. A table lock can be held in several modes.

Share Lock Share Update Lock Exclusive Lock

Page 131: Oracle naveen   Sql

Types of Locks

Share Lock

A share lock locks the table allowing users to only query but not insert, update or delete rows in a table. Multiple users can place share locks on the same table at the same time.

Ex: lock table <table_name> in share mode;

Page 132: Oracle naveen   Sql

Types of Locks

Share Update LockIt locks rows that are to be

updated in a table. It permits other users to concurrently query, insert, update or even lock other rows in the same table. It prevents the other users from updating the row that has been locked. We can enforce a share update lock by using the ‘for update’ clause in the select statement.

Share update lock falls under the table level but is effective only on rows.

Page 133: Oracle naveen   Sql

Types of Locks

Share Update Lock

Ex: lock table <table_name> in share update mode;

If a row is being updated in a table, when the share update lock is applied, the table will be available for all DML manipulation except the row that is being updated.

It allows numerous users to concurrently lock different rows of a table.

Page 134: Oracle naveen   Sql

Types of Locks

Exclusive LockExclusive lock is the most

restrictive of all table locks. When issued by one user, it allows the other users to only query but not insert, delete or update rows in a table. Only one user can place an exclusive lock on a table at a time, whereas many users can place a share lock on the same table at the same time. Locks can be released by issuing either a rollback or commit.

Ex: lock table <table name> in exclusive mode;

Page 135: Oracle naveen   Sql

Types of LocksNowait ClauseWhen a user has locked a table

without a “nowait” clause in the lock table format, if another user tries to violate the above restriction by trying to lock the table, then, he will be made to wait indefinitely until the user who has initially locked the table issues a commit or rollback statement. The delay could be avoided by appending a “nowait” clause in the lock table command.

Ex: lock table <table_name> in exclusive mode nowait;

Page 136: Oracle naveen   Sql

Types of Locks

Deadlock

A deadlock occurs when two users have a lock, each on a separate object, and, they want to acquire a lock on each other’s object. When this happens, the first user has to wait for the second user to release the lock, but the second user will not release it until the lock on the first user’s object is released. At this point both the users are at impasse and cannot continue. In such case, Oracle detects the deadlock automatically and solves the problem by aborting one of the two transactions.

Page 137: Oracle naveen   Sql

User Performing

The task

Locks mode permitted by another user

  

Establishing a share lock

Share

Share update

Exclusive

Yes No No

Establishing a share update

lockNo Yes No

Establishing an exclusive

lockNo No No

Querying a table

Yes Yes Yes

 

Page 138: Oracle naveen   Sql

TABLE PARTITIONS Tables can be Partitioned and stored in

different locations as per requirements. A single logical table can be split into a

number of physicallly separate pieces based on ranges of key values. Each of the parts of the table is called a PARTITION.

Although the partitions are held and managed independently , they can be queried and updated by reference to the name of the logical table.

Partitioning provides for physical security of the data. Breaking the table into smaller units minimizes the risk of data loss as only a part of the table could be lost rather than the entire table.

Page 139: Oracle naveen   Sql

TABLE PARTITIONS

A partitioned table consists of a number of pieces each having the same logical attributes.

There is a difference between a table which has single partition and a table that has no partitions. A non – partitioned table cannot be partitioned later.

Each partition is stored in a different segment and has different physical attributes.

Table partitions can be stored in different physical locations. We can access and manipulate data in one partition even if some or all of the other partitions are unavailable. Administrators and users can perform maintenanace operations on one partition while the data in other partitions will be available for use.

Page 140: Oracle naveen   Sql

Advantages of Table PartitionsSaves disk space & processing time.Reduction in the size of the unit of

failure.Partition mechanism built into the

server can enable set based parallel update & delete operations.

Allows for concurrent use of various partitions for various purposes.

Failure of one partition will not affect data access from other partitions.

Allows maintenance of selected partitions while other partitions can be available for users.

VLDB’s support.

Page 141: Oracle naveen   Sql

Advantages of Table PartitionsAdvantages of storing partitions

in different table spaces.o Reduces the possibility of data

corruption in multiple partitions.

o Back up & recovery of each partition can be done independently.

o Controlling the mapping of partitions to disk drives is possible.

Page 142: Oracle naveen   Sql

Creating a table partitionCreate table table_name (col1 datatype,

col2 datatype) partition by range(col name) (partition part_name values less than (value), partition part_name values less than (value));

Ex: create table stu_master (sid number(3) constraint stu_prim primary key, sname varchar2(15), courseid number(3)) partition by range (sid) (partition part1 values less than (100), partition part2 values less than (200));

Partitioned tables CANNOT contain any column with Long, Long Raw, LOB, Object types, User defined datatypes.

Page 143: Oracle naveen   Sql

Inserting records into a partitioned table

The records are stored in the table based on the partition key specified.

The partition key specified in the insert statement is compared with partition bound defined when creating the partitioned table.

Ex: insert into stu_master values (&sid, ‘&sname’, &courseid);

Sid = 90, Sid = 100, Sid = 150, Sid = 200, Sid = 300

Page 144: Oracle naveen   Sql

Querying the Partitions

Ex:

select * from stu_master partition (part1);

Select * from stu_master partition (part2);

First partition – Sid range 1 - 99

Second partition – Sid range 100 - 199

Page 145: Oracle naveen   Sql

Additional PointsA table can be partitioned on

more than one column. The partition key specified in the insert statement is compared with partition bound defined when creating the partitioned table.

Ex: create table stu_master2 (sid number(3) constraint

stu_prim primary key , sname varchar2(15), cid number(3)) partition by range (sid,cid) (partition part1 values less than (100,10), partition part2 values less than (200,20), partition part3 values less than (maxvalue,maxvalue));

Page 146: Oracle naveen   Sql

Additional PointsEx: insert into stu_master2

values (&sid, ‘&sname’, &cid);Sid = 90 Cid = 9, Sid = 150 Cid =

2 In the second insert, inspite of

Cid = 2, the record is inserted in the second partition because the LEFT PREFIX OF THE PARTITION BOUND TAKES PRECEDENCE.

The keyword MAXVALUE if specified in the partition bound value_list will accept all values greater than the bound specified in the previous partition.

Page 147: Oracle naveen   Sql

Additional PointsThe table partitions can also be placed

in tablespaces defined by the user.Placing table partitions in different

tablespaces is optional.When the Tablespace clause is not

mentioned Oracle creates the table in the default “System” tablespace.

Syntax: Create table tab_name(col1 definition, col2 definition) partition by range (col_name)

(partition part_name values less than (value) tablespace tabspc_name, partition part_name values less than (value) table space tabspc_name);

Page 148: Oracle naveen   Sql

Partition Maintenance OperationsMoving Partitions: to move a partition

from one tablespace to another.Syntax: alter table table_name move

partition part_name tablespace tabspc_name;

Adding Partitions: to add a new partition after the existing last partition (high end)

Syntax: alter table table_name add partition part_name values less than (value);

The new partition is appended to the end of the table.

The add partition option mentioned above is only for the tables where the last existing partition has been defined with a specific key value.

Page 149: Oracle naveen   Sql

Partition Maintenance OperationsSplitting Partitions: o To split a partition in two.o To add a partition at the

beginning or in the middle of a table or if the partition bound on the highest partition is MAXVALUE.

Syntax: alter table table_name split partition part_name at (value) into (partition part_name, partition part_name);

Page 150: Oracle naveen   Sql

Partition Maintenance OperationsEx: alter table stu_master split

partition part2 at (150) into (partition part3, partition part4);

Part3 – Sid range 100 – 150

Part4 – Sid range 151 – 200 Splitting a partition is not

possible along the partition key specified as it the highest bound.

Ex: Splitting Part2 of table stu_master at 200.

Page 151: Oracle naveen   Sql

Partition Maintenance OperationsDropping Partitions:

Syntax: alter table table_name drop partition part_name;

Exchanging Table partitions: Exchanging table partitions is used to

convert a partition into a non-partioned table, and a table into a partition of a partioned table by exchanging their data segments.

Useful when an application using non-partitioned table needs to be converted into partitions of a partitioned table.

Page 152: Oracle naveen   Sql

Partition Maintenance OperationsSyntax: Alter table table_name

exchange partition part_name with table table_name_exch;

Ex: create table part_exchange (sid number(3) constraint stu_prim primary key, sname varchar2(15), courseid number(3));

Insert into part_exchange values (139,’xyz’,100);

Alter table stu_master exchange partition part2 with table part_exchange;

The data exchange will take place only if the records in the table conform to the partition bound.

Page 153: Oracle naveen   Sql

Synonym

A synonym is a database object which is used as an alias for a Table,View or Sequence.

They are used to simplify SQL statements.

Hide the name and owner of an object Provide location transparency for

remote objects of a distributed database

Provide public access to an objectSynonyms can be used when a user

creates a table or other database object and wants to grant all privileges to other users but does not want them to alter the structure or drop the table all together.

Page 154: Oracle naveen   Sql

Synonym

Synonyms can either be private or public.

Private Synonyms are created by normal user which is available only to that user

Public synonyms are created by the DBA and are available to any database user

Syntax: for creating a synonym

Create [public/private] synonym synonym_name for table_name;

Page 155: Oracle naveen   Sql

Synonym

A synonym is an alias of a table and all manipulations on it actually affects the table.

Users other than the creator can perform all DML operations on the Synonym in the same way that of the table but cannot perform any DDL operations on the synonym excepting for dropping the Synonym itself.

Querying user_synonyms will provide details of synonyms that the user has created.

Page 156: Oracle naveen   Sql

Synonym

Public Synonyms are created by a DBA to hide the identity of a base table and to reduce the complexity of SQL statements.

Public synonyms are owned by user group PUBLIC. When there is a public and local object with the same name, the local object takes precedence. But the public synonym can be used as usual after dropping the local object.

An example of a public synonym is TAB which is used to view the tables owned by the user.

Page 157: Oracle naveen   Sql

Sequences

A Sequence is a database object, which can generate unique, sequential integer values. It can be used to automatically generate primary key values. A sequence can be either in an ascending or a descending order.

Syntax: create sequence seq_name [increment by n] [start with n] [minvalue n]

[maxvalue n] [cycle/nocycle] [cache/nocache];

Page 158: Oracle naveen   Sql

Sequences

Increment by n: ‘n’ is an integer which specifies the interval between the sequence numbers. The default is 1. If n is positive, then the sequence ascends and if it is negative the sequence descends.

Start with n: specifies the first sequence numbers to be generated.

Minvalue n: specifies the minimum value of the sequence. By default it is 1 for an ascending sequence and 10e26-1 for a descending sequence.

Maxvalue n: it specifies the maximum value that the sequence can generate. By default, it is –1 for descending & 10e27-1 for ascending sequence.

Page 159: Oracle naveen   Sql

Sequences

Increment by n: ‘n’ is an integer which specifies the interval between the sequence numbers. The default is 1. If n is positive, then the sequence ascends and if it is negative the sequence descends.

Start with n: specifies the first sequence numbers to be generated.

Minvalue n: specifies the minimum value of the sequence. By default it is 1 for an ascending sequence and 10e26-1 for a descending sequence.

Maxvalue n: it specifies the maximum value that the sequence can generate. By default, it is –1 for descending & 10e27-1 for ascending sequence.

Page 160: Oracle naveen   Sql

Sequences

Cycle: Specifies that the sequence continues to generate values from the beginning after reaching either its max or min value.

No cycle: specifies that the sequence cannot generate more values after reaching either its maxvalue or minvalue. The default value is ‘no cycle’.

Cache: the cache option pre allocates a set of sequence numbers and retains them in the memory so that sequence numbers can be accessed faster. When the last of the sequence numbers in the cache has been used, oracle reads another set of numbers into the cache.

Page 161: Oracle naveen   Sql

Sequences

Nocache: the default value ‘nocache’, does not preallocate sequence numbers for faster access.

Ex: to generate student id numbers automatically without any duplicates, we can create a sequence and use it in the insert statement.

Create sequence sidseq Increment by 1 start with 1 minvalue 1 maxvalue 100 cycle cache 40

After creating a sequence its values can be accessed with the help of the pseudo columns like currval and nextval. A pseudo columns behave like table columns, but it is not actually stored in the table. We can select values from pseudo columns but cannot perform manipulations on their values.

Page 162: Oracle naveen   Sql

SequencesNextval: nextval returns initial value of

the sequence, when referred to, for the first time. Later references to nextval will increment the sequence using the increment by clause and return the new value.

Currval: returns the current value of the sequence which is the value returned by the last reference to nextval.

Ex: insert into stu_master (sid,sname) values (‘s’||sidseq.nextval, ‘rajat’);

To obtain the current sequence number:Syntax: Select seq_name.currval from

dual;Ex: select sidseq.currval from dual;

Page 163: Oracle naveen   Sql

Sequences

Sequences are altered to Set or eliminate minvalue or

maxvalue Change the increment value Change the number of cached

sequence numbersEx: alter sequence sidseq maxvalue 150;Rules for sequences:Ascending Sequence: Minvalue should

be less than MaxvalueDescending Sequence: Maxvalue should

be less than Minvalue.USER_SEQUENCES will provide

details about sequences created by users.

Page 164: Oracle naveen   Sql

View A view is a tailored

presentation of the data contained in one or more tables or other views.

A view takes the output of a query and treats it as a table. Therefore, a view can be thought of as a “stored query” or a “virtual table”.

The tables on which views are built are called base tables.

Views can be used in most of the places where tables can be used.

Page 165: Oracle naveen   Sql

ViewAdvantages of views:1. They provide an additional level of table

security by restricting access to a predetermined set or rows and columns of a table.

2. They hide data complexity.Ex: A single view might be defined with a

join, which is a collection of related columns or rows in multiple tables. However, the view hides the fact that this information actually originates from several tables.

3. They simplify commands for the user because they allow the to select information from multiple tables without actually knowing how to perform a join.

4. View’s isolate applications from changes in the base table. Views can provide a different view of the table by renaming the columns without affecting the table.

Page 166: Oracle naveen   Sql

ViewSyntax for creating a view:Create [or replace] [{no}{force}]

view <view_name> [column alias_name] as <query> [with {check option} {read only} {constraint}];

Ex:Create view emp_v1 as select *

from emp1;Create view emp_v2 as select

empno,ename,sal from emp1;Create view emp_v3 as select *

from emp1 where deptno = 10;

Page 167: Oracle naveen   Sql

ViewWith check option:

Create or replace view emp_v3 as select * from emp1 where deptno = 10 with check option constraint empv;

Update emp_v3 set deptno = 20 where deptno = 10;

Error: check option violation

View with specific columns:

Create view emp_v4 as select empno,sal,comm from emp1;

Update emp_v4 set deptno = 40;

Error: invalid column name

Page 168: Oracle naveen   Sql

ViewWith Read only option:

Create or replace view emp_v3 as select * from emp1 with read only;

Update emp_v3 set deptno = 20;

Error: virtual column not allowed here.

Creating Views with errors:

If there are no syntax errors in a create view statement, oracle will create view evn if the view defining query refers to a non – existent table or an invalid column of an existing table, or when the view owner does not have the required privileges. The view will anyway be created and entered into the data dictionary. The view is considered created with errors.

Page 169: Oracle naveen   Sql

ViewWith Force option: to create a view with

errors, include the Force option in the Create View command:

Ex: Create force view force_v as select * from dept1;

When we create a table with the name Dept1, the view is automatically recompiled and becomes valid.

Manual recompilation:

Alter view force_v compile;

Page 170: Oracle naveen   Sql

ViewJoin Views: joining of tables is possible in

view. Ex: create empdept_v as select

empno,ename,sal,e.deptno,dname from emp e,dept d where e.deptno = d.deptno;

A. View’s cannot select pseudo columns like currval & nextval.

B. If a view’s query contains joins, set operators, group functions and distinct clause the deletion, updation and insertion cannot be performed.

C. The changes performed in the view will affect the base table and vice versa.

D. Group functions and group by clause can also be included in the views.

E. While using functions the column must be given an alias name.

Page 171: Oracle naveen   Sql

ViewPartition View: With partition views the

data resides in separate tables. These tables are brought together at runtime using the operator union all.

Syntax: create view <view name> as Select * from table_name1 union allSelect * from table_name2 union allSelect * from table_name3;Dropping Views: Syntax: drop view view_name;DD table USER_VIEWS will provide

details on views that user has created

Page 172: Oracle naveen   Sql

INDEX

Indexes are optional structures associated with tables. Indexes are created explicitly to speed up SQL statement execution on a table. Oracle index provides a faster access to table data, it affects only the speed of execution.

The index points directly to the location of the rows containing the value. The absence or presence of an index does not require a change in the working of any SQL statement.

Page 173: Oracle naveen   Sql

INDEX

An index is created on a column or a combination of columns using Create Index command.

Syntax:

Create index index_name on table_name(column_name);

When an index is created, Oracle fetches and sorts the columns to be indexed, and stores the ROWID along with the index value for each row.

Page 174: Oracle naveen   Sql

INDEX Indexes are physically & logically

independent of the data in the associated table.

Indexes can be created or dropped without affecting the base table.

Indexes are independent structures & require storage space.

Oracle automatically maintains & uses indexes once they are created.

Oracle automatically reflects changes to data, such as addition or new rows, deletion,updating rows, in all relevant indexes with no additional action by users.

Page 175: Oracle naveen   Sql

UNIQUE INDEXES

Unique indexes guarantee that no two rows of a table have duplicate values in the columns that define the index.

Syntax: create unique index index_name on table_name(column_name);

A unique index is automatically created when we create unique or primary key constraint. Alternatively a constraint is imposed on the column we create unique index.

We cannot create index for a column which is already indexed.

Page 176: Oracle naveen   Sql

COMPOSITE INDEXES

A composite index is an index created on multiple columns of a table. Columns in a composite index can appear in any order and need not be adjacent columns of a table.

Syntax: create index index_name on table_name(col_name1, col_name2);

Composite index can enhance the retrieval speed of data for select statements in which the ‘where’ clause references all or the leading portion of the columns in the composite index. Generally, the most commonly accessed or most selective columns go first in the order of the column list.

Page 177: Oracle naveen   Sql

REVERSE KEY INDEXESCreating a reverse key index, when

compared to a standard index, reverses each byte of the column being indexed while keeping the column order.

Syntax: create index index_name on table_name(column_name) reverse;

REBUILD a reverse key index into normal index using the keyword NOREVERSE.

Syntax: Alter index index_name rebuild noreverse;

We cannot rebuild a normal index as a reverse key index.

Page 178: Oracle naveen   Sql

BITMAP INDEXES

The advantages for Bitmap Indexes are greatest for low cardinality columns. Columns in which the number of distinct values is small compared to the number of rows in a table.

Syntax: create bitmap index index_name on table_name(column_name);

Bitmap indexes can dramatically improve query performance. AND and OR conditions in the where clause of a query can be quickly resolved by performing the corresponding Boolean operations directly on the bitmaps before converting the resulting bitmap into rowids.

Page 179: Oracle naveen   Sql

INDEX ORGANIZED TABLESAn index organized table differs from a

regular table in that the data for the table is held in its associated index. Changes to the table data, updation,insertion, deletion result only in updating the index.

EX: create table table_index (sid number(6) primary key, sname varchar2(20)) organization index;

Index organized table should have a primary key column, and that column will be the indexed column.

Page 180: Oracle naveen   Sql

PARTITIONING IN INDEX

Syntax for creating a partitioned index:

Create index index_name on table_name (col1,col2)

[Global/Local] partition by range (col2))

partition values less than (value) tablespace tabspc_name1, Partition values less than (value) tablespace tabspc_name2;

In the case of global indexes the keyword global need not be specified as it is present by default.

Page 181: Oracle naveen   Sql

LOCAL INDEXES

Syntax: Create index index_name on table_name (column_name) local;

In a local index, the partition key in the partition index should refer to the same rows as that of the underlying table partition.

A local index can be created on a partition by specifying the LOCAL attribute in the Create Index statement.

DD table User_segments gives details of partition name,segement type & tablespace name.

Page 182: Oracle naveen   Sql

GLOBAL INDEXES

The keys of a global index may refer to the rows stored in more than one underlying partitions. An index is global prefixed if it is partitioned on the left prefix of the index columns.

Ex:

A table partition based on more than one column. If the index is created on the first column then it is said to be prefixed. On the other hand, if the indexing is done on the second column then an error message is displayed that the global index should be prefixed.

Page 183: Oracle naveen   Sql

GLOBAL INDEXES

Create table stu_master(sid number(6), sname varchar2(20)) partition by range (sid))

(partition part1 values less than (100),

Partition part2 values less than (200),

Partition part3 values less than (maxvalue));

Create index stu_index on stu_master(sid) global partition by range (sid))

(partition a values less than (150),

Partition b values less than (maxvalue));

Page 184: Oracle naveen   Sql

GLOBAL INDEXES

Create table stu_master2(sid number(6), sname varchar2(20)) partition by range (sid,sname))

(partition part1 values less than (100, ‘xyz’),

Partition part2 values less than (200, ‘abc’),

Partition part3 values less than (maxvalue,maxvalue));

Create index stu_index2 on stu_master(sid,sname) global partition by range (sname))

(partition a values less than (‘xyz’),Partition b values less than (maxvalue));Error: global partitioned index must be

prefixed.

Page 185: Oracle naveen   Sql

INDEX PARTITIONS VS TABLE PARTITIONS Unlike table partitions movement of

the index partitions requires individual reconstruction of the index or each partition (only in the case of global index).

Alter index index_name rebuild partition part_name;

Index partitions cannot be dropped manually. They are dropped when the data they refer to is deleted from the partitioned table.

In the partition index the rows are also truncated when their main rows from the relevant partitions are also truncated.

DD tables User_indexes, user_ind_partitions, user_ind_columns provide details about indexes.

Page 186: Oracle naveen   Sql

OBJECT ORIENTED PROGRAMMINGObject Oriented Programming is a way to

organize data and the code within program.

A fruit is a CLASS.

Apple is an OBJECT of the CLASS fruit.

COLOUR is an ATTRIBUTE of the OBJECT Apple.

The action Cutting the Apple is a METHOD/FUNCTION of the OBJECT Apple of the CLASS Fruit.

Object: An object is a reusable component that developers need to be aware of, rather than how it works. Objects are basic entities in a system. They could represent any item handled by a program. An ATTRIBUTE could be any property of the object.

Page 187: Oracle naveen   Sql

OBJECT ORIENTED PROGRAMMINGClass: Class refers to the definition of an

Object. Class helps in making the entire set of data and code into a single user defined datatype. Once the class has been defined, a number of Objects that belong to the same class can be treated.

Attributes: Attributes help in identifying an object. These are implemented in the form of variable declarations made within the object clss definition.

Methods: Methods are functions and procedures that are used to perform actions related to the object. Anything that is to be done with the object is implemented as a method.

Page 188: Oracle naveen   Sql

Features of Object Oriented Programminga. Abstraction b.

Encapsulationc. Inheritance d.

PolymorphismExample using C++Base Class Derived

ClassClass A Class B:Public A{ {Public; int b ;Int a = 10; }Void display ( ) main ( ){ { B x;Cout << “a= ”<<a; x.display ( );

} }}

Page 189: Oracle naveen   Sql

Features of Object Oriented Programming

Declaration

Main ( ) int sum(int x, int y)

{ {

Int x; return x+y;

X = sum(10,20); }

Cout << “x= ”<<x; float sum (float x,float y)

Y = sum(10.5,11.2); {

Cout <<“y= ”<<y; return x+y

} }

Page 190: Oracle naveen   Sql

Features of Object Oriented ProgrammingAbstraction: Hiding the DATA and the

METHODS from another CLASS. DATA values and associated METHODS defined in a CLASS(BASE CLASS) can be called in another CLASS (DERIVED CLASS) but the BASE CLASS details is not revealed.

Encapsulation: the wrapping of DATA and FUNCTION/METHOD into a single unit is known as Encapsulation. In other words Encapsulation means binding the DATA with associated METHODS. The virtual container which is Encapsulated is a CLASS.

The real time instance of a CLASS or physical existence of a CLASS is an OBJECT. Encapsulation of DATA from direct access by the program is called ‘DATA HIDING’

Page 191: Oracle naveen   Sql

Features of Object Oriented ProgrammingInheritance: Deriving the features from

one CLASS to another. In other words, reusing the capabilities of already defined CLASS. Inheritance allows desigining of new objects that inherit the functionality of objects that are already created. Inheritance provide the idea of reusability.

Polymorphism: Providing many functionalities with single name and different prototype. The ability of an OBJECT to take more than one form is known as Polymorphism. It enables different OBJECTs to have methods of the same name that accomplish similar tasks, but in different ways.

Page 192: Oracle naveen   Sql

Advantages of Object Oriented in OracleOracle 8.0 and further versions are Object

Relational Database Management System, since they are an extension of the traditional relational database where the object oriented structures & concepts such as Abstract Type, Varrying Arrays, Nested Tables.. Are included.

Object reuse: If object oriented database objects are created the database objects can be reused to create other database objects.

Standard Adherence: if multiple applications use the same set of database objects, then a set of standards for the database objects can be created.

Defined access path: for each object procedures and functions can be defined which act on them. The data and the method that can be accesing this object can be united.

Page 193: Oracle naveen   Sql

Object Oriented Database Objects Abstract Data Types: abstract data

types are datatypes that consist of one or more subtypes. Thay can more accurately describe the data.

Ex: create or replace type address_ty as object (street_no number(3),street_name varchar2(20), city varchar2(20), state varchar2(20));

The above example creates a Type, which is named as address_ty.

The abstract datatype that has been created can be used to represent a column in a table.

The data type can be used to create object tables. In an object table the columns of the table map to the columns of the abstract data type.

Page 194: Oracle naveen   Sql

Object Oriented Database Objects Abstract Data Types: The create type command is the most

important in Object Relational Database. This will create an abstract data type named as address_ty. The as object clause explicitly identifies address_ty as an object oriented implementation. The replace clause recreates the type if it already exists. This clause can be used to change the definition of an existing type without dropping it. Once an abstract datatype has been created it can be used within other data objects.

Page 195: Oracle naveen   Sql

Object Oriented Database Objects Abstract Data Types: When an abstract type is created, then

a standard representation of abstract data elements is created. If the same abstract data type is used in multiple places then there is a guarantee that the same logical data is represented in the same manner. The reuse of the abstract data type leads to the enforcement of standard representation for the data.

Page 196: Oracle naveen   Sql

Object Oriented Database Objects Insertion of values into Abstract Data

Types: Values cannot be inserted directly into

the abstract data type. In order to store data we have to create a table that uses the data type. The data type then be stored in the table in the format specified. Hence the values cannot be directly inserted into the abstract data type. The abstract data type has to be used in a table and only then can values be stored in it.

Page 197: Oracle naveen   Sql

Object Oriented Database Objects Implementing an object type as a

column object:

Ex: Create table stu_master (sid number(5), sname varchar2(25), stu_address address_ty, tel_no number(8));

Ex: desc stu_master

The same can be viewed through the DD table called user_tab_columns.

Ex: select column_name,data_type from user_tab_columns where table_name = ‘STU_MASTER’;

Page 198: Oracle naveen   Sql

Object Oriented Database Objects When a user wants to view the actual

values of the stu_address data type then a query using the DD table user_type_attrs can be used.

Ex: select attr_name, length, attr_type_name from user_type_attrs where type_name = ‘ADDRESS_TY’;

Inserting records into abstract data types:

Ex: insert into stu_master values (101, ‘ritvik’, address_ty(100, ‘ameerpet’, ‘hyderabad’, ‘AP’), 2334456);

Page 199: Oracle naveen   Sql

Object Oriented Database Objects Selecting records from abstract data

types:Ex: select * from stu_master;If the user wants to query only the city

name from the stu_master then a normal query would raise an error.

Ex: select city from stu_master;Error: invalid column nameThe abstract data type cannot be

queried directly because it is a data type and not a table. The dot notation has to be used for the purpose of querying i.e., column.attribute.

Ex: select a.stu_address.city from stu_master a;

Page 200: Oracle naveen   Sql

Object Oriented Database Objects Updating records in abstract data types:Updating is done similar in a similar

manner to that of the select statement. The dot notation and an alias name of the table is used.

Ex: update stu_master aSet a.stu_address.street_no = 10 where sname = ‘AJAY’;

Deleting record from abstract data types:

To delete records that contain abstract data types use the dot notation and the table alias name.

Ex: delete from stu_master a Where a.stu_address.state = ‘AP’;

Page 201: Oracle naveen   Sql

Object Oriented Database Objects Dropping object types: dropping of

object types can be done in the same manner as other data base objects. However there should be no dependencies on the object type.

Ex: drop type address_ty

Error: cannot drop or replace a type with type or table dependencies.

The compiler informs that the object type cannot be changed or dropped without dropping the other objects dependent on it. However the FORCE clause can be used to forcefully drop an object type.

Page 202: Oracle naveen   Sql

Object Oriented Database Objects Dropping object types with FORCE

clause:

Ex: drop type address_ty force;

Using the force option to drop type with dependencies is not recommended. The operation is not recoverable and the data in the table could become inaccesible.

DD views which list the information about direct dependencies and dependency management are

User_dependencies

All_dependencies

Dba_dependencies

Page 203: Oracle naveen   Sql

Object Oriented Database Objects Security for abstract data types:

When two users create two different abstract data types, each of these users can grant the other privilege of using the abstract data type. however., when selecting, inserting, deleting the dot notation should be used. Here the user name has to be specified in addition to the column attribute notation.

Page 204: Oracle naveen   Sql

Object Oriented Database Objects Indexing abstract data types:

Ex: create index streetnum on stu_master (stu_address.street_no);

Once an index is created, it can be checked using the data dictionary table - all_indexes

Ex: select owner,index_name,index_type,table_owner,table_name,table_type from all_indexes where owner = ‘SCOTT’;

Page 205: Oracle naveen   Sql

Object Oriented Database Objects Varying Arrays: these help in storing

repeating attributes of a record in a single row. Varying arrays have a fixed lower value(0) and a flexible upper value(it could be any valid number). Varying arrays cannot be extended beyond the limit that was defined when the Varying array was created. Collectors are a set of elements that are treated as a part of a single row. Collectors such as Varying array allow repetition of only those column values that change potentially, saving storage space.

Page 206: Oracle naveen   Sql

Object Oriented Database Objects Creating a Varying Array:

Ex: create type cid as varray(5) of number(5);

Ex: create type cname as varray(5) of varchar2(15);

The above command creates a Varying Array that could contain a maximum of 5 values and each value could be of data type varchar2.

Creating a table using the varying array:

Ex: create table stu_detail(sid number(8), sname varchar2(25), course_id cid, course_name cname);

Page 207: Oracle naveen   Sql

Object Oriented Database Objects Ex: Desc stu_details

To ascetain the kind of data type that is stored in each column the user_types data dictionary view can be queried.

Ex: Select typecode,attributes from user_types where type_name = ‘CID’;

The DD view user_coll_types gives the characteristics of the varying array including the upper bound, collection type, data type including the abstract data type on which it is based.

Page 208: Oracle naveen   Sql

Object Oriented Database Objects Inserting records into Varying Arrays:Ex: insert into stu_detail values (220212,

‘satish’, cid(10,20,30),cname(‘ora’, ‘dwh’, ‘d2k’));

When values are inserted into the varying array care should be taken such that the maximum limit is not exceeded.

Selecting data from varying array:The varying array cannot be queried

directly using the select command. A cursor FOR loop should be used.

Ex: select * from stu_detail;Ex: select course_name from stu_detail;

Page 209: Oracle naveen   Sql

Object Oriented Database Objects Nested Tables: Nested Tables have no

limit on the number of entries per row. A nested table is a table within a table. A table is represented as a column within another table. Multiple rows can be present in the nested table for each row in the main table.

Ex: create type stu_ty as object (cid number(5), cname varchar2(15), course_fees number(7,2));

To use this data as the basis for a nested table a new abstract data type has to be created

Ex: create type stu_nt as table of stu_ty;

Page 210: Oracle naveen   Sql

Object Oriented Database Objects The as table of clause assumes that this

type will be used as the basis of a nested table. The type stu_nt can be used to create the table stu_detail.

Ex: create table stu_detail (sid number(8), sname varchar2(25), course_detail stu_nt) nested table course_detail store as stu_nested_table;

The nested table is stored in a table that is named stu_nested_table. The data in the nested table is not stored with the rest of the table’s data. It is stored apart from the main table. Oracle maintains pointers between the main table and the nested table.

Page 211: Oracle naveen   Sql

Object Oriented Database Objects To see the structure of the table:

Ex: desc stu_detail or

Ex: select column_name, data_type from user_tab_columns where table_name = ‘STU_DETAIL’;

To verify if stu_nt is a type:

Ex: select typecode, attributes from user_types where type_name = ‘STU_NT’;

Page 212: Oracle naveen   Sql

Object Oriented Database Objects To check the data types used as the basis

for nested tables:

Ex: select coll_type, elem_type_owner, elem_type_name, upper_bound, length from user_coll_types where type_name = ‘STU_NT’;

To see the attributes of stu_ty:

Ex: select attr_name, length, attr_type_name from user_type_attrs where type_name = ‘STU_TY’;

Page 213: Oracle naveen   Sql

Object Oriented Database Objects Querying Nested Tables:

A nested table is a column inside a table. To support queries of columns and rows of a nested table, Oracle provides a keyword (THE). A relational table is in existence in the database and hence can be queried whereas a nested table is a datatype and does not exist till it is used in a relational table and hence cannot be queried. In order to query the nested table the nested table is flattened using the THE function.

Ex: select NT.cid, NT.cname, NT.course_fees, from the (select course_detail from stu_detail) NT;

Page 214: Oracle naveen   Sql

Object Oriented Database Objects ‘THE’ function can be used to perform

Inserts or Updates directly against the Nested Table without necessarily requiring inserts into the main table.

Ex: insert into the (select course_detail from stu_detail where sid = 220234)

values (stu_ty (10, ‘oracle’, 3000));

Ex: update the (select course_detail from stu_detail where sid = 220234) set course_fees = 3500 where cid = 10;

Page 215: Oracle naveen   Sql

Object Oriented Database Objects When records already exist in a nested

table and records are to be inserted into the main table, the key words CAST & MULTISET have to be used together.

The CAST keyword allows casting of the result of a query in the form of a nested query.

The MULTISET keyword allows the cast query to contain multiple records.

Ex: insert into stu_detail values (220235, ‘vinod’, cast(multiset(select * from the (select order_detail from stu_detail where sid = 220234)) as stu_nt));

Page 216: Oracle naveen   Sql

Object Oriented Database Objects Nested tables Vs Varying Arrays: