Вы находитесь на странице: 1из 40

Select

Insert update delete merge DML

Create alter drop rename truncate comment DDL

Grant revoke DCL

Commit rollback
Savepoint TRANSACTION CONTROL

Select last_name “Name”, salary “annn Sal” From employee


(for as it is printing as in invertise comma)

For concatenate
Select last_name || job_is………

Select department_name || q’[,it’s assignes manager id:]’ || managerid……..


Administrator,it’s assigned manager id:

Select distinct department_id from employees;

Describe employee;

Select l_name,sal from emp where sal between 2500 and 3500;

Rules of precedence

Arithmetic operators
Concatenation
Comparison condition
Is[not] null,like,[not]in
[not] between
Not equal to
Not logical condition
And logical condition
Or logical condition

Order by (default increasing order)


Desc

For many time


Select emp_id from emp where emp_id=&emp_id;

For one time


Select emp_id from emp where emp_id=&&emp_id;
For giving next time new value we have to use undefined emp_id
Character function
Lower
Upper
Initcap-----first letter in upper
Concat-----for concatenation
Substr(‘helloworld’,1,5) = hello
Length((‘helloworld’) = 10
Instr((‘helloworld’,’w’) = 6
Lpad(sal,5,’*’) = ***10
Rpad(sal,5,’*’) =10***
Replace(‘jack and jue’,’j’,’bl’) = black and blue
Trim(‘h’ from ‘hello’) = ello

Number function
Round(45.926,2) = 45.93
Trunk(45.926,2) = 45.92
Mod(1600,100) = 100

Date function
Month_between(’date’,’date’)
Add_month(‘ date’,no_of_month)
Next_day(‘date’,’day’)
Last_day (‘date’)
Round (sysdate,’month’)
Round (sysdate,’year’)
Trunc (sysdate,’month’)
Trunc (sysdate,’year’)

Nvl (exp1, exp2)—if exp1 null then print exp2

Nvl2 (exp1, exp2, exp3)—if exp1 not null then print exp2 otherwise exp3

Coalesce (exp1, exp2….expn) ---if exp1 null then exp2,if exp2 null……….then expn

CASE
Select l_name,job_id,sal,
Case job_id when ‘it_prog’ then ..
when ‘st_prog’ then ..
when ‘sa_rep’ then ..
else sal end
from emp;

Decode
Select l_name,job_id,sal
Decode (job_id, ‘it_prog’, …… ,
‘st_prog’, …… ,
‘sa_reg’, …… ,
Sal)
From employees;
Group function

Avg
Count
Max
Min
Stddev--- standard deviation, ignoring null values
Sum
Variance---- Varianceof n , ignoring null values

Group by

Select d_id,avg(sal) from emp


Group by d_id;

Any column or expression in the select list that is not an aggregate function must be in
the group clause

Do not use WHERE with group clause, use HAVING

Select job_id,sum(sal) from emp


Where job_id not like ‘%rep’
Group by job_id
Having sum(sal)>3000
Order by sum(sal);

JOINS

Natural join----all columns in the 2 tables that have the same name.
Equal values in all matched columns.
Column same named but diff data type then error occur.

Eg:- select d_id,d_name,l_id,city


From dep natural join loc;

Joins with using clause—many column with same name but diff data type,natural join
can be applied by using the USING clause to specify the columns that shuld be
equijoins.
Use for specific column.
Don’t use table alise with reference column

Eg-- select e.emp_id,e.l_name,d.l_id,d_id


From emp e join dep d
Using(d_id);

Creating joins with on claues---- the join condition for the natural join is basically an
equijoin of all columns with the same name.
Use the ON clause to specify arbitrary condition or specify columns to join.
The join condition is separated from other search condition.
Self join using on clause

Eg:-- select e.l_name,m.l_name from emp e join emp m


On (e.mgr_id=m.mgr_id);

Three way join

Select emp_id,city,dep_name
From emp e
Join dep d
On d.d_id=e.d_id
Join loc l
On d.l_id=l.l_id;

Nonequi join

Select e.l_name,e.sal.j.g_level
From emp e join job_grad j
On e.sal between j.lowest_sal and j.higest_sal;

Outer join

Select e.l_name,e.d_id,d.dep_name
From emp e left/right/full outer join dep d
On (e.d_id=d.d_id);

Any--- reference max value


All--- > ref max value, < ref min value

A transaction consists of a collection of DML statements that form a logical unit of


work.

Insert

Insert into dept(d_id,d_name,m_id,l_id)


Values(70,’abc’,100,1);

Insert into sales_rep(id,name,sal,commisiion_pct)


Select emp_id,l_name,sal,comm._pact
From emp where job_id like ‘%REP%’;

Update

Update emp
Set dept_id=70
Where emp_id=113;
Delete

Delete from dept


Where dept_name=’Fin’;

Truncate --- remove all rows, can’t undo.

Commit --- ends the current transaction by making all pending changes permanently.
Savepoint --- marks a savepoint with in the transaction .
Eg: savepoint save_ab;

Rollback – rollback ends the current transaction by discarding all pending data
changes.

Rollback to savepoint ----- rolls back the current transaction to the specific savepoint ,
thereby discarding any changes and or savepoints that were created after the savepoint
to which you are rolling back. If you omit the TO SAVEPOINT clause, the
ROLLBACK statement rolls back the entire transaction. Because savepoints are
logical, there is no way to list the savepoint that you created.

Automatic commit occur when DDL, DCL statement is issued or commit.

DATETIME DATA TYPE

Timestamp --- date with fractional seconds


Interval year to month --- stored as an interval of years and months
Eg: Interval ‘123-2’ year (3) to month
** An interval of 123 years,2 months

Interval ‘123’ year (3)


** ** an interval of 123 years

Interval of ‘300’ month (3)


** ** an interval of 300 months
Create table t_exm
(loan_duration interval year (3) to month);

Insert into r_exm (loan_duration)


Values (interval ‘120’ month (3));
Select to_char(sysdate+loan_duration,’dd-mon-yyyy)
From t_exm; (sysdate === 11-11-2008)
Result========= 11-nov-2018

Interval day to second -- stored as an interval of day, hours, minutes and seconds.
Eg: Interval ‘4 5:12:10.222’ day to second (3)
** 4 days 5 hours 12 minutes 10 sec 222 thousandths of a sec
Interval ‘400 5’ day(3) to hour
** 400 days 5 hours
Timestamp with time zone ------ it include a time displacement in it value. The time
zone displacement is the difference b/w local time and universal time coordinate .this
data type is used for collecting and evaluating data information across geographic
location.

Timestamp with local time zone ---- it differ from TIMESTAMP WITH TIME ZONE
in the data stored in the database is normalized to the database time zone .
When user retrieves the data, it returns in the user’s local session time zone.

Constraints

NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK

Column level --- use only for a particular column


eg: create table emp(emp_id number(6)
constraint emp_id_pk primary key,
first_name varchar(20),…….);
Table level --- we can combine more the one column
Eg: create table emp(emp_id number(6),
first_name varchar(20),………..
constraint emp_id_pk
primary key (emp_id, first_name);

Foreign key constraint


It defines the column in the child table at the table-constraints.
Reference – identify the table and column in the parent table.
On delete cascade – delete the dependent rows in the child table when a row in
the parent table is deleted.
On delete set null – converts dependent foreign key values to null.
Eg:

Create table emp


(emp_id number(6)
Constraint emp_id_pk PRIMARY KEY,
l_name varchar2(20)
Constraint l_name_nn NOT NULL,
Email varchar2(20)
Constraint email_uk UNIQUE ,
Salary number(8,2)
Constraint sal_ck CHECK (salary>0),
Dep_id number(4)
Constraint dep_id_fk REFERENCES
Dept(depat_id));
Creating table by using a sub quary

Create table t_12


As select emp_id,l_name,sal,hire_date
From emp where dept_id=80;

Alter statement --- add new column, modify an existing column, define a default
value & drop a column.

Dropping a table -- all data,structure,index and constaints are droped.


Not rollback and all pending transaction are committed.
Only the creator of table or a user with the drop any table privilege can remove the
table.

Database objects --- Table, View, Sequence, Index, and Synonym.

VIEW

 Logical subset or combination of data by creating view of table.


 Restrict access to the data.
 View can be used to make simple queries to retrieve the results of complicated
queries.
 Views provide groups of users access to data according to their particular
criteria.
 Two type ----- simple views , complex views.
 Simple view --- drives data from only one table, not contains any function or
groups of data and can’t perform DML (insert, update, delete) operations
through it.
 Complex view --- drive data from more than one table, contain function or
groups of data and can perform (but not always) DML (insert, update, delete)
operations through it.

Eg: SIMPLE VIEW


Create/replace view empview_12
As select emp_id,l_name,sal,hire_date
From emp where dept_id=80;

COMPLEX VIEW

Create/replace view empview


(name,minsal,maxsal,avgsal)
As select d.dept_name,min(e.sal),
Max(e.sal),avg(e.sal),
From emp e join dept d
On ( e.dept_id = d. dept_id)
Group by e.dept_name;
Denying DML operation --- with read only

Create/replace view empview_12


As select emp_id,l_name,sal,hire_date
From emp where dept_id=80
With read only;

SEQUENCES

 Automatically generated unique number.


 Sharable object
 Can be used to create a primary key value
 Replace application code
 Speed up the efficiency of accessing sequence value when cached in
memory.

Eg : create sequence dept_seq


Increment by 10
Start with 120
Maxvalue 9999
Nocache
Nocycle

NoCycle/cycle - specify whether the sequence continue to generate values after


reaching its max or min value

Cache n /nocache – specify how many values the oracle server pre allocates and keeps
in memory (by default 20 values).
Caching seq. values in memory gives faster access to those values.
Gapes in seq. value can occur when:

 A rollback occurs.
 The system crashes.
 A seq. is used in another table.

For modify the seq. we use ALTER command


Eg. Alter sequence dept_depid…………………………

Some guidelines for modifying seq. :


 We must be owner or have alter privilege
for the seq.
 Only future seq. no. are affected.
 The seq. must be dropped and recreate to
restart the seq. at a different no.
 To remove a seq. , use the DROP
statement.
NEXTVAL AND CURRVAL

 NEXTVAL returns the next value available seq. value. It returns a unique value
every time it is referenced, even for different users.
 CURRVAL obtains the current seq. value.
 NEXTVAL must be issued for that seq. before CURRVAL contains a value.

Eg: insert into dept ( dept_id,dept_name, l_id)


Value (dept_deptid_seq.NEXTVAL, ‘support’ , 2500);

INDEX

 Can be used by the oracle server to speed up the retrieval of rows by


using a pointer.
 Can reduce disk i/o by using a rapid path access method top locate
data quickly.
 Is independent of the table that it indexes and automatically
maintained by oracle server.

Guidelines
Create when
o A column contains a wide range of values
o A column contains a large no. of null values.
o One or more column are frequently used in WHERE clause
or join clause.
o The table is large and most queries are expected to retrieve
less than 2% to 4% of the rows in the table

Not create when


 The column are not often used as a condition in the
query.
 The table is too small or most queries are expected
to retrieve less than 2% to 4% of the rows in the table
 The table is updated frequently .
 The index column are referenced as part of an
expression.

Type --- automatically (unique index) created when we define a PRIMARY KEY or
UNIQUE constraints in a table.
Manually created by users (nonunique index ) on column to speed up access to rows.

Eg: create index ab_index


On emp(l_name);

Drop index ab_index ;


Create INDEX with the CREATE TABLE statement

Eg: create table n_emp


(emp_id number (6)
Primary key using index
(create index emp_id_idx on n_emp (emp_id)),
F_name varchar2 20).
L_name varcahr2 (25));

FUNCTION BASED INDEXES

 A function-based index is based on expression.


 The index expression is built from table columns, constraints, SQL
function, and user-defined function.

Eg: create index upper_dept_name_idx


On dept (upper (dept_name));

SYNONYAM
 To give alternate name to a table.
 Shorten lengthy object names.
 Create an easier reference to a table that is owned by another user.

Public -- create a syn. That is accessible to all users.


By default it will create private which must be distinct named from all objects that are
owned by the same user.

Eg: create synonym d_sum for dept_sum_vl;

Create public synonym d_sum for dept_sum_vl;

Drop synonym d_sum;

Data Dictionary Structure

User ---- user’s view (what is ur schema ; what u own)


All ----- expended user’s view (what u can access)
DBA --- database administrator’s view (what every one’s schema)
V$ --- performance – related data.
Eg:
1. DESC DICTIONARY;
2. DESC USER_OBJECTS;
3. DESC USER_TABLES;
4. DESC USER_TAB_COLUMNS; (column info)
5. DESC USER_ constraints;
6. DESC USER_ cons_ columns;
7. DESC USER_ views;
8. DESC USER_ sequences;
9. DESC USER_ synonyms;
10. Comment on table emp is ‘employee info’;
DATABASE SECURITY

1. System security – it covers access and use of db at the system level such as the
username and password, the disk space allocated to users and the system operation
that user can perform.

2. Data security -- it covers access of database objects and the action that those
users can have on the objects.

Some system privileges of dba --- create user, drop user , drop any table , backup
any table , select any table , create any table.

Create user---- eg: create user user1 identified by password;


NOTE : when dba create a user by this statement ,the user not
have any privileges at this point.

User system privileges --- create session / table / sequence / view / procedure .
Create session is used for connection with database.

Eg: grant create session, create table, create sequence, create view to scott;

ROLE -- group of related privileges that can be granted to the user.

Eg : create role manager;

Grant create table , create view to manager;

Grant manger to user1 , scoot;

Change password --- eg : alter user user1 identified by newpassword;

Object Privileges

Table – alter, delete, index, insert, reference, select update.


View ---- delete, insert, select, update.
Sequence --- alter, select.

Eg: grant object_priv [columns]


On object to {user/role/PUBLIC}
[with grant option];

Public -- grants object privileges to all users .


With grant option -- enables the grantee to grant the object privileges to other
users and roles.
Eg : if A---> B ---- > C ----- > D (with grant option )
If A revoke the privilege from user B then the privileges granted to users C and D
are also revocked.
Note: if a user were to leave the company and you revoke his piv. You must
regrant any priv. that this user may have granted to other users. If you drop the user
without revoking the priv. from it, then the system priv. granted by this user to
other users are not affected by this action.

Alter table statement

Add a new column, modify an existing column, define a default value for the new
column, and drop a column

Eg: alter table dept add (job_id varchar2(9));

alter table dept modify (job_id varchar2(10));

alter table dept drop column job_id ;

Set Unused Option

When we marked as unused than these column will not be seen by select command and
when we run drop command, it will run faster.

Eg: alter table dept set unused (l_name);


Alter table dept drop unused columns;

Adding a constraints

Add or drop a constraints, but not modify its structure, enable or disable constraints,
add a NOT NULL constraints by using the modify clause

Eg : alter table emp modify emp_id primary key;

Alter table emp add constraint emp_mgr_fk


Foreign key (manager_id)
References emp(emp_id);

On delete cascade

Delete child row when a parent key is deleted.

Eg: alter table emp add constraint emp_dt_fk


Foreign key (dept_id)
References dept on delete cascade);

Dropping a constraints

Eg: alter table emp drop constraint emp_mgr_fk;

Drop primary key and associated foreign key


Alter table dept drop primary key cascade;

Disabling / enabling Constraints

Eg: alter table emp disable/enable constraint emp_dt_fk;

Cascading Constraints

 The CASCADE CONSTARINTS clause


is used along with the DROP COLUMN clause.
 The CASCADE CONSTARINTS clause
drop all referential integrity constraints that refer to the primary and
unique keys defined on the dropped column.
 The CASCADE CONSTAINTS clause
also drops all multicolumn constraints defined on the dropped
columns.

Eg: alter table emp drop column emp_id cascade constraints;

Alter table test drop (pk,fk,coll);

Note: first statement drop emp_id column , the primary key constraints and any
foreign key constraints referencing the primary key constraints for emp table.

If all columns ref. by constraints defined on the dropped columns are also
dropped, then CASCADE CINSTARINTS is not required .
Eg: assuming that no other table refer to the PK column , it is valid to submit the
2nd statement without the CASCADE CONSTAINTS clause for the test table
created .

DROP Table by PURGE

 New feature of 10g


 Immediately delete and release the space associated with the table as we
issue the drop table statement with PURGE in a single step.
 We can’t rollback this statement or recover the table .

Eg: drop table dept purge;

Flashback Table Statement

 A new feature of oracle 10g.


 Repair tool for accidental table modification.
 Restore a table to an earlier point in time.
 Benefit: ease of use, availability, fast execution.

Eg: drop table emp;


Select original_name , operation , droptime from recylebin;

Flashback table emp to before drop;


EXTERNAL TABLES

 A read-only table whose metadata is stored in db but data is stored outside


the db.
 No DML operations are possible on external tables and no indexes created
on them.
 The external table data can be queried and joined directly and in parallel
without requiring that the external data first be loaded in the db.
 External tables can be created and thus unload (i.e. read data from a table
in db and insert it into an external table) data by using the CREATE
TABLE AS SELECT command.
 Oracle provide two major driver for external table, one the loader access
driver (oracle_ loader) is used for reading of the data from external files
whose format can be interpreted by the sql loader.
 ORACLE _ DATAPUMP access driver can be used to both import and
export data using a platform-independent format.

Creating a Directory for the External Table

Eg: create or replace directory emp_dir as ‘/…/emp_dir’;

Grant read on directory emp_dir to hr;

We must have CREATE ANY DIRECTORY system priv. to create directory


and we also get automatically granted the read and write object priv.
Note: data unload and reload data into on oracle db ,this is a one time
operation that can be done when the table is created. After the creation and
initial population is done , we can’t update, insert, or delete any rows.

Creating an External Table

Eg: create table <table name>


( <col name> <datatype> , …..)
Organizational external
( type <access_driver_ type>
Default directory < directory_name>
Access parameters
(..))
Location ( ‘<location_specifier’> )
Reject limit [0 | <number> | unlimited];
Use the location clause to specific one external locator for each external data source .
usually the <location_specifier> is a file ,but it need not be.
The reject limit clause enables you to specify how many conversion errors can occur
during a query of the external data before an oracle error is returned and the query is
aborted. Default value is 0.

Creating an External Table By Using Oracle_ Loader

Eg: create table oldemp (


Fname char (25), lname char (24))
Organizational external
(type oracle_loader
Default directory emp_dir
Access parameters
(records delimited by newline
Nobadfile
Nologfile
Fields terminated by ‘,’
(fname position (1:20) char,
Lname position (22:41) char ))
Location (‘emp.dat’))
Parallel 5
Reject limit 200;
Querying External Tables

Copying rows from another table

Eg: insert into sales rep ( id, name, sal, com_pact)


Select emp_id, l_name, sal, comm._pact
From emp
Where job_id like ‘%REP%’;
Note: don’t use the VALUE clause and match no of column in insert clause with the
subquery.
Eg:
Insert into
( select emp_id, l_name, h_date,job_id, sal , dept_id
From emp where dept_id = 50)
Values ( 9999, ‘Abhi’, to_date (’02-jun-99’ , ‘dd-mon-rr’),
‘st_clark’ , 5000 , 50);

Retrieving Data with a Subquery a Source

Eg : select a.l_name , a.sal , a.dept_id , b.salavg


From emp a join ( select dept_id, avg(sal) salavg
From emp group by dept_id ) b
On a.dept_id = b.dept_id
And a.sal > b.salavg;

Updating Two Column with a Subquery

Eg : update emp1
Set job_id = ( select job_id
From emp
Where emp_id = 205 ) ,
Salary = ( select sal from emp
Where emp_id = 168 )
Where emp_id = 114 ;

Eg :
update emp1
Set dept_id ( select dept_id
From emp Where emp_id = 205 )
Where job_id = ( select job_id
From emp
Where emp_id = 200) ;

Delete

Eg: delete from emp1


Where dept_id = ( select dept_id
From dept where dept_name like ‘%public%’);

Explicit Default Feature

 We can use the DEFAULT keyword as a column value where the column default is
desired.
 Allows the user to control where and when the default value should be applied to
data.
 Explicit default can be used in INSERT and UPDATE statements.
Eg : insert into dept
( dept_id , dept_name , manager_id )
Values (300 , ‘engg’, default);

Update dept
Set manager_id = default
Where dept_id = 10 ;

Types of Multi Table Insert Statement

Unconditional Insert: ALL --- the oracle server executes each insert into clause once for
each row returned by the subquery.

Eg : insert ALL
Into sal_his values(empid , hiredate , sal)
Into mgr_his values(empid , mgr , sal)
Select emp_id empid , hire_date hiredate , salary sal , manager_id mgr
From emp where emp_id > 200 ;

Conditional Insert: --- > oracle server filters each insert into clause through the
corresponding WHEN condition , which determine whether that insert into clause is
executed. A single multitable insert statement can contain up to 127 WHEN clause.

Eg: insert
When sal > 10000 then
Into sal_his values(empid , hiredate , sal)
When mgr > 200 then
Into mgr_his values(empid , mgr , sal)
Select emp_id empid , hire_date hiredate , salary sal , manager_id mgr
From emp where emp_id > 200 ;

Conditional Insert : All -- > if we specify ALL , the oracle server evaluate each when
clause regardless of the result of the evaluation of any other WHEN clause.
Eg: insert ALL
When sal > 10000 then
Into sal_his values(empid , hiredate , sal)
When mgr > 200 then
Into mgr_his values(empid , mgr , sal)
Select emp_id empid , hire_date hiredate , salary sal , manager_id mgr
From emp where emp_id > 200 ;
Pivoting INSERT ------ > is an operation in which we must build a transformation such
that each record from any i/p stream as non- relational db table, must be converted
into multiple records for a more relational db table environment.
Eg : suppose we receive a set of sales records from a non-relational db table
sales_source_data in the following format :
Employee_id , week_id, sales_mon , sales_tus , sales_wed , sales_thur ,
sales_fri
We want to store these records in the sales_info table in a more typical relation format:
Employee_id , week, sales
Inset ALL
Into sales_info values ( employee_id , week_id , sales_mon)
Into sales_info values ( employee_id , week_id , sales_tue)
Into sales_info values ( employee_id , week_id , sales_wed)
Into sales_info values ( employee_id , week_id , sales_thur)
Into sales_info values ( employee_id , week_id , sales_fri)
Select Employee_id , week_id, sales_mon , sales_tue , sales_wed , sales_thur , sales_fri)
From sales_source_data;

Merge Statement
 Performs an UPDATE if the row exists , and an INSERT if it is a new row.
 Avoids separate updates , increase performance and ease of use
 Is useful in data warehousing application.

Eg : Merge into emp1 c


Using emp e
On (c.emp_id = e.emp_id)
When matched then
Update set
c.f_name = e.f_name,
c.l_name = e.l_name,
………..
c.dept_id = e.dept_id
When not matched then
Insert values (e.emp_id , e.f_name , e.l_name ….);
CUBE OPERATOR
Composite Column
 A composite column is a collection of column that are treated as a unit
Rollup (a , (b , c) , d)
 Use parenthesis within the GROUP BY clause to group column , so that are treated
as a unit while computing ROLLUP or CUBE operation.
 When used with ROLLUP or CUBE composite columns would require skipping
aggregation across certain levels.
TIME ZONE

CURRENT _DATE ----- returns the current date from the system, data type is DATE

CURRENT _TIME STAMP ---- returns the current timestamp from the system, data
type is TIMESTAMP WITH TIME ZONE

LOCAL_TIMESTAMP -- returns the current timestamp from the user session , data
type is TIMESTAMP

Difference b/w LOCALTIMESTAMP and CURRENT_TIMESTAMP returns a


TIMESTAMP value , where as CURRENT_TIMESTAMP returns a TIMESTAMP
WITH TIME ZONE .

Eg:
Alter session set nls_date_format = ‘dd-mon-yyyy hh24:mi:ss’;
Alter session set time_zone = ‘-5:0’;
DBTIMEZONE -- display the value of db time zone.
SESSIONTIMEZONE ---- display the value of session’s time zone.
Timestamp Data Type

TIMESTAMP -- contains the date time fields: year ,month ,day ,hour, minutes,
seconds and frictional seconds .

TIMESTAMP WITH TIME ZONE --- contains the date time fields: year ,month
,day ,hour, minutes, seconds, Timezone_hour and Timezone_minute and frictional
seconds .

TIMESTAMP WITH LOCAL TIME ZONE -- contains same as the TIMESTAMP


data type , except that the data is normalized to db time zone when stored and adjust to
match the client’s time zone when retrieved.

INTERVAL Data Type - it is used to store the difference b/w two datatime values.

INTERVAL YEAR (year precision) TO MONTH – used to store a period of time in


years and months where year precision is the number of digits in the year datetime
filed. The acceptance value are 0 to 9. the default is 6

Eg: ‘312-2’ assigned to INTERVAL YAER(3) TO MONTH


Indicate an interval of 312 years and 2 months

Create table t1 (p_id, w_time INTERVAL YEAR(3) TO MONTH);

Insert into t1 values (1 , interval ‘8’ month);


Insert into t1 values (2 , interval ‘200-1’);
Insert into t1 values (1 , interval ‘8’ year);

INTERVAL DAY (day precision) TO SECOND (fractional_seconds_precision)-- –


used to store a period of time in days,hours and seconds where day precision is the max
number of digits in the DAY datetime field(acceptance value are 0 to 9. the default is
2). And the fractional _seconds_precision is number of digit in the frictional part of the
SECONDS field. The acceptance value are 0 to 9. the default is 6

Eg: interval ‘6 03:30:10 ‘ day to second


Indicate an interval of 6 days 3 hours 30 minutes and 16 seconds.

EXTRACT ---- the extract expression extracts and returns the values of a specified
datatime or interval value expression. We can extract only following values by using
extract function
Select extract ([year] [month] [day] [hour] [minute] [second]
[timezone_hour] [timezone_minutes]
[timezone_region] [timezone_abbr]
From [datatime_value_expression] [interval_value_expression] );

Note : abbr -- time zone abbreviation.


TZ_OFFSET -- this function returns the time zone offset corresponding to the value.
Eg: select tz_offset ( ‘us/eastern’) from dual;

Select * from v$timezone_names ; (listing for all valid time zone)

TIMESTAMP conversion Using FROM_TZ --- by this function a TIMESTAMP


value convert in to TIMESTAMP WITH TIME ZONE value.

Eg:

TIMESTAMP conversion Using TO_ TIMESTAMP -- by this function a string of


CHAR, VARCHAR2, NCHAR or NVARCHAR2 data type converts in to
TIMESTAMP data type.

TIMESTAMP conversion Using TO_ TIMESTAMP_TZ - by this function a string


of CHAR, VARCHAR2, NCHAR or NVARCHAR2 data type converts in to
TIMESTAMP WITH TIME ZONE data type.
TIME INTERVAL CONVERSION WITH TO_YMINTERVAL &
TO_DSINTERVAL

TO_YMINTERVAL - - convert a character string of CHAR, VARCHAR2,NCHAR2


OR NVARCHAR2 data type to INTERVAL YEAR TO MONTH type.
TO_DSINTERVAL - - convert a character string of CHAR, VARCHAR2,NCHAR2
OR NVARCHAR2 data type to INTERVAL DAY TO SECOND type.

Multiple-Column Subqueries

1. pairwise comparison subquery --

eg : display the details of emp who are managed by the same manager and
work in the same department as employees with the first name of “John”
select emp_id , manager_id , department_id from emp
where (manager_id , department_id) in
(select manager_id , department_id from emp
Where f_name = ‘John’)
And f_name <> ‘John’ ;
2. NonPairwise Comparison subquery --

Eg: display the details of emp who are managed by the same manager
department as employees with the first name of “John” and work in the same
department as employees with the first name of “John”.

select emp_id , manager_id , department_id from emp


where manager_id in (select manager_id from emp
Where f_name = ‘John’)
And department_id in (select department_id from emp
Where f_name = ‘John’)
And f_name <> ‘John’ ;
Scalar Subquery Expression - return exactly one column value from one row
it can be used in condition and expression part of
DECODE and CASE , all clause of select except GROUP BY

eg : select emp_id , last_name


(case
When dept_id = (select dept_id from dept
Where loc_id=1800)
Then ‘Canada’ else ‘USA’) location
From emp;

Correlated Subquery - the oracle server performs a correlated subquery when the
subquery references a column from a table referred to in the parent statement. A
correlated subquery is evaluated once for each row processed by the parent statement.
the parent statement can be select, update, delete statement.
Execution: Get a candidate row (fetch by the outer query).
 Execute the inner query using the value of candidate row.
 Use the values resulting from the inner query to qualify
or disqualify the candidate.
 Repeat until no candidate row remains.

Eg : find all employees who earn morn then the avg salary in the dept.

Select l_name, sal , dept_id from emp e


Where sal > (select avg (sal) from emp
Where dept_id = e.dept_id);

Display details of those employees who have changed jobs at least twice.

Select e.empid , l_name , e.job_id from emp e


Where 2<= ( select count(*) from job_history
Where emp_id = e.emp_id);

Using the EXISTS Operator

 The EXISTS operator tests for existence of rows in the results set of the
subquery.
 If a subquery row value is found :
The search does not continue in the inner query.
The condition is flagged TRUE.
 If a subquery row value is not found :
The condition is flagged FLASE.
The search continues in the inner query.

Eg: find employees Who have at least one person reporting to them
select emp_id , l_name , job_id , dept_id from emp e
Where exists ( select ‘X’ from emp where manager_id= e.emp_id);

Alternative query - select emp_id , l_name , job_id , dept_id from emp


Where emp_id in (select manager_id from emp);
Find all departments that do not have any employees

Select dept_id,dept_name from dept d


Where not exists (select ‘X’ from emp where dept_id = d.dept_id);

Alternative query- select dept_id,dept_name from dept


Where dept_id not in (select dept_id from emp);

Correlated update

Eg: update emp16 e


Set dept_name = (select dept_name from dept d where e.dept_id=d.dept_id);
Eg: using the WITH clause write a query to display the department name and total
salaries for those departments whose total salary us grater than the average salary
across departments.

Вам также может понравиться