Professional Documents
Culture Documents
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.
Creating Table
CREATE
Example
Create
TABLE myTable ( id INTEGER, status VARCHAR2(20) DEFAULT 'Order pla ced' NOT NULL, last_modified DATE DEFAULT SYSDATE );
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) ;
<col name1> to <col name N> from <table name>; * from <table name>; * from customer;
Select Select
Select
Select
<colname1>, <colname2>.. From <table name> where <condition>; account_no from customer where name=lucky;
Select
distinct <colname1>, <colname2>,.. From <table name>; distinct * from <table name>; distinct occupation from customer;
Select Select
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;
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
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;
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;
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);
table <table name> drop column <column name>; table customer drop column occupation;
Alter
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
Renaming table
Rename
name>;
Rename
customer to cust;
Truncating tables
Truncate Truncate
Difference
Destroying tables
Drop Drop
* 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
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
Create
table customer(cid number(3), name varchar2(20), acc_no number(5), primary key (cid));
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 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.
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 (<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
<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
Create
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), name varchar2(20), unique(erno)); table std (rno number(3) unique, name varchar2(20));
Create
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
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
Select
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
Alter
Arithmetic operators
+ * / ** ()
SELECT
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
Select
empid, name from emp where sal not between 5000 and 7000
Examples
Select Select Select
* from emp where name like a%a; * from emp where name like %n_;
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
SELECTtitle_nameFROMtitles WHEREtitle_nameLIKE'%!%%'ESCAPE'!';
In predicate
Select
select*fromregistrations
whereevaluationin(1,2,3,NULL);
Not in predicate
Select
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
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
Select
selectmin(first_name)fromemp;
Max
max
Select
Count
Count Select Select
Sum
Sum
([distinct/all] <exp>)
Select
ee;
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
Power
Select
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
Sqrt
Select
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
Trunc
Floor
Select
24
Ceil
Select
25
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;
String functions
Select Select Select
lower (name) from emp; initcap (ivan bayross) from dual; upper (ivan bayross) from dual;
Substr
Substr Select
cure
Ascii
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
dual; 14
Translate
Translate
Select
dual; 7sct5a9
Replace
If the look for string is not present, then the replacing does not occur
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
The decimal point (.) is counted in the number of salary characters. SELECTsalary, LENGTH(salary) FROMemployee;
Ltrim
Ltrim
Select
isha
Rtrim
rtrim
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
Rpad
rpad
(char1, n [,char2])
Vsize
Select
CONCAT(x, y) appends y to x
Conversion function
To_number Update
(char)
(n[,fmt])
$017,145
Selectto_char
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)
Last_day
Select
Months_between
Select
Next_day
Select
next_day(06-july-02,Saturday) from
dual; 13-july-02
Round
Round
(date,[format])
Select
dual; 25th-jan-98
Select
twenty five
Select
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
Having clause
Select
Select
branch_name, count(emp_id) from emp_mstr where city=jodhpur group by branch_name having count(emp_id) >5;
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
a.name, a.(avgsal), b.deptname from (select avg(sal) avgsal from emp) a, dept_dtl b where a.deptno=b.deptno;
acno, bal, branch_no from acct a where bal>(select avg(bal) from acct);
fname, lname from emp where (fname, lname) in (select fname , lname from emp where fname like a% and lname like n %);
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
Inner join
Also It
compare 2 columns from 2 tables with = operator. join return all the rows from both tables where there is a match.
Inner
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.
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
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
Select