Академический Документы
Профессиональный Документы
Культура Документы
Commit rollback
Savepoint TRANSACTION CONTROL
For concatenate
Select last_name || job_is………
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
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’)
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
Any column or expression in the select list that is not an aggregate function must be in
the group clause
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.
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
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
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);
Insert
Update
Update emp
Set dept_id=70
Where emp_id=113;
Delete
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.
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
Alter statement --- add new column, modify an existing column, define a default
value & drop a column.
VIEW
COMPLEX VIEW
SEQUENCES
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.
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.
INDEX
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
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.
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.
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.
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;
Object Privileges
Add a new column, modify an existing column, define a default value for the new
column, and drop a column
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.
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
On delete cascade
Dropping a constraints
Cascading Constraints
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 .
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
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 ;
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.
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
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 .
INTERVAL Data Type - it is used to store the difference b/w two datatime values.
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] );
Eg:
Multiple-Column Subqueries
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”.
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.
Display details of those employees who have changed jobs at least twice.
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);
Correlated update