You are on page 1of 155

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), name varchar2(20), account_no number(5) );

Creating table with default values


CREATE

TABLE myTable ( id INTEGER, status VARCHAR2(20) DEFAULT 'Order pla ced' NOT NULL, last_modified DATE DEFAULT SYSDATE );

Inserting data into table


INSERT

INTO <table name> (<colname1>,<colname2>,) values (<expression1>,<expression2>,.);

Examples

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

Viewing data in the tables


Select

<col name1> to <col name N> from <table name>; * from <table name>; * from customer;

Select Select

Selected columns and all rows


Select

<colname1>,<colname2>,. from <table name>;

Select

name, account_no from customer;

Selected rows and all columns


Select

* from <table name> where <condition>; * from customer where name=lucky;

Select

Selected columns and selected rows


Select

<colname1>, <colname2>.. From <table name> where <condition>; account_no from customer where name=lucky;

Select

Eliminating duplicate rows


Select

distinct <colname1>, <colname2>,.. From <table name>; distinct * from <table name>; distinct occupation from customer;

Select Select

Sorting data in table

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

Use a column position number in the ORDER BY clause


SELECT

id, first_name, last_name FROM employee ORDER BY 2;

Creating table from a table


Create

table <new table name> (<colname>,<colname>) as select <colname1>,<colname2>, from <old table name>; table employee (eid,account_no,name) as select cid, account_no, name from customer;

Create

Inserting data from another table


Insert

into <table name> select <col1>,<col2>, from <table name> where <condition>; into employee select cid, name, account_no from customer where name=lucky;

Insert

Delete operation

Delete from <table name>; Delete from <table name> where <condition>; Delete from customer; Delete from customer where name=lucky;

Updating table content

Update <table name> set <colname1>=<expression1>, <colname2>=<expression2> where condition>; Update customer set name=sam ; Update customer set name=sam where name=lucky; UPDATE myTable SET id = DEFAULT;

Modifying table structure adding new column

Alter table <table name> add(<new col name> <data type> (<size>), <new col name> <data type> (<size>),); Alter table customer add(occupation varchar2(20)); alter table registrations add (entered_by number(4) default 7839);

Drop a column from table


Alter

table <table name> drop column <column name>; table customer drop column occupation;

Alter

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

Changing the Default Value of a Column


ALTER

TABLE myTable MODIFY last_modified DEFAULT SYSDATE - 1;

Renaming table
Rename

<old table name > to <new table

name>;
Rename

customer to cust;

Truncating tables
Truncate Truncate

table <table name>; table customer; between truncate and delete

Difference

Destroying tables
Drop Drop

table <table name>; table customer;

Displaying table structure


Describe Describe This

<table name>; customer;

will display column name, data type, size and constraint.

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, col name, ..);

At

Example
Create

table customer(cid number(3) primary key, name varchar2(20), acc_no number(5));

Create

table customer(cid number(3), name varchar2(20), acc_no number(5), primary key (cid));

Features of primary key


Do

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

Foreign key constraint


A

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

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),cid number(3) references customer (cid) on delete cascade);

Foreign key defined at table level

Foreign key (<col name >[,<col name>,]) references <table name> [(col name),<col name)] [on delete cascade]/[on delete set null]; Create table account (acno number(5), ac_cid number(3), bal number(6), foreign key (ac_cid) references customer (cid) on delete set null);

create

table employees ( empno NUMBER(4) primary key , mgr NUMBER(4) ) ; Insert into employees values(10,null);
Alter

table employees modify (mgr references employees )

User defined name to constraint


Constraint

<contraint name> <constraint defination> table std (rno number (5) default 0 constraint new_const primary key, class_no number(3) constraint c23 references class (class_no) );

Create

Unique key at column level


<col

name> <datatype> (<size>) unique

Create

table std (rno number(3), name varchar2(20), erno number(5) unique);

Unique key
Do

not allow duplicate values multiple entries of null raw data type cant be unique.

Permit

Long/long

Unique key at table level/column level


Create

table std (rno number(3), name varchar2(20), unique(erno)); table std (rno number(3) unique, name varchar2(20));

Create

Business rule constraint


These

are the rules which are determined by business manager and they vary from system to system.

Principles
Null

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

Null value concept


Insert into std values(123,,65); Insert into std values(120,null,90); Select * from std where name=; Select * from std where name is null; Select * from std where name is not null; Create tabel std(rno number(3) primary key, name varchar2(20) not null); Null cant be specified at table level.

Check constraint

<col name> <data type> (<size>) check(<logical expression>) Create table std (rno number(3), name varchar2(20) default abc check (name= upper (name))); Create table std (rno number(3), name varchar2(20) ,per number(4,2),check (name= upper (name)));

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

Restriction on check
Condition

must be Boolean expression and must evaluate to true or false. cant be sub query or sequence cant include sysdate, uid, user sql

Condition Condition

functions.

user_constraints table
OWNER CONSTRAINT_NAME TABLE_NAME CONSTRAINT_TYPE

(P R U C) SEARCH_CONDITION R_OWNER R_CONSTRAINT_NAME

Select

owner, constraint_name, constraint_type from user_constraints where table_name=std;

Adding constraint to existing table

Alter table std add primary key (rno);

Alter table result add foreign key (rno) references std (rno); Alter table std add constraint c44 unique (name); ALTER TABLE employee ADD CONSTRAINT reasonable_stock_date CHECK( start_date >= to_date('19000917','YYYYMMDD') );

Drop constraint
Alter

table std drop primary key;

Alter

table std drop constraint c44;

Arithmetic operators
+ * / ** ()

SELECT

10 * (12 / 3 - 1) FROM dual;

30

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 %n_;

* from emp where name like _d%e_ _;

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 "_". 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. The underscore is not treated as a wildcard character as would otherwise be the case.

1.

2. 3.

Example

SELECTfirst_nameFROMemployee 2WHEREfirst_nameLIKE'%\_%'ESCAPE'\'; FIRST_NAME ---------J_mes

SELECTtitle_nameFROMtitles WHEREtitle_nameLIKE'%!%%'ESCAPE'!';

In predicate
Select

* from emp where deptno in(10,30,70);

select*fromregistrations

whereevaluationin(1,2,3,NULL);

Not in predicate
Select

* from emp where deptno not in(10,30,70);

Dual

Dual is table owned by sys and it is part of data dictionary. DESCRIBEdual; NameNull?Type DUMMYVARCHAR2(1) Select 2*2 from dual; Select sysdate from dual;

Oracle functions
Group

function / aggregate function these functions act on set of values.

Scalar

function / single row function these function act only on one value at a time

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> UPDATE employee 2 SET salary = salary * 0.75 3 RETURNING AVG (salary) INTO :average_salary; 8 rows updated. SQL> SQL> PRINT average_salary; AVERAGE_SALARY -------------3053.81875

Min
min

( [distinct / all] <exp>) min (sal) from emp;

Select

selectmin(first_name)fromemp;

Max
max

( [distinct / all] <exp>) max (sal) from emp;

Select

Count
Count Select Select

([distinct/all] <exp>) count (name) from emp; count(*) from emp;

Sum
Sum

([distinct/all] <exp>)

Select

sum (bal) from account where cid=101;

Median / standard deviation


selectMEDIAN(salary)fromemployee; SELECTSTDDEV(salary)FROMemploy

ee;

You cannot use an aggregate function to limit rows in a WHERE clause


SELECTcity,AVG(salary)

FROMemployee WHEREAVG(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.

SELECTid,AVG(salary)

FROMemployee; (error)

Numeric functions
Abs

select abs(-15) absolute from dual;


SELECT id, value, ABS(value) FROM myTable

Power
Select

power(3,2) from dual;

select power(value, 3) from myTable ; power(2,3), power(-2,3) from dual;

select

Round

Select round(15.19,1) from dual; 15.2 select ROUND(5.75) from dual; ROUND(5.75) ----------6 SQL> select ROUND(5.75, 1) from dual; ROUND(5.75,1) ------------5.8

SQL>selectround(345.678,2) ,round(345.678,-1) ,round(345.678,-2) fromdual; ROUND(345.678,2)ROUND(345.678,-1)ROUND(345.678,-2) -------------------------------------------------345.68350300

Sqrt
Select

sqrt(25) from dual;

SELECT id, value, SQRT(value) FROM myTable;

Exp Select exp(5) from dual;

Extract
Extract

([year/month/day/hour/minute/second] from date value) extract (year from date 07-02-2007), extract( month from sysdate) from dual;

Select

Greatest
Select

greatest (10,20,5) from dual; Select greatest (4, 5, 17) from dual;

Least
Select

least (10,20,5) from dual; Select least (4, 5, 17) from dual;

Mod

Select mod (15,7) from dual;

Trunc

Select trunc (125.815,1), trunc (125.815,-2) from dual; 125.8 100

Floor
Select

24

floor (24.8), floor (13.15) from dual; 13

Ceil
Select

25

ceil (24.8), ceil (13.15) from dual; 14

SIGN(x)

SELECTSIGN(-5), SIGN(5), SIGN(0) FROMdual; SIGN(-5) SIGN(5) SIGN(0) ---------- ---------- ----------1 1 0

Log /ln
1.

LN returns natural logs, that is, logs with respect to base e. LOG returns base 10 log.

2.

Log
LOG function requires two arguments. The first argument is the base of the log. The second argument is the number that you want to take the log of.
SELECTLOG(2,8)FROMdual;

Ln
SELECTLN(value)FROMdual;

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

String functions
Select Select Select

lower (name) from emp; initcap (ivan bayross) from dual; upper (ivan bayross) from dual;

Substr
Substr Select

(<string>, <start position>, [length]) substr(secure,3, 4) from dual;

cure

Ascii

Ascii (<single character>) Select ascii (a) from dual; 97


SQL> SELECTASCII('first') FROMdual; ASCII('FIRST') --------------------102

Chr

SELECTCHR(97), CHR(65), CHR(122), CHR(90), CHR(48), CHR (57) FROMdual; CCCCCC -----aAzZ09

Instr
Instr(<string1>,<string2>,[start

position] ,[nth

appearance])
Select

instr(acT on the net, t , 1 ,2) from

dual; 14

Translate
Translate

(<string1>,< string to replace>,<replacement string>) translate (1sct523, 123, 7a9) from

Select

dual; 7sct5a9

Replace

SELECTREPLACE ('This is a test',' is ',' may be ') FROMdual;

REPLACE('THISISATE -----------------This may be a test

If the look for string is not present, then the replacing does not occur

Translate v/s replace

selecttranslate('beer bucket','beer','milk') as translate , replace ('beer bucket','beer','milk') as replace_1 , replace ('beer bucket','beer') as replace_2 fromdual; TRANSLATE REPLACE_1 REPLACE ----------- ----------- ------miik muckit milk bucket bucket

Length
Select

length (lucky) from dual;

The decimal point (.) is counted in the number of salary characters. SELECTsalary, LENGTH(salary) FROMemployee;

Ltrim
Ltrim

(char, [set]) ltrim (nnnisha,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

Rpad
rpad

(char1, n [,char2])

Vsize
Select

vsize (abc d) from dual;

CONCAT(x, y) appends y to x

SELECTCONCAT(first_name, last_name) FROMemployee;

Conversion function
To_number Update

(char)

emp set sal=sal+to_number(substr(11000,1,4));

To_char (number conversion)


To_char Select

(n[,fmt])

to_char (17145,$099,999) from dual;

$017,145

To_char (date conversion)


To_char

(date [,fmt]) (sysdate,month dd, yyyy) from

Selectto_char

dual; january 05, 2003

Date conversion function


Insert

into std (rno, Name, dob) values (123, abc, to_date(25-jun-1952 10:55 a.m.,dd-mon-yy hh:mi a.m. ));

Date functions
Add_months Select

(d,s)

add_months(sysdate,4) from dual;

Last_day
Select

sysdate, last_day (sysdate) from dual;

Months_between
Select

months_between (02-feb-92,02-jan92) from dual;

Next_day
Select

next_day(06-july-02,Saturday) from

dual; 13-july-02

Round
Round

(date,[format])

Select

to_char (dob, ddth-mon-yy) from

dual; 25th-jan-98

Select

to_char (dob, ddsp) from dual;

twenty five

Select

to_char (dob, ddspth) from dual;

twenty-fifth

Concept of grouping
Group

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

Select<col

name1> <col name 2> aggregate function (expression) from <table name> where <condition> group by <col name 1>, <col name 2>,.;

Example
Select

branch_name, count(emp_id) from emp_mstr group by branch_name;

Having clause
Select

branch_name, count(emp_id) from emp_mstr group by branch_name having count(emp_id) >5;

Select

branch_name, count(emp_id) from emp_mstr where city=jodhpur group by branch_name having count(emp_id) >5;

Display all customer who have only one account


Select

cid, count(acno) from cust group by cid having count(acno)=1;

Display all customer who have more than one account


Select

cid, count(acno) from cust group by cid having count(acno)>1;

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

Sub query in from clause


Select

a.name, a.(avgsal), b.deptname from (select avg(sal) avgsal from emp) a, dept_dtl b where a.deptno=b.deptno;

Correlated sub queries


Select

acno, bal, branch_no from acct a where bal>(select avg(bal) from acct);

Multi column sub query


Select

fname, lname from emp where (fname, lname) in (select fname , lname from emp where fname like a% and lname like n %);

Sub query in order by clause


Select

name, sal from emp a order by (select deptname from dept_dtl b where a.deptno=b.deptno);

Exists operator

Not exists

Joins
Inner Outer Cross Self

join join (left and right) join

join

Inner join
Also It

known as equi join

compare 2 columns from 2 tables with = operator. join return all the rows from both tables where there is a match.

Inner

Ansi style / Theta style


Select

a.emp_id, a.name, b.dept_name from emp a inner join dept_dtl b on a.emp_id=b.emp_id; a.emp_id, a.name, b.dept_name from emp a ,dept_dtl b where a.emp_id=b.emp_id;

Select

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.

Left outer join (ansi/ theta)


Select

a.emp_id, a.name, b.local_addr, b.per_addr from emp a left join addr_dtl b on a.emp_id=b.emp_id; b.emp_id, b.name, a.local_addr, a.per_addr from addr_dtl a , emp b where b.emp_id=a.emp_id(+);

Select

Right outer join (ansi/ theta)


Select

b.emp_id, b.name, a.local_addr, a.per_addr from addr_dtl a right join emp b on a.emp_id=b.emp_id; Select a.emp_id, a.name, b.local_addr, b.per_addr from emp a , addr_dtl b where a.emp_id(+)=b.emp_id;

Cross join
Cartesian This

product

join combines every row from left table with every row in right table. a.rno, a.name, t.name from std a cross join events t where a.class=10;

Select

Self join
It

means joining table to itself.

Select

emp.name, mgr.name from emp_manager emp, emp_manager mgr where emp.mgr_id=mgr.emp_id;

You might also like