SQL Tutorial PDF
SQL Tutorial PDF
SQL
Structure Query Language
Page 1 of 43
SQL Satya Manchiganti’s
Data:
It is a collection of raw facts from which conclusions can be drawn.
Database:
It is an collection of meaningful and related information stored at one location.
DBMS:
It is an software tool.
It is an collection of programs working together, to manage the information stored at one location.
It supports to store information with high security.
It allows to manipulate (Add, Change & Remove), Retrieve (read) and share information.
Student
Roll Name Course Fee
101 Ram Ora9i 2500
Data Types:
Data type represents the type of information stored in memory location.
2 types…
1. Simple data types
2. Composite data types.
Page 2 of 43
SQL Satya Manchiganti’s
4. Date:
Use to represent the date and time information memory occupied is 7 bytes.
Standard format of date and tme is ‘DD-M-YY’ and ‘HH:MI:SS’.
Birthday date;
Doj date;
5. Long Datatype:
Use to represent numbers and character information.
Maximum limit is 2GB
It can be used only once in table definition.
Description Long;
6. Raw(N):
Use to represent images.
Maximum limit is 256bytes
Photo raw(1000);
7. Long Raw:
Use to represent the images upto 2GB.
Photo long Raw.
Page 3 of 43
SQL Satya Manchiganti’s
SQL * Plus:
SQL commands are classified into 5 sub languages.
Naming Convention:
A-Z/a-z
0-9
_(underscore)
Maximum 30 characters
Ex:
Create table student(roll number(9), sname varchar2(20), course varchar2(20), fee
number(4));
Create table dept(dno number(9), dname varchar2(90), loc varchar2(90);
Create table employee(eno number(9), ename varchar2(90), sex char(1), sal number(9, 2),
hiredate date, dno number(9));
Desc student;
Non-sql stmt gives
1.2. Alter structure of table
Used to change structure of existing table.
Page 4 of 43
SQL Satya Manchiganti’s
Alter Add:
Alter table student add(phone number(10), mail-id varchar2(90));
Alter table emp add job varchar2(90);
Alter Modify:
Alter table student modify sname varchar2(50);
Alter table emp modify(ename varchar2(90), sal number(16,2));
Alter table student modify roll char(9); Changing the datatype of
column or reducing the
Alter Drop: column size is possible
Alter table emp drop column job; only if table is empty.
Alter table student drop (phone, mail_id);
1.3. Drop
Used to remove the table created.
Syntax:
Drop table <table_name>
Ex:
Drop table dept;
Drop table emp;
Drop table student;
Rename(8.0):
Used to change existing table.
Rename student to stu_info;
Rename emp to employ;
Rename Column(9i):
Used to change existing column name.
Alter table em rename column ename to
emp_name;
2.1. Insert
Used to add rows to existing table.
Syntax:
1. insert into <table_name> values(list of values);
2. insert into <table_name>(column_list) values(list of values);
Ex:
Insert into student values(101, ‘RAM’, ‘Oracle9i’, 2500);
Insert into student(roll, name) values(102, ‘SIVA’);
Page 5 of 43
SQL Satya Manchiganti’s
NULL: (Keyword)
Used to represent empty values.
Supports with all types of data.
Insert into dept values(30, ‘ADMIN’, NULL);
Where Clause:
Used to specify condition while manipulating or retrieve data.
Used to with update, delete and select stmts.
Operators in Oracle:
Arithmetic Relational Logical Special
+ > AND IN
- < OR BETWEEN
* <= NOT LIKE
/ >= is NULL
=
!= or <>
2.2. Update:
Used to manipulate information in table used to change existing rows.
Syntax:
Update <table_name> set col 1 = value\
[, col 2 = val, col 3 = val,……….where <cond>];
EX:
Update emp set sal = sal+2000;
Update emp set course = ‘Oracle9i’, fee = 1000 where roll = 102;
2.3. Delete:
Used to remove existing rows from table
Syntax:
Delete from <t_name> [where <cond>;
Ex:
Delete from emp;
Delete from emp where deptno = 30;
Delete from student where course = ‘.net’;
Page 6 of 43
SQL Satya Manchiganti’s
Ex:
Select * from emp;
Select * from student where course = ‘Oracle9i’;
Select * from emp where deptno = 10 and job = ‘CLERK’;
Select * from emp where deptno = 20 or job = ‘SALESMAN’;
Select * from emp where hiredate >= ‘1-jan-07’ and hiredate <= ’31-dec-07’
System Tables:
TAB: Holds the list of tables created by user.
USER_TABLES: Holds the complete details of table.
USER_TAB_COLUMNS: Holds the brief information about
the columns defined in table.
Scott:
Revoke all on emp from public;
Revoke select, insert on dept from user1, user2;
Sharing Columns:
Only insert and update permissions are allowed on columns.
Grant insert(empno, ename, job) on emp to user1;
Grant update(fee) on student to user2;
User1:
Insert into scott.emp(empno, ename, job) values(…);
Scott:
Revoke insert on emp from user1;
Revoke update on student from user2;
Page 7 of 43
SQL Satya Manchiganti’s
System Tables:
All_tab_privs_made Holds the collection of permissions given to other users.
All_tab_privs_recd Holds the collection of permissions received from other users.
Creating Users:
DBA: (system or sys)
Show user scott
Connect sys as sysdba
Password : *******
Show user sys
Create user RAM identified by ram111;
Grant connect, resource to RAM;
Grant connect, resourse to HARI identified by hari123;
Revoke connect, resource from ram;
Drop user hari cascade;
User:
show user scott
connect ram/ram111@oracle
show user Ram
@demobld.sql creates demo tables
Alter user ram identified by sriram111;
Select * from all_users;
Holds the list of
users in server.
Explicit commit:
Provided by user after DML operations to save the changes permanently.
Ex: insert, update, delete.
Page 8 of 43
SQL Satya Manchiganti’s
5.2. Rollback:
Used to cancel the uncommitted transactions.
Insert/update/delete
Rollback;
Delete from emp;
Select * from emp; No rows selected
Rollback;
Select * from emp; we can see the entire contents.
Delete from emp;
Select * from emp; No rows
Commit;
Select * from emp; No rows
Rollback;
Select * from emp; No rows.
Page 9 of 43
SQL Satya Manchiganti’s
Special Operators:
Used to improve performance, while retrieving or manipulating data.
IN:
Picks one by one value from given list of value supports with all types of data.
Select * from emp where empno in (101, 103,104, 109);
Update emp set sal = sal+4000 where ename in (‘RAM’, ‘HARI’, ‘PAVAN’):
NOT IN:
Select * from emp where empno NOT IN (101, 103, 108);
Update emp set sal = sal + 7000 where deptno NOT IN(10, 20, 30);
BETWEEN:
Used to pick the values in a range.
Supports with numbers and date values.
Select * from emp where sal BETWEEN 10000 and 15000;
Update emp set sal = sal +sal *.35 where hiredate BETWEEN ‘1-jan-89’ and ’31-dec-89’;
NOT BETWEEN:
Select * from emp where sal NOT BETWEEN 10000 and 15000;
Update emp set sal = sal+sal*.35 where hiredate NOT BETWEEN ‘1-jan-07’ and ’31-dec-07’;
NOTE:
BETWEEN is an inclusive operator. (includes range limits in output)
NOT BETWEEN is an exclusive operator. (excludes range limits).
LIKE:
Used to search for a pattern in character, valid with character data only.
NOT LIKE:
Select * from emp where ename NOT LIKE ‘S%’;
Page 10 of 43
SQL Satya Manchiganti’s
NULL:
It is an undefined and unconditional value.
It is not equal to zero or space.
It is represented with a null keyword and shown as space.
It will not occupy any memory.
It is a standard value imposed by E.F.Codd in every RDBMS tool.
It provides unique treatment for all types of data any arithmetic operation with null value returns a
null value.
IS NULL:
Used to compare null values.
Select * from emp where comm. Is null;
Update emp set deptno = 10 where deptno is null;
-- assign dept as 10 if dept is not assigned.
Update emp set hiredate = ’01-jun-10’ where hiredate is null;
Select * from emp where comm. Is not null;
-- list the employees who are having comm.
Alias names:
Used to provide the tempary names for columns or expressions in select stmt.
They are only for display purpose.
They are valid in the select stmt only.
Select empno, ename, job, sal, basic,
Sal * .25 DA,
Sal * .45 HRA,
Sal * .15 PF,
Sal + sal *.35 + Sal * .25 “Gross Pay”
From emp;
Dual:
It is a system table.
Used to retrieve general information through select.
Used to fulfill select stmt syntax.
Desc dual
--dummy char(1)
Page 11 of 43
SQL Satya Manchiganti’s
1. Column functions:
Applied on every column value.
a. Arithmetic:
Abs(n):
Gives the absolute value of given number.(if N is –ve converts to +ve)
Sqrt(n):
Gives the square root of the given number.
Power(m,n):
Gives MN result.
Mod(m,n):
Gives remainder after m y n operation.
Sin(n), cos(n), tan(n):
Trigonometric functions gives the results in radians.
Ln(n):
Gives natural logarithm value of N.
Log(m,n):
Gives logarithm value of n to value of M.
Exp(n):
Gives eN value.
Sign(n):
If N is +ve 1
N is –ve -1
N is 0 0
Round(m,n):
Gives nearest whole numbers for M.
Trunk(m,n):
Gives only whole number by elimating decimal values.
Ceil(n):
Similar to round. (gives higher value always).
Floor(n):
Similar to truncate.(always gives lower value)
NOTE:
N is optional value in round and truncate.
Page 12 of 43
SQL Satya Manchiganti’s
b. Character:
Applied on character data only.
Init_cap(s):
Converts that starting letter of every word in given string to capital letters.
Upper(s):
Converts the given string into capital letters.
Lower(s):
Converts the given string into lower case letters.
Length(s):
Gives the no of char’s in given string.
Reverse(s):
converts the string into reverse pattern.
Page 13 of 43
SQL Satya Manchiganti’s
O/P : ram kumar Ram Kumar RAM KUMAR ram kumar 9 ramuk mar
Char(20) 20
Length(ename)
9
Varchar2(20)
Ascii©:
Gives ascii value of the given character.
Chr(n):
Gives equalent character for the given number.
Concat(s1, s2):
Use to join the strings s1 & s2
|| concatenation operator.
Select concat(concat(ename, ‘is a’), job) from emp;
RAM is a Manager
Lpad(s, n, c):
Left padding, pads the given string upto N characters with character C.
Rpad(s, n, c):
Right padding, pads the given string upto N characters with character C.
Page 14 of 43
SQL Satya Manchiganti’s
Soundex(s):
Gives encrypted sound value of given string, used to compare strings based
on sound.
Select ename, soundex(ename) from emp;
Select soundex(‘oracle’) from dual;
Select * from emp where soundex(ename) like soundex(‘smythy’);
Substr(s, m, n):
Used to extract a particular portion of string.
S string
M Starting Position
N No of charcters to be retrieved. (optional)
Select substr(‘oracle9i’, 7) from dual; 9i
Select substr(‘ilogic’, 2) from dual; logic
Select ename, substr(ename, 1, 3), substr(ename, 5), substr(ename, 5, 3)
from dual;
Ram kumar Ram Kumar Kum
Instr(s, c, m, n):
Use to find the position of character c in the given string s.
M starting position
N occurance no.
Select instr(‘ANAND’, ‘A’, 1, 1), instr(‘ANAND’, ‘A’, 1, 2) from dual;
1 3
c. Date Functions:
Applied on date information.
Sysdate:
Pseudo column (system defined column).
Gives system date from server.
Add_months(d, ±N):
Adds N no of months to given date and retrns date.
Next_day(d, ‘day’):
Gives the date of next coming week day.
Last_day(d):
Gives the last day date of month in given date.
Months_between(d1, d2):
Return number, Gives difference between two dates in months.
Page 15 of 43
SQL Satya Manchiganti’s
DATE Arthematic:
Supports to perform addition and subtraction on date results are manipulated interns of
days and o/p will be date.
Page 16 of 43
SQL Satya Manchiganti’s
To_char(d, ‘format’):
Use to convert the given date into character in specified format.
Format indicates inot which it has to be convert.
To_date(c, ‘format’):
Use to convert the given character into date.
Format indicates in which it is available.
Invalid Conversions:
To_date(‘24’, ‘cc’)
To_date(‘3’, ‘Q’)
To_date(‘28’, ‘ww’)
To_date(‘3’, ‘w’)
To_date(‘Monday, may, 208’, ‘day, month, yyyy’)
Inserting time:
Select sysdate form dual;
Select ename, hiredate from emp;
2. Group functions:
Applied on group of rows.
They ignore null values.
Sum(N):
Gives the total of given column.
Page 17 of 43
SQL Satya Manchiganti’s
Count(N, C, D):
Gives the number of rows in the given column.
Avg(N):
Gives the average of given column(sum/count)
Min(n, d):
Picks the smallest value in the given column.
Max(n, d):
Picks the largest value in the given number.
Stddev(N)(8.0):
Gives the standard deviation of the given column.
Variance(N)(8.0):
Gives the variance of given column.
3. General Functions:
Applied on any type of data.
Least:
Picks the smallest value from given list of values.
Greatest:
Picks the largest value from given list of values.
User:
It gives user name.
Uid:
Gives user identification number.
Error/err:
Gives currently raised errors in pl/sql manipulation.
Vsize:
Gives the memory occupied by table column.
NVL(column, value):
If column is null it considers the value specified.
Used to retrieve accurate results in arithematic calculations with null values.
Select ename, sal, com, sal + comm. Net, nvl(sal, 0)+nvl(comm, 0) “netpay”
from emp;
Decode:
Used to check for multiple conditions.
Implement “IF” construct
Used for reporting purpose.
Page 18 of 43
SQL Satya Manchiganti’s
Select ename, job, deptno, decode(deptno, 10, sal*.25 20, sal*.45 30,
sal*.65, sal*.85) bonus from emp;
Select empno, ename, job, decode(job, ‘clerk’, ‘excutive’, ‘salesman’,
‘Mkt.mgr’, ‘mgr’, ‘tech mgr’, job) designation from emp;
JOB DESIGNATION
Clerk executive
Analyst analyst
Mgr tech mgr
4. Analytical functions(9i):
Used to retrieve data analysis reports.
To_number©:
Used to convert given char to number.
Select to_number(‘2008’)+1 from dual;
Select to_number(substr(‘ora1001’, 4))+1 from dual; 1002
Select to_number(‘abc’) from dual; Error.
Page 19 of 43
SQL Satya Manchiganti’s
Select Clause:
Select <col list> from <table name>
[Where <cond>
Group by <columns>
Having <cond>
Order by <columns>];
Group By:
Use to group the rows based on the specified column.
Whenever an ordinary column retrieve along with aggregate values than all the ordinary
columns must be provided after group by clause.
10
Emp
20
30
Select course, count(*), sum(fee) from student group by course;
Having:
Use to apply the cond on grouped results.
Select course, count(*), sum(fee) from student group by course having count(*) > 100;
Select deptno, sum(sal) from emp group by deptno having sum(sal) >10000;
Order By:
Use to arrange the select stmt o/p in ascending as desending order.
Supports all types of data.
Ase ascending order (default)
Descc descending order.
Page 20 of 43
SQL Satya Manchiganti’s
Emp 30
Distinct Clause:
Used to eliminate duplicate values in select stmt.
Select course from student;
Select job from emp;
Select deptno from emp;
Select distinct course from sudent;
Select distinct deptno from emp;
Select count (distinct course) from student;
Page 21 of 43
SQL Satya Manchiganti’s
JOINS:
Used to query multiple table.
Used to retrieve data from more than 1 table in one select stmt.
5 types of joins…
1. Equi Join
Use to retrieve data from more than 1 table based on equality condition.
Tables must have similar column repeated in itself to apply this join.
If N tables are join ‘N-1’ conditions are required.
Select eno, ename, job, sal, emp.deptno, dname, loc from emp, dept where emp.deptno =
dept.deptno;
--emp details along with their dep details
Select s.roll, s.name, s.cid, c.cname, c.timming, c.room, c.fee, c.fee-s.fee – paid “due” from
course c, student s where s.cid = c.cid;
--stdt details along with course infn and fee due infn.
2. Cartesian join
Used to retrieve the data from more than 1 table without any condition.
No need to have common column b/n tables to apply this join.
Select eno, ename, job, sal, emp.dno, dname from dept, emp;
Select s.roll, s.name, s.cid, c.cname, c.timing, c.room, c.fee, s.fee-paid from course c,
student s;
Select fname, cname from faculty, course;
3. Non-Equi Join:
Used to join the tables using any oter condition but not equal to (=).
Select eno, ename, sal, job, grade from emp, sal where sal between losal and hisal;
4. Outer Join:
Used to retrieve all the rows from table 1 but only matching rows from table 2.
Select eno, ename, sal, job, emp.dept, dname, loc from emp, dept where emp.deptno(+)
=dept.deptno;
--emp’s along with their dept details
Select roll, name, s.cid, cname, timing, room, fee_paid from student s1 course c where
s.cid = c.cid(+);
--students with or without proper course details.
Select roll, name, s.cid, cname, timing, room, fee_paid from student s, course c where
s.cid(+) = c.cid;
--courses with or with out proper students.
5. Self Join:
Joining the table to itself.
Table must have similar column repeated in itself to apply this join.
Page 22 of 43
SQL Satya Manchiganti’s
EMP
WORKER MANAGER
Eno Ename Mgr Eno Ename Mgr
101 A Null 101 A Null
102 B 101 102 B 101 SUBORDINATE SUPERIOR
103 C 102 103 C 102 B A
104 D 101 104 D 101 C B
105 E 102 105 E 102 D B
E B
NOTE:
One column of the table connected to some
column of the table i.e; self join.
Set Operators:
Used to join the o/p of select stmt based on the operator specified.
Select stmts must have equal no of columns and similar data type columns.
Maximum 32 queries can be join using operators.
4 operators…
1. Union all
Output of Q1+ output of Q2
2. union
O/p of Q1 +O/p of Q2 – Duplicate rows
3. intersect
O/p common of Q1 & Q2
4. minus
O/p of Q1 – O/p of Q2 (rows unique to Q1 only)
Ex:
select job form emp where deptno = 10 union all select job from emp where deptno = 20;
select job from emp where deptno = 10 union select job from emp where deptno = 20;
select job from emp where deptno = 10 intersect select job from emp where deptno = 20;
select job from emp where deptno = 10 minus select job from emp where deptno = 20;
Page 23 of 43
SQL Satya Manchiganti’s
More examples….
Select job from emp where deptno = 10 union
Select job from emp where deptno = 20 union
Select job from mp where deptno = 30;
Page 24 of 43
SQL Satya Manchiganti’s
2. Spool:
Used to store the sql screen content to an OS file.
Spool <filename>
Spool off stopsthe transferring of sql screen content into OS file.
Substitution operator:
&:
Used to accept the values from keyboard.
Valid for that particular stmt only.
Select * from &tname where &cond;
Insert into stu_info values(&roll, ‘&sname’, ‘&course’, &fee);
Insert into stu_info values(&1, ‘&2’, ‘&3’, &4);
&&:
Valid for complete session.
Select * from &&tname where &cond;
Insert inot stu_info values(&roll, ‘&sname’, ‘&&course’, &fee);
Page 25 of 43
SQL Satya Manchiganti’s
Sub Queries:
In a sub query first inner query will be executed and based on the output of inner query outer query
will be executed.
Also called as “Query with in a Query”.
Select stmt provided in the cond is known as “Nested Query”.
Sub Queries will improve the performance while retrieving or manipulating data.
Ex:
List the employees who belongs to RAM’s dept.
Q1 > select deptno from emp where ename = ‘RAM’;
Q2 > select * from emp where deptno = 10;
Select * from emp where deptno = (select deptno from emp where ename = ‘RAM’);
Select * from emp where deptno in (select deptno from emp where ename = ‘RAM’);
List employee details along with dept details & no of incr’s and total incr amt and should be morethan one
incr.
Select incr.empno, ename, sal, job, emp.deptno, dname, loc, count(incr.empno) icount, sum(amt)
total from incr, emp, dept
Where incr.empno = emp.empno and emp.deptno = dept.deptno
Group by incr.empno, ename, sal, job, emp.deptno, dname, loc
Having count(incr.empno) > 1;
Page 26 of 43
SQL Satya Manchiganti’s
Ex:
List the emp’s whose salary is morethan 10th dept lowest pay.
Select * from emp where sal > Any(select sal from emp where deptno = 10);
List the emp’s whose salary is morethan 10th dept highest pay.
Select * from emp where sal > All(select sal from emp where deptno = 10);
Select * from emp where sal > Any/All (5000, 8000, 3000, 12000, 14000, 20000);
List the employees of dept 10 if there are morethan 5 analysts in the same dept.
Select * from emp where deptno = 10 and exists (select Count(*) from emp where deptno = 10 and
job = ‘Analyst’ group by job having count(*) >5);
List the emp details whose salary is more than their dept avg pay.
Select * from emp e where sal > ( select avg(sal) from emp where deptno = e.deptno);
Update salary by 25% salary is less than their dept, avg pay.
Update emp e set sal = sal + sal *.25 where sal < (select avg(sal) from emp where deptno =
e.deptno);
Page 27 of 43
SQL Satya Manchiganti’s
Scalar Query:
It is an independent query.
Select stmt provided in place of column name is known as “scalar query”.
Ex:
List the employ dept details along with no of employees and total salary.
Select dno, dname, loc,
(select count(*) from emp where dno = d.dno) ecount,
(select sum(sal) from emp where dno = d.dno) total
from dept d;
Page 28 of 43
SQL Satya Manchiganti’s
Integrity Constraints:
A set of pre defined rules applied on the table columns while creating tables or after creation.
They are automatically activated whenever ‘DML’ stmts are performed on tables.
They are also activated when tables are manipulated by other users or by other application software
tools.
They provide high security on tables.
3 types…
1. Domain integrity rules:
Used to provide conditional restrictions on table columns.
a. NOT NULL:
Use to restrict null values into table columns.
b. CHECK:
Use to provide conditional rules on table columns.
a. UNIQUE:
use to restrict duplicate values into table columns.
But only number of null values on table columns.
b. PRIMARY KEY:
NOT NULL + UNIQUE + INDEX
Use to define key column of table.
It can be used only once in table definition.
It will not accept null values and duplicate values.
It is supported with index automatically.
INDEX:
It is a point locates the physical address of data.
It is automatically activated when key column is used in where condition.
It will improve the performance of oracle while retrieving or
manipulating data using key column.
Page 29 of 43
SQL Satya Manchiganti’s
a) Column constraint:
Constraints are defined next to the column definition.
All the constraints are supported in this syntax.
Use to define the constraints while creating tables.
Syntax:
Create table <t_name> (col1 datatype constraint, col2 datatype constraint,….);
Ex:
Create table dept( dno number(90) primary key, dname varchar2(90) not null
unique, loc varchar2(90) default ‘hyderabad’);
Activating default:
Insert into dept values(40, ‘Training’, default); inserted
Insert into dept values(null, ‘Training’, default); not inserted, null value not
allowed at dno.
Select * from dept where deptno = 10; -- Index activated automatically.
Create table student( roll number(9) primary key, sname varchar2(90) not null, course
varchar2(90) check(course in (‘oracle’, ‘java’, ‘unix’, ‘D2k’)), fee number(8)
check(fee>=5000), doj date default sysdate);
Create table emp(eno number(90) primary key, ename varchar2(90) not null, sex char(1)
check(sex in (‘M’, ‘F’)), sal number(9,5) check(sal >=5000), hiredate date default sysdate,
mail-id varchar2(90) unique, dno number(9) references dept(dno));
Insert into emp values(101………., 90); Error, parent key not found.
Create table incr(eno number(4) not null references emp(eno), amt number(10, 2) not null);
Delete from dept where deptno = 10; Error, depending child rows exists.
delete from incr where eno in (select eno from emp where deptno = 10);
Incr
Page 30 of 43
SQL Satya Manchiganti’s
Cascade constraints:
Allows to remove the parent table even if child exists.
It will destroy the relationship between 2 tables.
Child records still exists even if parent table is dropped.
It is used with drop stmt on parent table.
b) Table constraint:
Used to define constraints on existing table.
Max 32 columns can be defined in CPK or CFK.
Ex:
Create table reservation( trainno number(9), coach_id varchar2(5), seat_no number(3), doj date,
pname varchar2(90), age number(3), sex char(1), to_stn varchar2(90), from_stn varchar2(90),
fare number(5), constraint pk_rail primary key(train_no, coach_id, seat_no, doj));
Create table bankmaster(accno number(4), acc_type char(1), name varchar2(90) not null,
curr_bal number(12, 2), pan_no varchar2(12), constraint pk_bank primary key(accno,
accc_type), constraint chk_atype check(acc_type in (‘s’, ‘c’, ‘r’)), constraint chk_bal
check(curr_bal>=5000), constraint unq_pan unique (pan_no));
Page 31 of 43
SQL Satya Manchiganti’s
Alter table emp add constraint fk_dept foreign key(dno) references dept on delete cascade;
Sharing constraints:
Scott:
Grant references on dept to user1;
Removing constraints:
Alter table <t_name> drop constraint <cons name>;
-- In place of “DROP”, we can use disable/enable.
System tables:
User_constraints Holds complete details of constraints
defined on table columns.
User_cons_columns Holds the brief information about the
constraints applied on table columns.
Select constraint_name, constraint_type from
user_constraints where table_name = ‘EMP’;
Page 32 of 43
SQL Satya Manchiganti’s
Locks:
Used to preserve the rows for manipulation purpose to prevent the other users manipulating same
information at the same time.
It supports to share the data with multiple users.
They will improve data concurrency.
2 types….
1. Implicit Locks:
Automatically applied by oracle whenever DML operations are performed by user.
2. Explicit Locks:
Provided by the user before manipulating the table contents.
2 types..
a. Row level locks:
Used to lock the selected rows before manipulating data.
It is imposed by update clause in select.
Select * from emp where empno = 7900 for update;
Update emp set sal = sal+3000 were empno = 7900;
Commit;
NOTE: Commit/Rollback will release
any type of lock.
Behavior of Locks:
USER
Share Share Update Exclusive
O Share Y Y N
T
H Share update Y Y N
E Exclusive N N N
R
S DML Not Allowed DML allowed Not Allowed
on other rows
Select Y Y Y
Page 33 of 43
SQL Satya Manchiganti’s
1. Table:
Supports to store the information and allows to manipulate, retrieve and share the information.
2. view:
Supports to manipulate, retrieve and share the information
It will not hold data.
3. Synonym:
Supports to manipulate, retrieve and share the information.
Used to hide the original name.
It will not hold data.
4. Sequence:
Use to generate the numbers automatically.
5. Index:
Used to improve performance of oracle while retrieving or manipulating data.
6. Cluster:
Used to improve performance of oracle while retrieving or manipulating data.
7. Roles:
Used to hold the collection of permissions on different data base objects.
Views:
It is a virtual component.
It is a stored select stmt.
It will not hold data.
It allows describe, DML and select on it.
It is stored permanently in user_views system table.
It can be shared with other users.
It supports to share selected rows & columns with other users.
It provides high security while sharing.
DML on view are reflected in table and DML on table are reflected in views.
They improve the performance while retrieving data.
They are used for reporting purpose.
Syntax:
Create view <v_name> as <select stmt>;
Ex:
Create view v1 as select * from emp;
Desc v1;
Select * from v1;
Grant all on v1 to user1;
--we can do all operations on views as like on table.
Create view v10 as select * from emp where dno = 10 with check option;
Force Option:
Supports to create view without table.
Create force view my_view as select * from my_table;
Desc my_table; --Error
Create table my_table as select * from student;
Select * from my_view;
Drop view <v_name>
Drop view v1;
Desc user_views;
Select * from user_views;
Materialized views(8i):
It is static view.
It holds data.
It will not allow DML.
DML on table are not reflected in view.
It is used to maintain historic data.
To create this view “create materialized view” permission is required.
It is use for data analysis purpose.
It is equal lent to SNAPSHOT_DBA object.
DBA:
Grant create materialized view to scott;
Create materialized view mv1 as select * from emp;
Select * from mv1;
Drop materialized view mv1;
Inline view:
Select stmt provided in place of table name is known as “Inline view”.
Page 36 of 43
SQL Satya Manchiganti’s
Synonym:
Used to hide the original name and owner of the database object.
It provides security by hiding identity of component.
Describe, DML and select are allowed on synonyms.
It is stored permanently in user_synonyms table.
DML on synonym are reflected in table and DML on table are reflected on synonym.
They can be shared with other users.
It will not hold data.
2 types….
1. Private synonym: created by user.
2. public synonym: created by DBA
Syntax:
Create synonym <s_name> for <db obj name>;
It can be table
Ex: or view also.
create synonym esyn for emp;
select * from esyn;
desc esyn
Insert into esyn values (…);
update esyn set sal = sal+8000;
delete from esyn where empno = 8900;
grant allon esyn to user1;
Page 37 of 43
SQL Satya Manchiganti’s
Sequence:
Used to generate the numbers automatically.
It is stored in user_sequences system table.
It is not related to any table.
It used 2 pseudo columns.
NEXTVAL: gives the next value generated by sequence.
CURRVAL: gives the present value available with sequence.
Ex:
create sequence s1 increment by 1;
select s1.nextval from dual; o/p: 1
select s1.nextval from dual; o/p: 2
select s1.nextval from dual; o/p: 3
select s1.currval from dual; o/p: 3
insert into emp values(s1.nextval,……); o/p: 4
create sequence s1 increment by 1 start with 101 minvalue 101 cycle cache 5 maxvalue 999;
Page 38 of 43
SQL Satya Manchiganti’s
INDEX:
It is a pointer locates the physical address of data.
It will improve the performance when indexed column is used in where condition.
It is stored permanently in user_indexes system table.
Generally indexes supports with update, delete and select only.
Unique index:
Create unique index idx2 on dept(dname);
Select * from dept where dname = ‘sales’;
Insert into dept values(60, ‘sales’, ‘pune’);
Composite index:
Create index idx3 on student(course, timing);
Select * from student where course = ‘oracle9i’ and timing = ‘6:30pm’;
Page 39 of 43
SQL Satya Manchiganti’s
Cluster:
It holds the common column shared by 2 tables.
It will improve the performance while retrieving or manipulating data from master detailed
tables.
It has to be created before creating the tables.
It can’t be applied to the existing tables.
It is stored permanently in user_clusters system table.
Roles:
Created by DBA only.
Holds the collection of permissions of different database objects.
Easy to share multiple objects with other users.
Stored in user_roles system table.
Page 40 of 43
SQL Satya Manchiganti’s
Pseudo columns:
Rowid Rownum
Level Sysdate
Nextval Currval
New Old
Sqlcode Sqlerrm
1. Rowid:
It is a unique value.
It is a stored permanently in the database.
It is automatically assigned with every row insert into to the table.
It is A18-bit hexa decimal value comprises of object id, block id, data file id and
recoring.
Delete from emp where rowid NOT IN (select min(rowid) from emp group by
empno);
--Removing duplicate rows.
Update emp set sal=sal+3000 where rowid NOT IN(select min(rowid) from
emp);
--Except first row update other rows.
Select * from emp where rowid not in(select max(rowid) from emp);
--Except last row display other rows.
2. Rownum:
It is a unique value.
It is not stored in the database.
It is a dynamic value retrieved along with the select stmt output.
Select rownum, eno, ename, job, sal from (select rownum, eno, ename, job, sal from
emp order by desc) where rownum <= 5;
--Retrieving Top 5 highly paid employees.
Select rownum, eno, ename, sal from (select rownum, eno, ename, sal from emp
order by sal desc) group by rownum, eno, ename, sal having rownum = &n;
--Retrieving Nth max salaried employ details.
Select rownum, eno, ename, job, sal, from emp group by rownum, eno, ename, job,
sal
having mod(rownum, 2) = 0; Even rows
Page 41 of 43
SQL Satya Manchiganti’s
3. Level:
Used to arrange the output of select stmt in hierarchal tree structure(inverted tree).
It gives the position of row in tree.
Select level, eno, ename, job, sal from emp connect by prior eno = mgr start
with mgr is null order by level;
“Connect by prior”,
“start with” both are
system defined values.
Page 42 of 43
SQL Satya Manchiganti’s
Tunning:
It means making the database application run faster, faster means high throughput.
You can also say that when your program using so many resources and performance is low, now tnning
comes in the picture.
Tunning considerations:
database availability
data base hit percentages
memory utilization, etc.,
Tunning steps:
Tune the database (normalization).
Tune the application design.
Tune the resource concentration.
Tune the operating system etc.
2. Explain Plain:
When ever you read or write data in oracle, you do so by issuing an sql stmt.
One of oracles task when it receives such a stmt is to build a query execution plan.
An execution plan defines how oracle finds or writes the data.
For example, an important decision that oracle has to take is if it uses
indexes or not. And if there are more indexes, which of these is used. All this is
contained in an execution plan.
Syntax:
Explain plan into table_name for your_precious_sql_stmt;
If you omit the “INTO T_NAME”
clause, oracle fills a table named
"plan_table” by default.
~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~
Page 43 of 43