Oracle

Ankita Kachwaha

Data Type
 CHAR(size)
Fixed length character data of length size bytes. This should be used for fixed length data.

 VARCHAR2(size)/VARCHAR(size)
Variable length character string having maximum length size bytes.

 DATE
Use to represent date and time. Standard format is DD-MON-YY

NUMBER(p,s)
Variable-length number; precision is the maximum number of digits (in front of and behind a decimal point, if used) that may be used for the number. The maximum precision supported is 38; scale is the maximum number of digits to the right of a decimal point (if used). If neither precision nor scale is specified, then a number with up to a precision and scale of 38 digits may be supplied

 

LONG
Use to store variable length character string upto 2 GB.

RAW / LONG RAW
Use to store binary data such as picture or image.

.Creating Table  CREATE TABLE <table name> (<colname1> <datatype>(<size>). …………………..). <colname1> <datatype>(<size>).

Example  Create table customer(cid number(5). account_no number(5) ). . name varchar2(20).

status VARCHAR2(20) DEFAULT 'Order pla ced' NOT NULL.Creating table with default values  CREATE TABLE myTable ( id INTEGER. . last_modified DATE DEFAULT SYSDATE ).

<expression2>.….Inserting data into table  INSERT INTO <table name> (<colname1>.…) values (<expression1>.). .<colname2>.

10112).name.).      .'ZOMBIE'. DEFAULT).trunc(sysdate). insert into Employee(ID.'J"a"mes') . cid) values(’lucky’. insert into employees(empno.bdate.account_no. Insert into customer(name.’lucky’.init.10112. First_Name) values('08'. INSERT INTO myTable (id) VALUES (1) .msal.ename.Examples  Insert into customer(cid.deptno) values (7001. Insert into customer values (101.0. 101.10112).’lucky’.'ZZ'.account_no) values(101.

* from <table name>.  Select  Select . * from customer.Viewing data in the tables  Select <col name1> to <col name N> from <table name>.

from <table name>. .Selected columns and all rows  Select <colname1>.<colname2>. account_no from customer.  Select name.…….

 Select . * from customer where name=‘lucky’.Selected rows and all columns  Select * from <table name> where <condition>.

account_no from customer where name=‘lucky’.Selected columns and selected rows  Select <colname1>.. <colname2>….  Select . From <table name> where <condition>.

From <table name>. distinct * from <table name>.Eliminating duplicate rows  Select distinct <colname1>..  Select  Select . distinct occupation from customer. <colname2>..

<colname2>.    .. <[sort order]>. state FROM employees ORDER BY state ASC. city DESC. city.Sorting data in table  Select * from <table name> order by <colname1>.. Select * from customer order by name desc. au_lname. SELECT au_fname. Select * from customer order by name.

last_name FROM employee ORDER BY 2. .Use a column position number in the ORDER BY clause  SELECT id. first_name.

name from customer.<colname2>.<colname>) as select <colname1>.… from <old table name>. table employee (eid.Creating table from a table  Create table <new table name> (<colname>.name) as select cid.account_no.  Create . account_no.

name. account_no from customer where name=‘lucky’. into employee select cid.<col2>.Inserting data from another table  Insert into <table name> select <col1>. … from <table name> where <condition>.  Insert .

Delete from customer. Delete from <table name> where <condition>.    . Delete from customer where name=‘lucky’.Delete operation  Delete from <table name>.

Update customer set name=‘sam’ where name=‘lucky’. <colname2>=<expression2> where condition>.Updating table content  Update <table name> set <colname1>=<expression1>. Update customer set name=‘sam’ .    . UPDATE myTable SET id = DEFAULT.

<new col name> <data type> (<size>). alter table registrations add (entered_by number(4) default 7839).……).   . Alter table customer add(occupation varchar2(20)).Modifying table structure adding new column  Alter table <table name> add(<new col name> <data type> (<size>).

 Alter . table customer drop column occupation.Drop a column from table  Alter table <table name> drop column <column name>.

Modifying existing column  Alter table <table name> modify (<colname> <new data type> (<new size>)). Cant change name of column Size cant be decrease if data exist Data type can be changed only if column is empty    .

.1.Changing the Default Value of a Column  ALTER TABLE myTable MODIFY last_modified DEFAULT SYSDATE .

 Rename customer to cust.Renaming table  Rename <old table name > to <new table name>. .

between truncate and delete  Difference . table customer.Truncating tables  Truncate  Truncate table <table name>.

. table customer.Destroying tables  Drop  Drop table <table name>.

customer. data type. will display column name. size and constraint. .Displaying table structure  Describe  Describe  This <table name>.

.Finding out tables creating by user  Select * from tab.

Data constraint  These are the rules which are applied to data prior to it stored in the database table. the data which satisfy all the rules will be stored in data base for future analysis.  Only .

Type of data constraint  I/O constraint  Business rule constraint .

.Primary key  At column level <col name> <data type> (<size>) primary key table level primary key(col name.).  At . col name. .

name varchar2(20).Example  Create table customer(cid number(3) primary key. . acc_no number(5)). name varchar2(20).  Create table customer(cid number(3). acc_no number(5). primary key (cid)).

 Upto 16 columns can be combine in a composite primary key.Features of primary key  Do not allow duplicate values. .  Do not allow null values.  Primary key cant be long or long raw.

 Records of master table cannot be deleted if corresponding records in the detail table actually exist.Foreign key constraint A foreign key is a column whose values are derived from primary key or unique key of some other table. .  Records can’t be inserted into detail table if corresponding records in the master table do not exist.

.cid number(3) references customer (cid) on delete cascade).Foreign key defined at column level  <col name> <data type> (<size>) references <table name> [<col name>] [on delete cascade]/[on delete set null]  Create table account (acno number(5). bal number(6).

<col name)] [on delete cascade]/[on delete set null]. Create table account (acno number(5).  .<col name>.Foreign key defined at table level  Foreign key (<col name >[. bal number(6). foreign key (ac_cid) references customer (cid) on delete set null).…]) references <table name> [(col name). ac_cid number(3).

 Insert into employees values(10. create table employees ( empno NUMBER(4) primary key . mgr NUMBER(4) ) .  Alter table employees modify (mgr references employees ) .null).

class_no number(3) constraint c23 references class (class_no) ).User defined name to constraint  Constraint <contraint name> <constraint defination> table std (rno number (5) default 0 constraint new_const primary key.  Create .

erno number(5) unique).Unique key at column level  <col name> <datatype> (<size>) unique  Create table std (rno number(3). name varchar2(20). .

Unique key  Do not allow duplicate values multiple entries of null raw data type cant be unique.  Permit  Long/long .

table std (rno number(3) unique. name varchar2(20)). unique(erno)).Unique key at table level/column level  Create table std (rno number(3). name varchar2(20).  Create .

Business rule constraint  These are the rules which are determined by business manager and they vary from system to system. .

 In case of null oracle ignore unique.  Expression including null evaluate to null. foreign key and check constraint .  Null is not equivalent to 0 or empty string  Null can be inserted to column of any data type.Principles  Null value is used when actual value is not available or when a value is not meaningful.

Null value concept        Insert into std values(123. Null can’t be specified at table level. Select * from std where name is not null.’’. Create tabel std(rno number(3) primary key. Select * from std where name is null. name varchar2(20) not null). . Select * from std where name=‘’.null.90). Insert into std values(120.65).

per number(4.   . Create table std (rno number(3). name varchar2(20) default ‘abc’ check (name= upper (name))).check (name= upper (name))).Check constraint  <col name> <data type> (<size>) check(<logical expression>) Create table std (rno number(3).2). name varchar2(20) .

Constraint can also check that value of one column is less than another Like predicate can be also used   . create table departments ( deptno NUMBER(2) constraint D_PK primary key constraint D_DEPTNO_CHK check (mod(deptno.10) = 0) ).

Restriction on check  Condition must be Boolean expression and must evaluate to true or false. user sql  Condition  Condition functions. uid. cant be sub query or sequence cant include sysdate. .

user_constraints table  OWNER  CONSTRAINT_NAME  TABLE_NAME  CONSTRAINT_TYPE (P R U C)  SEARCH_CONDITION  R_OWNER  R_CONSTRAINT_NAME .

. constraint_name. Select owner. constraint_type from user_constraints where table_name=‘std’.

ALTER TABLE employee ADD CONSTRAINT reasonable_stock_date CHECK( start_date >= to_date('19000917'.  Alter table result add foreign key (rno) references std (rno).'YYYYMMDD') ).Adding constraint to existing table  Alter table std add primary key (rno). Alter table std add constraint c44 unique (name).   .

Drop constraint  Alter table std drop primary key. .  Alter table std drop constraint c44.

Arithmetic operators + * /  **  () .

1) FROM dual. 30 . SELECT 10 * (12 / 3 .

Relational operator >  >= <  <= =  != or <> .

Logical operator  And  Or  Not .

Examples
 Select  Select  Select

* from std where per>50 and per<60; * from std where per=50 or per=60; * from std not (per=60);

Range searching
 Select

* from emp where sal between 5000 and 8000;

 Select

empid, name from emp where sal not between 5000 and 7000

Pattern matching like predicate
% _

allow to match any string of any length

match single character

Examples  Select  Select  Select * from emp where name like ’a%a’. * from emp where name like ‘_d%e_ _’. . * from emp where name like ‘%n_’.

2. 1. The ESCAPE option specifies that the backslash character precedes any wildcard characters used with the LIKE operator. The underscore is then used in the text match.ESCAPE option If you perform a text match on the actual underscore or percent characters. you can use the ESCAPE option. The following example retrieves the employees whose name contains the string "_". 3. . The underscore is not treated as a wildcard character as would otherwise be the case.

Example  SELECT first_name FROM employee 2  WHERE first_name LIKE '%\_%' ESCAPE '\'. FIRST_NAME ---------J_mes  SELECT title_name FROM titles WHERE title_name LIKE '%!%%' ESCAPE '!'. .

 select *from   registrations where  evaluation  in (1. .3.70).2.30.In predicate  Select * from emp where deptno in(10.NULL).

70). .Not in predicate  Select * from emp where deptno not in(10.30.

   . DESCRIBE dual. Select sysdate from dual.  Name         Null?    Type  DUMMY                 VARCHAR2(1) Select 2*2 from dual.Dual  Dual is table owned by sys and it is part of data dictionary.

 Scalar function / single row function these function act only on one value at a time .Oracle functions  Group function / aggregate function these functions act on set of values.

Aggregate functions  Avg  Max  Min  Count  Sum .

Avg  Avg ( [distinct / all] <n>) avg (sal) from emp. avg ( distinct sal) from emp.  Select  Select .

 SQL> VARIABLE average_salary NUMBER. SQL> SQL> PRINT average_salary. SQL> SQL> UPDATE employee 2 SET salary = salary * 0. AVERAGE_SALARY -------------3053. 8 rows updated.75 3 RETURNING AVG (salary) INTO :average_salary.81875 .

 Select   select min(first_name) from emp. .Min  min ( [distinct / all] <exp>) min (sal) from emp.

 Select .Max  max ( [distinct / all] <exp>) max (sal) from emp.

count(*) from emp. .Count  Count  Select  Select ([distinct/all] <exp>) count (name) from emp.

Sum  Sum ([distinct/all] <exp>)  Select sum (bal) from account where cid=101. .

Median / standard deviation
 select MEDIAN(salary) from employee;  SELECT STDDEV(salary) FROM employ

ee;

You cannot use an aggregate function to limit rows in a WHERE clause
  SELECT city, AVG(salary)

FROM employee  WHERE AVG(salary) > 20; error

Incorrect Usage of Aggregate Function Calls
 When

your query contains an aggregate function, and selects columns not placed within an aggregate function, those columns must be placed in a GROUP BY clause.

 SELECT id, AVG(salary)

FROM employee; (error)

SELECT id. ABS(value) FROM myTable . value.Numeric functions  Abs select abs(-15) “absolute” from dual.

 select power(value. power(2.3).Power  Select power(3. 3) from myTable .3) from dual. power(-2.  select .2) from dual.

2 select ROUND(5.Round  Select round(15.1) ------------5. ROUND(5.19.75) from dual. ROUND(5.75.75) ----------6 SQL> select ROUND(5.8   . 1) from dual. 15.1) from dual.75.

2) ROUND(345.678.678.-2) ---------------- ----------------- ----------------          345.68               350               300 .678.678.2)           .-1)           .-1) ROUND(345.      round(345.678. ROUND(345. SQL> select round(345.-2)           from   dual.      round(345.678.

Sqrt  Select  sqrt(25) from dual. Exp  Select exp(5) from dual. SELECT id. . SQRT(value) FROM myTable. value.

extract( month from sysdate) from dual.  Select .Extract  Extract ([year/month/day/hour/minute/second] from date value) extract (year from date ‘07-02-2007’).

Least  Select least (10.5) from dual.  Select least (‘4’.5) from dual. ’17’) from dual. . ’17’) from dual.20.Greatest  Select greatest (10. ‘5’. ‘5’.20.  Select greatest (‘4’.

815.815.1).-2) from dual.Mod  Select mod (15. Trunc  Select trunc (125. 125.8 100 .7) from dual. trunc (125.

15) from dual. 14 .15) from dual. ceil (13.Floor  Select 24 floor (24. floor (13.8). 13 Ceil  Select 25 ceil (24.8).

---------. SIGN(-5) SIGN(5) SIGN(0) ---------.----------1 1 0 .SIGN(x)  SELECT SIGN(-5). SIGN(0) FROM dual. SIGN(5).

LN returns natural logs. logs with respect to base e.Log /ln 1. LOG returns base 10 log. that is. . 2.

8) FROM dual.  The second argument is the number that you want to take the log of.Log LOG function requires two arguments. .  The first argument is the base of the log.  SELECT LOG(2.

Ln  SELECT LN(value) FROM dual. .

 Sin()  Cos()  Tan()  Asin()  Acos()  Atan() .

upper (‘ivan bayross’) from dual. initcap (‘ivan bayross’) from dual.String functions  Select  Select  Select lower (name) from emp. .

4) from dual. [length]) substr(‘secure’.3. <start position>.Substr  Substr  Select (<string>. cure .

Ascii  Ascii (<single character>) Select ascii (‘a’) from dual. ASCII('FIRST') --------------------102   . 97 SQL> SELECT ASCII('first') FROM dual.

CHR(48). CHR (57) FROM dual. CCCCCC -----aAzZ09 . CHR(122).Chr  SELECT CHR(97). CHR(90). CHR(65).

Instr  Instr(<string1>. 1 .[start position] . ‘t’ .<string2>.[nth appearance])  Select instr(‘acT on the net’. 14 .2) from dual.

<replacement string>) translate (‘1sct523’. 7sct5a9 .Translate  Translate (<string1>. ‘123’.< string to replace>. ‘7a9’) from  Select dual.

Replace  SELECT REPLACE ('This is a test'. REPLACE('THISISATE -----------------This may be a test  If the look for string is not present. then the replacing does not occur  .' may be ') FROM dual.' is '.

'beer'. replace ('beer bucket'.'beer'.'beer') as replace_2 from   dual.------miik muckit milk bucket bucket .Translate v/s replace  select translate('beer bucket'. replace ('beer bucket'.'milk') as translate .'milk') as replace_1 .----------. TRANSLATE REPLACE_1 REPLACE ----------.

) is counted in the number of salary characters. SELECT salary. 5  The decimal point (.Length  Select length (‘lucky’) from dual.  . LENGTH(salary) FROM employee.

[set]) ltrim (‘nnnisha’.Ltrim  Ltrim (char.’n’) from dual.  Select isha .

Rtrim
 rtrim

(char, [set]) rtrim (‘sunilaaa’,’a’) from dual;

 Select

sunil

Trim

Trim ([leading/ trailing/ both trimcharacter from] <string>) The optional 'where' is one of the keywords "leading," "trailing," or "both." If the optional 'trim character' is not present, then blanks will be trimmed. 'Trim character' may be any character. The word FROM is necessary only if where or trim character is present.

1. 2. 3. 4.

Lpad
 Lpad

(char1, n [,char2])

 Select

lpad(‘page1’,10,’*’) from dual; ****page 1

char2]) .Rpad  rpad (char1. n [.

Vsize  Select vsize (‘abc d’) from dual. 5 .

y) appends y to x  SELECT CONCAT(first_name.CONCAT(x. last_name) FROM employee. .

.4)).1.Conversion function  To_number  Update (char) emp set sal=sal+to_number(substr(‘11000’.

To_char (number conversion)  To_char  Select (n[. $017.145 .999’) from dual.’$099.fmt]) to_char (17145.

january 05. yyyy) from  Selectto_char dual.fmt]) (sysdate.’month dd.To_char (date conversion)  To_char (date [. 2003 .

Name. .m.’. ‘abc’.Date conversion function  Insert into std (rno.’dd-mon-yy hh:mi a.’ )). to_date(25-jun-1952 10:55 a. dob) values (123.m.

Date functions  Add_months  Select (d. .4) from dual.s) add_months(sysdate.

last_day (sysdate) from dual.Last_day  Select sysdate. .

1 .’02-jan92’) from dual.Months_between  Select months_between (’02-feb-92’.

Next_day  Select next_day(’06-july-02’.’Saturday’) from dual. 13-july-02 .

Round  Round (date.[format]) .

‘ddth-mon-yy’) from dual. Select to_char (dob. 25th-jan-98 .

twenty five . Select to_char (dob. ‘ddsp’) from dual.

twenty-fifth . Select to_char (dob. ‘ddspth’) from dual.

 Rows are grouped on the basis of specified column.Concept of grouping  Group by clause is optional clause of select statement. .

…. . <col name 2>. Select<col name1> <col name 2> …… aggregate function (expression) from <table name> where <condition> group by <col name 1>..

.Example  Select branch_name. count(emp_id) from emp_mstr group by branch_name.

count(emp_id) from emp_mstr group by branch_name having count(emp_id) >5.Having clause  Select branch_name. .

. count(emp_id) from emp_mstr where city=‘jodhpur’ group by branch_name having count(emp_id) >5. Select branch_name.

.Display all customer who have only one account  Select cid. count(acno) from cust group by cid having count(acno)=1.

count(acno) from cust group by cid having count(acno)>1.Display all customer who have more than one account  Select cid. .

Sub queries
 It

is nested query i.e. a sql statement inside another sql statement. containing sub query is called parent statement and it uses the rows returned by sub query.

 Statement

Select sem ||’sem percentage is’ || per “Result” from result where rno in(select rno from std where fee_status=‘complete’);

Select sem, per from result where rno in(select rno from std where name like ‘a%’);

 Select

std.name, result.per from std, result where std.rno=result.rno; a.name, b.per from std a, result b where a.rno=b.rno;

 Select

(avgsal). a.Sub query in from clause  Select a. b.deptname from (select avg(sal) avgsal from emp) a. .deptno. dept_dtl b where a.deptno=b.name.

branch_no from acct a where bal>(select avg(bal) from acct).Correlated sub queries  Select acno. . bal.

lname) in (select fname . lname from emp where fname like ‘a%’ and lname like ‘n %’). lname from emp where (fname.Multi column sub query  Select fname. .

.deptno=b.deptno). sal from emp a order by (select deptname from dept_dtl b where a.Sub query in order by clause  Select name.

Exists operator .

Not exists .

Joins  Inner  Outer  Cross  Self join join (left and right) join join .

join return all the rows from both tables where there is a match.Inner join  Also  It known as equi join compare 2 columns from 2 tables with = operator.  Inner .

emp_id=b. a. a.emp_id.Ansi style / Theta style  Select a.name.emp_id.dept_dtl b where a. b.emp_id.emp_id.dept_name from emp a inner join dept_dtl b on a.  Select . b. a.dept_name from emp a .name.emp_id=b.

.Outer join  This type of joins are used in the situation where it is required to select all rows from the table in left (left outer join) or all the rows from the table in right (right outer join) regardless of whether the other table has common value or not.

emp b where b.emp_id.emp_id=a. a.local_addr.emp_id(+).per_addr from addr_dtl a .per_addr from emp a left join addr_dtl b on a.emp_id=b. a.emp_id.Left outer join (ansi/ theta)  Select a. b.name. b. b.local_addr.name. a.  Select . b.emp_id.

addr_dtl b where a. a.emp_id. b.name.emp_id.local_addr.emp_id.name.emp_id(+)=b.per_addr from emp a . b. • . a. b.per_addr from addr_dtl a right join emp b on a. a. Select a.Right outer join (ansi/ theta)  Select b.local_addr.emp_id=b.emp_id.

a.  Select .rno. t.name from std a cross join events t where a.name. a.Cross join  Cartesian  This product join combines every row from left table with every row in right table.class=10.

 Select emp.mgr_id=mgr.name from emp_manager emp. emp_manager mgr where emp. .Self join  It means joining table to itself.name. mgr.emp_id.

Sign up to vote on this title
UsefulNot useful