oracle notes

24

Click here to load reader

Upload: sachin-shukla

Post on 26-Jun-2015

601 views

Category:

Technology


1 download

DESCRIPTION

ORACLE NOTES

TRANSCRIPT

Page 1: ORACLE NOTES

1.create table/DESC/SELECT ->(I)Create table sachin (name varchar2(20), Rollno number(5), Address varchar2(20));

(II)to create a table from existing table or copy all the data from existing table-> Create table b As (select ename,sal ,empno from emp);

(III)copy only the structure of the table not the data->Create table bAs(select ename,sal ,empno from emp where empno=-1);Put any false condition at the end of the query.

(II)DESC tablename; OR DESCRIBE tablename;

4. insert values in the given tableinsert into a values(1,’sachin’,40000,’gzb’)

Insert into a(empno,ename) values(2,’sachin’);

Insert into a(no,name,sal) select empno,ename,sal from emp;

Insert into a values(‘&empno’,’&ename’,’&sal’);

* Insert into a (ename,empno) select &from tablename;Here tablename is asked by oracle at the time of running the query.

Insert into a(ename) select ename from &tablename;Oracle will ask the table name for inserting the data.

(III)FETCHIN THE VALUE FROM TABLE select * from tablename; OR Select name, code, address from tablename; OR Select * from &tablename; Enter value for tablename: emp

Page 2: ORACLE NOTES

OR SQL> select a ,b, a + b, a-b from maths;

A B A+B A-B---------- ---------- ---------- ---------- 10 10 20 0 20 30 50 -10

OR

SQL> select a,b,a+b as addition,a-b as subtraction from maths;

A B ADDITION SUBTRACTION---------- ---------- ---------- ----------- 10 10 20 0 20 30 50 -10NOTEif any airthmatic operation that includes a NULL value has NULL as a value. Null represent an irrelevant or unknown value.

5.COMMENT ON TABLE->

COMMENT ON TABLE tablename IS ‘writer ur comment’;

*6.comment on column-> COMMENT ON COLUMN tablename IS ‘write ur comment’;

select name /* it gives the name of employees*/ from sach;it is also a comment with in the query.

7.REMOVE COMMENT-> COMMENT ON TABLE/COLUMN tablename/columnname IS ‘’;

8.ALTER TABLE->

alter table sachinadd (address varchar2(20));

Alter table tablenamedrop column address;

alter table tablename Alter table sachinModify column modify (address varchar2(15));Drop constraint constraint_name;

Page 3: ORACLE NOTES

Use alter table to add columns or constraints to a table,change column datatypes,sizes and not null settings ,drop constraints ,change future storage allocation ,and update the data dictionary to show that a backup of the table occurred at the time the statement was executed.TO SHOW THE CONSTRAIN NAME -> SELECT * FROM USER_CONSTRAINTS;

9.RENAME rename tablename1 to tablename2;

10.drop table tablename;After drop we can not rollback and it will remove the table as well as data.IF THERE is any view exist related with the table then it wil becomes invalid.

11.truncate table tablename;Table wil exixt .after truncate we can not rollback it wil remove the data not the table.

12.UPDATE->UPDATE tablename Set sal=2000,mobile=9999999999 Where empno=22 or ename=’sachin’;This command only run for the date updation not for the column operations.

13.DELETE-> Delete from(optional) tablenameWhere empno=22;We rollback our data after delete.

14.ORDER BY--SELECT …. SELECT ……………ORDER BY EXPR ASC,….. ORDER BY EXPR DESC,….ORDER BY POSITION ASC ORDER BY POSITION DESCThe order by clause specifies the order in which to display the results of a query.expr. references one or more SELECT clause columns or FROM clause tables.Position is a number indicating the place of a colukmn in the SELECT clause.ASC OR DESC specify ascendin or descending order for the sort ;the default is ASC.

SQL> select ename,empno from emp order by empno desc;

ENAME EMPNO---------- ---------------MILLER 7934FORD 7902

Page 4: ORACLE NOTES

JAMES 7900ADAMS 7876TURNER 7844KING 7839SCOTT 7788CLARK 7782BLAKE 7698MARTIN 7654JONES 7566WARD 7521ALLEN 7499SMITH 7369NOTE=> ORDER BY cannot be used in subqueries of INSERT,UPDATE,CREATE TABLE OR CREATE VIEW STATEMENTS.An ORDRE BY cancels the effect of a connect by clause in the same statement.

15.GROUP BY and HAVINGSELECT LIST…..FROM TABLEWHERE CONDITION GROUP BY EXPR,EXPR2HAVING CONDITIONWith this clause ,SELECT computes one summary row for each group of selected rows.Every SELECT LIST EXPRESSION must either—(i)be a function or constant with no parameter,like SYSDATE;(ii)contain a group function like SUM,COUNT OR MAX;(iii)match a GROUP BY expr

THE HAVING condition sets which GROUPBY groups appear in the result.

SQL> select deptno,job,sum(sal) from emp group by deptno,job;

DEPTNO JOB SUM(SAL)---------- --------- ---------- 10 CLERK 1300 10 MANAGER 2450 10 PRESIDENT 5000 20 ANALYST 6000 20 CLERK 1900 20 MANAGER 2975 30 CLERK 950 30 MANAGER 2850 30 SALESMAN 5600

9 rows selected.

Page 5: ORACLE NOTES

16. CUBE operator

The CUBE operator is an additional switch in the GROUP BY clause in a SELECT statement. The CUBE operator can be applied to all aggregate functions including AVG, SUM, MAX, MIN and COUNT. It is ued to produce results set that are typically used for cross-tabular reports. While ROLLUP produces only a fraction of possible subtotal combinations, CUBE produces subtotals for all possible combinations of groupings specified in the GROUP BY clause and a grand total.

The CUBE operator is used with an aggregate function to generate additional rows in a result set. Columns included in the GROUP BY clause are cross-referenced to produce a superset of groups. The aggregate function specified in the select list is applied to the groups to produce summary values for the additonal superaggregate rows. The number of extra groups in the results set is determined by the number of columns included in the GROUP BY clause.

SELECT department_id, job)id, SUM(salary)FROM employeesWHERE department_id < 60GROUP BY CUBE(department_id,Job_id)

MATHEMATICAL FUNCTIONS SQL> select distinct deptno from emp;

DEPTNO---------- 10 20 30

SQL> select max(sal) from emp;

MAX(SAL)---------- 5000

SQL> select min(sal) from emp;

MIN(SAL)---------- 800

SQL> select count(*) from emp;

COUNT(*)

Page 6: ORACLE NOTES

---------- 14

SQL> select * from sam;

SALARY COMMISION---------- ---------- 123.423 6665.64566 545.3444 234.534 34.43 645.3355

SQL> select round(salary,2),round(commision,2) from sam;

ROUND(SALARY,2) ROUND(COMMISION,2)--------------- ------------------ 123.42 6665.65 545.34 234.53 34.43 645.34

SQL> select trunc(salary,3),trunc(commision,3) from sam;

TRUNC(SALARY,3) TRUNC(COMMISION,3)--------------- ------------------ 123.423 6665.645 545.344 234.534 34.43 645.335

OPERATORS->(I) Airthmatic and character operators->

( ) ->select (x+y) +- ->….where sal= - 400 */ -> select sal*100 +- -> select (sal-comm)

(II) we can write a line with the help of database like-- select 'contact '||ename||' gets '||'$'||sal||' per month' from emp where empno=7369SQL> /

contact SMITH gets $800 per month (III) Logical operators->

NOT->Reverse the result of a logical expression .Exception:NOT(NULL)evaluates to null.Select……..where NOT (bal=0)AND->Returns TRUE if all conditions are TRUE…………….where a=1 AND b=100;

Page 7: ORACLE NOTES

SQL> SELECT ENAME FROM EMP WHERE DEPTNO=20 AND SAL>500;

ENAME----------SMITHJONESSCOTTADAMSFORD

OR->Returns TRUE if any of the conditions is TRUE…………………..where a is null or b is null

(IV) tablename.*--Selects all columns from the table in a query(V) ALLReturns duplicate values from a query or aggregation(VI) DISTINCTEliminates duplicate values from the result of a query .default is

ALL.(VII) (+)-THE PRECEDING COLUMN IS THE OUTER JOIN COLUMN IN A

JOIN.(VIII) INTERSECT->combines queries to return all distinct rows by every

individual query.(IX) UNION combines queries to return all distinct rows returned by any

individual query.(X) MINUScombines queries to return all distinct rows returned by the first

query buy not the second.(XI) UNION ALLLike union but duplicate as it is come.

Note->number of column and types of columns must be same (XI) >ALL more than the max (XII). <ALL Less than the min (xIII) >ANY MORE THAN THE MIN (XIV) <ANY LESS THAN THE MAX (XV) IN min

( XVI ) LIKE-> the sql like operator matches part of the char string to part of the ‘pattern’ string.you can use two “wild word” matchin character in the ‘pattern’:

% matches zero or more characters(called wildcard) _ matches exactally one character(called aposition marker) NoteString must be in quotes.and it is case sensitive.Example->(TO FIND EMPLOYEES WHO HAVE NAMES BEGINNING WITH ‘A’) Select ename ,sal,mgr from emp Where ename like ‘A%’; ANS-> ASHUTOSH , AMAR

(TO FIND EMPLOYEES WHO HAVE HYPHENATED NAMES)Select ename from emp

Page 8: ORACLE NOTES

Where ename like ‘%-%’;

SQL> select ename,empno from emp where 2 empno like '79%';

ENAME EMPNO---------- ----------JAMES 7900FORD 7902MILLER 7934

SQRTSQL> SELECT SQRT(625) FROM DUAL;

SQRT(625)---------- 25NOTEoracle does not find out the square root of the negative number because it will give the imaginary number as ans. and oracle does not support it, so it will giver an error.

LENGTH SQL> SELECT LENGTH ('SACHIN') FROM DUAL;

LENGTH('SACHIN')---------------- 6

SQL> SELECT LENGTH('SACHIN SHUKLA') FROM DUAL;

LENGTH('SACHINSHUKLA')---------------------- 13

SQL> select name from sach order by length(name);

NAME--------------------SURWARDFORDKINGSMITHJONESCLARKADAMSJAMES

Page 9: ORACLE NOTES

SCOTTBLAKESACHINMILLERTURNERMARTIN

SQL> ED;Wrote file afiedt.buf

1* SELECT LENGTH ('SACHIN') FROM DUALSQL> SELECT LPAD('SACHIN',8,'#') FROM DUAL;

LPAD('SA--------##SACHIN

SQL> SELECT RPAD('SACHIN',8,'@') FROM DUAL;

RPAD('SA--------SACHIN@@

17.TO CHANGE THE PASSWORD OF ORACLE

SQL> GRANT CONNECT TO SCOTT IDENTIFIED BY TIGER;

Grant succeeded.

18.SET FEEDBACK OFF/ON/SHOW FROM THIS QUERY SQL WILL NOT DISPLAY THE NO OF ROWS SELECTED AT THE END OF OUTCOME(ANSWER).

SQL> SET FEEDBACK ON;SQL> SELECT ENAME FROM EMP ORDER BY ENAME;

ENAME----------ADAMSALLENBLAKECLARKFORDJAMESJONES

Page 10: ORACLE NOTES

KINGMARTINMILLERSCOTTSMITHTURNERWARD

14 rows selected.

SQL> SET FEEDBACK OFF;SQL> SELECT ENAME FROM EMP ORDER BY ENAME;

ENAME----------ADAMSALLENBLAKECLARKFORDJAMESJONESKINGMARTINMILLERSCOTTSMITHTURNERWARDSQL>SQL> SHOW FEEDBACK;FEEDBACK ON for 25 or more rows

19.NUMWIDTHthis means that all the number columns will be five digit wide.if you anticipate havig numbers with more than five digit numbers higher than five.individual column in the display wil set automatically or independentally.SQL> SHOW NUMWIDTH;numwidth 10SQL> SET NUMWIDTH 15;SQL> SHOW NUMWIDTH;numwidth 15

20.NULL AND NOT NULLSelect ename from emp where mgr is null and comm is null;KING

Page 11: ORACLE NOTES

SQL> SELECT ENAME FROM EMP WHERE COMM IS NOT NULL;

ENAME----------ALLENWARDMARTINTURNER

21.INSQL> SELECT * FROM CLASS;

NAME SECTI-------------------- -----SACHIN BSURNEDRA BNAVJEET AKAMLESH AGAGAN B

SSQL> SELECT NAME FROM CLASS WHERE SECTION IN('A');

NAME--------------------NAVJEETKAMLESH

2 rows selected.SQL> SELECT NAME FROM CLASS WHERE SECTION NOT IN('B');

NAME--------------------NAVJEETKAMLESH

22.BETWEENSQL> select ename from emp where sal between 1000 and 2000;

ENAME----------ALLENWARDMARTINTURNERADAMSMILLER

Page 12: ORACLE NOTES

6 rows selected. SELECT ENAME FROM EMP WHERE DEPTNO=20 AND SAL BETWEEN 1000 AND 2000SQL> /

ENAME----------ADAMS

23.EDIT/DELIf we want to edit the command at the run time and a error is come at the given 2nd line or any other line then if we press the DEL KEY,SO it will delete that line which was having that error.SQL> select ename from emp 2 wheer ename='SMITH';wheer ename='SMITH' *ERROR at line 2:ORA-00933: SQL command not properly endedSQL> DEL;SQL> ED;Wrote file afiedt.buf

1* select ename from empSQL> ED;Wrote file afiedt.buf

1 select ename from emp 2* WHERE ENAME='SMITH'SQL> /

ENAME----------SMITH

1 row selected. For multiline delete we can write the command as- DEL 3 7;

It means that sql have to delete the lines between 3 to 7. If we want to delete the particular line then we can write it asdel 12;

24.INPUT/APPENDWe can edit out command at run time with these keywords. With the input keyword->SQL> select ename,empno from emp;

ENAME EMPNO

Page 13: ORACLE NOTES

---------- ----------SMITH 7369ALLEN 7499WARD 7521JONES 7566MARTIN 7654BLAKE 7698CLARK 7782SCOTT 7788KING 7839TURNER 7844ADAMS 7876

ENAME EMPNO---------- ----------JAMES 7900FORD 7902MILLER 7934

14 rows selected.

SQL> ed;Wrote file afiedt.buf

1* select ename,empno from empSQL> input where ename='SMITH';SQL> /

ENAME EMPNO---------- ----------SMITH 7369

And with the append keyword we have to just writer out text after the append keyword and give two spaces after the append command->SQL> ED;Wrote file afiedt.buf

1* select ename,empno from empSQL> APPEND WHERE ENAME='SMITH'; 1* select ename,empno from emp WHERE ENAME='SMITH'SQL> /

ENAME EMPNO---------- ----------SMITH 7369

Page 14: ORACLE NOTES

25.SAVEwe can save our last command as a file.we have to just write a command->SQL> select max(sal) from emp;

MAX(SAL)---------- 5000

SQL> save sach.sql;Created file sach.sql

And this file will save at the position c:/oracle/bin.u can see it’s location.

26.STORE SETTINGu can store the setting of ur oracle in a particular file name SQL> store set my_setting.sql create;Created file my_setting.sql

If u want to store another setting with the same name then use replace keyword at createSQL> store set my_setting.sql replace;Wrote file my_setting.sqlAnd these files are stored at c:/oracle/bin

27.STRING CONCATINATE STRING || STRING

SQL> SELECT UPPER('Mr..')||LOWER(ENAME) FROM EMP;UPPER('MR.')|-------------MR.smithMR.allenMR.wardMR.jonesMR.martinMR.blakeMR.clarkMR.scottMR.kingMR.turnerMR.adamsMR.jamesMR.fordMR.miller

14 rows selected.

SQL> SELECT 'SACHIN'||','||UPPER(ENAME) FROM EMP;

Page 15: ORACLE NOTES

'SACHIN'||','||UP-----------------SACHIN,SMITHSACHIN,ALLENSACHIN,WARDSACHIN,JONESSACHIN,MARTINSACHIN,BLAKESACHIN,CLARKSACHIN,SCOTTSACHIN,KINGSACHIN,TURNERSACHIN,ADAMSSACHIN,JAMESSACHIN,FORDSACHIN,MILLERNOTENOTICE THE NAME OF THE COLUMN NAME.AND WE CAN USE THE OTHER QUERY FOR THE RESULT LIIKE->Select concat(ename,empno) from emp is equivalent to select ename||empno from emp;

28.RPAD/LPADSQL> SELECT RPAD(ENAME,20,'.'),EMPNO FROM EMP

RPAD(ENAME,20,'.') EMPNO-------------------- ----------SMITH............... 7369ALLEN............... 7499WARD................ 7521JONES............... 7566MARTIN.............. 7654BLAKE............... 7698CLARK............... 7782SCOTT............... 7788KING................ 7839TURNER.............. 7844ADAMS............... 7876JAMES............... 7900FORD................ 7902MILLER.............. 7934

14 rows selected.

SQL> SELECT LPAD(ENAME,20,'.'),EMPNO FROM EMP

LPAD(ENAME,20,'.') EMPNO-------------------- ----------

Page 16: ORACLE NOTES

...............SMITH 7369

...............ALLEN 7499

................WARD 7521

...............JONES 7566

..............MARTIN 7654

...............BLAKE 7698

...............CLARK 7782

...............SCOTT 7788

................KING 7839

..............TURNER 7844

...............ADAMS 7876

...............JAMES 7900

................FORD 7902

..............MILLER 7934

SQL> SELECT LPAD(ENAME,20),EMPNO FROM EMP;

LPAD(ENAME,20) EMPNO-------------------- ---------- SMITH 7369 ALLEN 7499 WARD 7521 JONES 7566 MARTIN 7654 BLAKE 7698 CLARK 7782 SCOTT 7788 KING 7839 TURNER 7844 ADAMS 7876 JAMES 7900 FORD 7902 MILLER 7934

29.UPPER/LOWER/INTICAPSQL> SELECT ENAME,UPPER(ENAME),LOWER(ENAME),INITCAP(ENAME) FROM EMP;

ENAME UPPER(ENAM LOWER(ENAM INITCAP(EN---------- ---------- ---------- ----------SMITH SMITH smith SmithALLEN ALLEN allen AllenWARD WARD ward WardJONES JONES jones JonesMARTIN MARTIN martin MartinBLAKE BLAKE blake Blake

Page 17: ORACLE NOTES

CLARK CLARK clark ClarkSCOTT SCOTT scott ScottKING KING king KingTURNER TURNER turner TurnerADAMS ADAMS adams AdamsJAMES JAMES james JamesFORD FORD ford FordMILLER MILLER miller Miller

30.SUBSTRING(SUBSTR)SQL> SELECT SUBSTR(NAME,4,6) FROM RAM;

SUBSTR------HIN SHENDRAAN AGRESH MINOTE->here 4 is the initial point and we have to go upto 6th place from 4th position.

SQL> SELECT LPAD(SUBSTR(NAME,4,6),20,'.') FROM RAM;

LPAD(SUBSTR(NAME,4,6--------------------..............HIN SH..............ENDRA..............AN AGR..............ESH MINOTE->SUBSTR(4,15) IS EQUAL TO SUBSTR(4).

31.FIND LETTER IN THE STRING(INSTR) SQL> SELECT NAME,INSTR(NAME,'S') FROM RAM;

NAME INSTR(NAME,'S')------------------------------ ---------------SACHIN SHUKLA 1SURENDRA SINGH; 1GAGAN AGRAWAL; 0RUPESH MISHRA 5

After find the first one letter in the given string if we want to find the second location of that letter in the string then we have to run the query which is given below

SQL> SELECT NAME,INSTR(NAME,'S',1,2) FROM RAM;

Page 18: ORACLE NOTES

NAME INSTR(NAME,'S',1,2)------------------------------ -------------------SACHIN SHUKLA 8SURENDRA SINGH; 10GAGAN AGRAWAL; 0RUPESH MISHRA 10

SQL> SELECT NAME, INSTR(NAME,'SHUKLA') FROM RAM;

NAME INSTR(NAME,'SHUKLA')------------------------------ --------------------SACHIN SHUKLA 8SURENDRA SINGH; 0GAGAN AGRAWAL; 0RUPESH MISHRA 0Note we can also add or subtract the numbers form the instr function to change the positon of the cursor.(instr(author,’a’) +-1);

32.SOUNDEX(FIND THE ENTRIES ,SOUNDS LIKE THE WORD)

SQL> select * from emp where soundex(ename)=soundex('alln');

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO---------- ---------- --------- ---------- --------- ---------- ---------- ---------- 7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30NOTE->it compares the word’s pronuntiation in quotations and find the word’s like that.

33.NULLBeforeSQL> select ename,comm from emp;

ENAME COMM---------- ----------SMITHALLEN 300WARD 500JONESMARTIN 1400BLAKECLARKSCOTTKINGTURNER 0

Page 19: ORACLE NOTES

ADAMSJAMESFORDMILLER

If we want to put some values at the null place of the commission column then we have to write down the following query.(value=500)After

SQL> select ename,nvl(comm,500) from emp;

ENAME NVL(COMM,500)---------- -------------SMITH 500ALLEN 300WARD 500JONES 500MARTIN 1400BLAKE 500CLARK 500SCOTT 500KING 500TURNER 0ADAMS 500JAMES 500FORD 500MILLER 500

If u want to take the average of the commission column when it was having the null points then we have to use the following query(here null will not make problem to find the correct answer it will choose only the values)

SQL> select avg(comm) from emp;

AVG(COMM)---------- 550