SQL Modified Notes
SQL Modified Notes
i integration
g grid
c cloud
java frontend
other db techs
sql server
sybase
mongo db
db2 .. etc
Relational Operators
******************
= <> !=
<
>
<=
>=
in not in
like not like
between not between
all
any
is null is not null
select
column(s)
from
table name
where
condition
order by
asc/desc -- last
case manipulation
upper
lower
initcap
character manipulation
* * **************** * *
instr
substr
length
replace
translate
reverse
trim
ltrim
rtrim
lpad
rpad
length 1 - 1 - input
purpose : to count the no of letters
eg : select first_name , length(first_name) from employees;
select length('Hermann') from dual;
reverse 1 - 1 - input
purpose : to get the mirror of the given string
eg : select first_name , reverse(first_name) from employees;
replace 3 - 1 - input 2 - to be replaced 3 - replacement string ( optional)
purpose : to change a word by word
eg : select replace('greens tech','tech','technologys') from dual;
Number functions
**************
Round
Trunc
Mod
Ceil
Floor
Abs
Sign
round - 1 checks the decimal whether 5 or > 5 => will rounding off
eg : select round(42.56) , round(85.86) , round(78.49) from dual;
as - column alias
date functions
************
add_months--select add_months(sysdate,2) from dual;
months_between---select months_between('01-oct-2017','01-may-2017') as output from
dual;
next_day---select next_day(sysdate,'monday') from dual;
last_day--select last_day('09-feb-2018') from dual;
Oracle
format - 'dd-mon-yyyy'
general functions
***************
distinct / unique
greatest
least
concat ||
case
decode
CASE and DECODE --Both are used to implement the if/else functionality.
--------------- Case is the extended the version of decode.
Decode we can able to do only equality function
case we can do equality and non equality functions.
1 SCOTT 85 P
2 ALLEN 30 F
3 SMITH 45 P
4 ADAMS 25 F
5 JAMES 55 NULL
select s_no,
s_name,
s_result,
DECODE(s_result,'P','PASS','F','FAIL','RESULT NOT AVAILABLE')AS result
from student_tab;
select s_no,
s_name,
s_mark,
s_result,
CASE s_result
WHEN 'P' then 'PASS'
WHEN 'F' then 'FAIL'
ELSE 'RESULT NOT AVAILABLE'
END
AS result from student_tab;
select s_no,
s_name,
s_mark,
s_result
CASE
WHEN s_result = 'P' and s_mark >=60 then 'PASS = FIRST CLASS'
WHEN s_result = 'P' and s_makr < 60 then 'PASS = SECOND CLASS'
WHEN s_result = 'F' then 'FAIL'
ELSE 'RESULT NOT AVAILABLE'
END AS RESULT
FROM student_tab;
-----------------------------------------------------------------------------------
---------------------------
Null functions => null is not equal to anything. you can not compare anything
with null. null is null
Conversion Functions
********************
=================================================================
create
alter
truncate
rename
drop
DATA TYPES:-
---------------
number
char 2000
varchar / varchar2 4000
date
timestamp-- (date & time)
long--(can store string upto 2gigabytes)
clob char large object(can store upto 128 terabytes of char data)
blob binary large object(can store upto 128 terabytes of binary data)
bfile path - outside
char(3) varchar(3)
sai sai
a hi
on delete cascade - parent table delete then child table also get deleted.
on delete null - parent table data deleted means child table data become null.
on delete update- when parent table get updated child table also get upated.
* Question: Need to add values in column only with data 'yes' and null values
should not get insert into column? (note:already existing data is there)
ANS: ALTER TABLE ct1 add constraint ctn check(a = 'yes')novalidate; -- to update
only 'yes' values.
ANS: ALTER TABLE ct1 modify a not null novalidate; -- to avoid null values.
6 operations
1. adding a column
alter table wwe add bb date;
1.adding a column
alter table wwe add cc varchar(10);
2.droping a column
alter table wwe drop column bb;
3.adding a constraint
alter table wwe add constraint ww1 primary key(aa);
4.droping a constraint
alter table wwe drop constraint ww1;
5.renaming a column
alter table wwe rename column cc to bb;
6.modifying a datatype
alter table wwe modify bb date;
insert
update
delete
merge
merge
*******
omr
id name fee
101 sai 5000
102 ram 5000
tam
101 sai 4500 u
i
*grant
*revoke
create user tbbm identified by abc;
select * from all_users;
grant create session to tbbm;
grant select on wwf to tbbm;
select * from hr.wwf;
grant insert on wwf to tbbm;
grant delete on wwf to tbbm;
grant all on wwf to tbbm;
revoke all on wwf from tbbm;
*Commit
*Rollback
*save point.
Example:-
savepoint sp1;
delete from emp where employee_id <110;
savepoint sp2;
delete from emp where employee_id <120;
savepoint sp3;
delete from emp where employee_id <130;
savepoint sp4;
rollback to sp2;
commit;
=================================================================
Virtual column(Virtual column is a table column whose values is automatically
computed using other columns values,
The values of the virtual column are not stored in data base,their values were
derived rather being stored on disc)
=================================================================
Set Operators(set operators combine the results of two queries into a single
result,
queries containing set operators are called compound queries)
************
union => removes duplicates ,(displayes non duplicate values) asc
union all => it displays results as it is in the table
intersect => common values
minus => value in first query not in second query it will compare on first table
values if rendu irukum means delete compare only on first table.
Rules
1.no of columns should be matched
2.data type should be matched
3.execution order can be changed by using ( and )--open and close brases.
union
*****
select a from t1
union
select b from t2;
union all
********
select b from t2
union all
select a from t1;
intersect
********
select a from t1
intersect
select b from t2;
minus
******
select a from t1
minus
select b from t2;
select b from t2
minus
select a from t1;
task
****
select b from t2
minus
select a from t1
union all
select b from t2
union
select a from t1;
select b from t2
minus
(select a from t1
union all
select b from t2)
union
select a from t1;
=================================================================
=================================================================
Analytical Functions
******************
Rank()
Dense_rank()
row_number()
lead
lag
listagg -- 11g
select * from(
select first_name , salary ,department_id,dense_rank() over(order by salary desc)
as rnk from employees)
where rnk = 3;
with abcde as
(select first_name , salary ,department_id,dense_rank() over(order by salary desc)
as rnk from employees)
select * from abcde where rnk=3;
with e as(
select first_name , salary , dense_rank() over(order by salary desc) as rnk from
employees)
select * from e where rnk = 1;
with s as(
select first_name , department_id , salary ,
dense_rank() over(partition by department_id order by salary desc) as rnk from
employees)
select * from s where rnk=1;
=================================================================
Pseudo columns
*************
sysdate / current_date
systimestamp
user
uid
rownum
rowid
level
nextval
currval
Dual : Oracle predefined dummy table (Or) One row one column table
select level from dual connect by level <= 100; -- to print 1 to 100
create sequence sq1 start with 101 increment by 1 max value 500;
===================================================================================
=====
Group functions => This funcion will group the rows and fetch one row for each
group.
max
min
sum
avg
count
select
column name
from
table name
where
conditions
group by
add columns + grp fun 515213
having
grp fun with condition
order by
asc/desc
=================================================================
sql plus commands
===============
clear screen/clear scr/cl scr
set pagesize => how many records to be displayed in each page
set linesize => how many char to be printed in each line
@ => @desktop\testomr.txt
set heading on => columns to be displyed ?
set heading off => columns not to be displayed ?
set feedback on => whether acknowledgement required ?
set feedback off => or not ?
set timing on => time taken to execute the query
set timing off => to disable
set verify on => to display old and new
set verify off => to remove old and new
define => to change value of constant variable
undefine => to reset the value of constant variable
ed => edit the query .. save .. close then give /
ttitle ' hi '
btitle ' bye '
& => substitution variable
/&& => constant
/ => last executed statement
spool => spool desktop\test.txt ....... spool off
show user => to display the current user
exit/quit => to quit the session
***********************************************************************************
***********
sql loader => bulk loader utility(Sql loader is a utility provided by oracle to
load data from external files into database)
Files which associated with sql loader are :- (data file,control file,log file,bad
file,discard file)
step 1 : data preparation
open a notepad
cid,cname,fees
10,sql,4500
20,plsql,3500
30,java,5000
save as (select all files) => 1.csv (comma separated value file)
open a notpad
load data infile 'desktop\1.csv'
append into table course
fields terminated by ","
(cid,cname,fees)
**********************************************************************
views => virtual table / only query will be stored / does not occupy memory in db
DML-possible in simple view.
View is just a named query.it doesn't store anything.actually data comes from the
base table.
No need to refresh. Since the data is directly fetched from base table.
Index not possible in view,because there will be no data in view only query will be
stored.
we can create view for not create table by creating FORCE VIEW
types of view
retriction methods
****************
with read only-- no data manipulation allowed in any condition, only selects are
allowed against the views.
with check option--row insertion allowed based on some condition. it used for
restricted DML operations.
l
create or replace view testv2 as select * from t2 with read only;
create or replace view testv3 as select * from t2 where b < 5 with check option;
Complex view
************
functions
expression
group function
analytical function
dictionary table
sub query .... etc
create or replace view testv4 as select upper(first_name) as fname
from employees;
****************************************************************************
execute dbms_mview.refresh('mvw','c');
refresh methods
************ **
complete
fast
force
types of joins
************
inner join => matching records
left outer join => matching of both , unmatching of left table
right outer join => matching of both , unmatching of right table
full outer join => matching and unmatching of both tables
self join => joining table within itself
cross join => cartesian poduct , no of rows in first table * no of rows in
second table
drop table students purge;
drop table course purge;
create table students(sid number, sname varchar(50), cid number) ;
create table course(cid number, cname varchar(50)) ;
sname cname
neena oracle
alex java
rupa c++
kiran unix
(or)
(or)
sname cname
neena oracle
alex java
rupa c++
kiran unix
raju
(or)
(or)
(or)
(or)
sname cname
neena oracle
alex java
rupa c++
kiran unix
linux
rpa
python
**********************************************************************
execute dbms_mview.refresh('mvw','c');
refresh methods
************ **
complete
fast
force
***********************************************************************************
***********
*) Difference between SQL Loader and External Table.
----------------------------------------------------
* SQL Loader is command line utility to load data from external files into
tables.
* The data from external file can be accessed as if it were in the database
table.
* SQL Loader can be loaded from any system having oracle client installed.
* In External table the files has to be accessed from system where DB is
installed via pre-defined directory object.
* SQL Loader Insert the data into target table.
* External table the data accessed via external table,can be joined with
other tables to fetch necessary data.
***********************************************************************************
**************
External Tables => data import and export process(External table is also another
method to read external file into oracele table)
*
***********************************************************************************
********* *
Index
why ? to retrieve the data faster but not all the times, to make performance
better.
decision maker - optimizer
when ? whenever a column frequently called in where clause
**********************************************************************
course
sql 10
plsql 10
java 10
unix 10
course
sql 100000 p1
plsql 100000 p2
java 100000 p3
unix 100000 p4
*list
*range
*hash
List Partitioning
*****************
create table course
(
cid number,
cname varchar(15)
)
partition by list(cname)
(
partition a1 values('sql'),
partition a2 values('plsql'),
partition a3 values('java'),
partition a4 values('unix'),
partition a5 values(default)
);
Range Partitioning
******************
create table emp1
(
eid number,
ename varchar(10),
phno number,
salary number
)
partition by range(salary)
interval(5000) --11g
(
partition b1 values less than (5000),
partition b2 values less than (10000),
partition b3 values less than (15000),
partition b4 values less than (20000)
);
* Any table can be partitioned except those table contains columns with LONG or
LONG RAW datatypes.
* However use tables containing columns with CLOB or CBLOG datatypes...
=================================================================
sub query => query that embeded within another query
========
single row sub query: if sub query returns only one row
******************
select first_name from employees where salary = (select min(salary) from
employees);
select * from
(select first_name , salary , dense_rank() over(order by salary desc) as rnk from
employees)
where rnk = 2;
select first_name ,
(select department_name from departments where departments.department_id =
employees.department_id) as depname ,
salary from employees;
nested sub query: sub query that embeded within another subquery
*****************
select * from employees where department_id in(select department_id from
departments where departments.department_id=employees.department_id and
location_id in(select location_id from locations where
locations.location_id=departments.location_id));
*****************************************************
1.syntactic check
if any mistake there in clauses
2.symantic check
if any mistake there in column name or table name
3.shared pool check ( library cache check )
for every select statement oracle will generate sqlid1
it will check the same sqlid is there in the library cache
if found then it will go for softparsing else optimizer will generate new
explainplan
select * from m;
select * from mn;