You are on page 1of 43

SQL Satya Manchiganti’s

SQL
Structure Query Language

For any Queries: m21.satya@gmail.com

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.

RDBMS: --Developed in 1968


 Information is represented in rows & Columns.
 Intersection of row and column gives a single value.
 Supports unlimited data.
 Provides high security.
 Supports multiple users & multiple platforms.
 Supports error handling.
 Supports EF Codd’s rules.
 Supports “ACID” properties.
 Supports “NULL” values(No value).
 Supports “Integrety constranints” or “Pre-defined rules”.
 Supports to store any type of information(Text, Null, characters, date, time, images, files).
 No data redundancy like HDBMS.
 Relations are maintained logically through code.
 Data Retrievel and manipulation is very faster.

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

Simple Data types:


1. Number(p,s): P Precision, S Scale
 Used to represent the numeric information.
 Maximum limit for precision is 32 digits
Eno number(4);
Salary number(7,2);

2. Char(N):  Fixed length character datatype.


 Used to represent the character information.
 Maximum limit for ‘N’ is 256bytes
 It supports static memory allocation.
Name char(90);
Sex char(1);

3. Varchar2(N): Varrying length character datatype


 Used to represent the character information.
 Maximum limit for ‘N’ is 2000 bytes.
 Supports dynamic memory allocation.
Varchar2(90)
Addresss2(290)
NOTE:
Any value included in single quotes is
treated as character information.

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.

;  SQL statement Terminator.

Page 3 of 43
SQL Satya Manchiganti’s

SQL * Plus:
SQL commands are classified into 5 sub languages.

1. Data Definition Language (DDL) Store Manipulation


2. Data Manipulation Language (DML)
3. Data Querying Language (DQL)  Read
4. Data Control Language (DCL)  Share
5. Transaction Control Language. (TCL)  Saving

1. Data Definition Language:


Used to define the database objects.

A component stored permanently


into the data base when ever create. Table:
EX: Table, View…..etc.,  Use to represent the information in every
RDBMS rule.
 A table can have maximum 1000 columns
and minimum 1 column.
 A table can have unlimited number of
rows.
1.1. Create
Used to define new database objects.
Syntax:
Create table <t_name>(col 1 datatype, col 2 datatype…….col N datatype);

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.

ADD: Used to add new column to existing table.


MODIFY: used to change structure of existing column.
DROP column(8i): used to remove existing column.

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. Data manipulation Language(DML):


Used to manipulate information in table.

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’);

Rest of the columns are


filled with empty
values(Null values)

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’;

3. Data Querying Language(DQL):


Used to retrieve the data from table for read only purpose.
Syntax:
Select <col list> from <t_name>
[Where <cond>
Group by <col’s>
Having <cond>
Order by <col’s>];

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.

4. Data Control Language(DCL):


Used to control flow of information between users.

4.1. Grant:used to give permissions on database objects to other users.


4.2. Revoke: used to cancel permissions.

Permissions: select, insert, update, delete, All(4 at once).


2 types…
Grantor: gives the permission.
Grantee: receives the permission.
PUBLIC: Represents all
the users in the server.
Ex:
Scott:
 Grant all on emp to public;
 Grant select, insert on dept to user1, user2;
 Grant all on student to user1 with grant option.
Allows to give permissions
User1: on shared object.
 Select * from scott.emp;
 Grant select, insert on scott.student to user2;

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;

Destroy the user


permanently.

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.

5. Transaction control Language(TCL):


Used to control DML operations performed by user. Logical
Memory
5.1. Commit:
 Used to save changes made to table. Commit
 Once if you give the commit all the operations are
stored in physical memory. Physical
2 types… Memory
Implicit commit:
Oracle automatically saves the transactions performed.
Ex: DDL commands.

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.

5.3. Save Point:


 Used to book mark transactions performed by user.
 Used to refer the DML operations for further manipulations used with rollback stmt only.
 Insert  100 rows
 Savepoint s1;
 Update  50 rows
 Savepoint s2;
 Delete  25 rows;
 Roll back to savepoint s2;  cancels delete stmt.
 Commit;

NOTE: Commit and rollback clear the savepoint.

Truncate: Delete + commit


 Used to remove all the rows from table & saves permanently
 Improves performance by releasing resources.
 Faster in execution.
Ex:
 Truncate table emp;  whole table will be deleted.
(or)
 Delete table emp;
 Commit;
 Desc emp;  structure is there.
 Drop table emp;
 Desc emp;  Error.

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.

Uses 2 meta characters…..


%  Represents zero or more characters.
_  Represents single character. (underscore)

List employees whose names start with ‘S/s’


 Select * from emp where ename like ‘S%’;
 Select * from emp where ename like ‘S%’ or ename like ‘s%’;

List emp’s whose names start and end with ‘S/s’


 Select * from emp where ename like ‘S%S’ or ename like ‘s%s’;

List emp’s whose names having 2nd char as ‘I’


 Select * from emp where ename like ‘_i%’;

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.

Removing a column value:


 Update emp set comm. = NULL where empno = 101;

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.

Arithmetic expressions in select:


 Select empno, ename, job, sal, sal * .25, sal *.35, sal *. 15, sal+sal*.35 – sal*.15 from emp;

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

Built-in Functions in oracle:


Provide by oracle automatically.

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.

 Select sqrt(625), mod(11, 2), power(4,2) from dual;


 Select sin(30), cos(45), tan(90) from dual;
 Select ln(35), log(2, 35) from dual;
 Select exp(1.17) from dual;
 Select sign(200), sign(-400), sign(70-800) from dual;
 Select ename, job, sign(sal-comm) from emp;

Page 12 of 43
SQL Satya Manchiganti’s

 Select round(19.7678), round(19.7678, 2), round(20.2324), ROUND(20.2324, 2) from


dual;
20 19.77 20 20.23

 Select trunc(19.7678), trunc(19.7678, 2), trunc(20.2324), trunk(20.2324, 2) from dual;


19 19.76 20 0.23

 Select round(-19.76) from dual


-20

 Select round(7678678678.6775, -1) from dual;


7678678680
 Select round(7678678678.6775, -2) from dual;
7678678700
 Select round(7678678678.6775, -3) from dual;
7678679000
 Select round(7678678678.6775, -4) from dual;
7678680000
 Select round(7678678678.6775, -5) from dual;
7678700000
 Select trunc(7678678678.6775, -1) from dual;
7678678670
 Select round(7678678678.6775, -2) from dual;
7678678600

 Select round(24.2321), ceil(24.2321) from dual;


24 25

 Select trunk(30.7678), floor(30.7678) from dual;


30 30

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.

 Select ename, initcap(ename), upper(ename), lower(ename), length(ename),


reverse(ename) from emp;

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.

 Select ascii(‘A’), ascii(‘a’) from dual;


65 97
 Select chr(65), chr(97) from dual;
A a
 Select ‘SAI’|| ||’BABA’ from dual;  SAI BABA
 select lpad(rpad(‘5000’, 7, ‘*’), 10, ‘*’) from dual;
***5000***
 select ename, lpad(rpad(ename, length(ename)+3, ‘*’), length(ename) +6, ‘*’) padded
from emp;
Ename Padded
Ram ***RAM***
Sridhar ***Sridhar***
Anil Kumar ***Anil kumar***

 Ltrim(s), Rtrim(s), trim(s):


Used to eliminate the repeting characters (default space) from given string.
 Select Ltrim(‘sssram’, ‘s’), rtrim(‘ramsss’, ‘s’), trim(‘sssramsss’, ‘s’)
from dual;
o/p : RAM
 Select * from student where trim(name) = ‘mahesh’;
 Update student set name = trim(name);

 Replace(s, c1, c2):


Replaces character c1 with c2 in given string.
 Select replace(‘jack and jue’, ‘j’, ‘bl’) from dual;
Black and blue

Page 14 of 43
SQL Satya Manchiganti’s

 Translate(s, c1, c2):


Similar to replace but c1 & c2 must have equal no of char’s.
 Select ename, translate(ename, ‘AEIOU’, ‘aeiou’) from emp;
Ename Translate
RAM Ram
HARI HaRi
ARUN aRuN

 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

 Select sysdate from dual;  28-aug-08(‘dd-mm-yy’)

 Select sysdate, add_months(sysdate, 12), add_months(sysdate, 12),


add_months(sysdate, -12) from dual;
28-aug-08 28-aug-09 28-aug-07

 Select next_day(sysdate, ‘Sunday’) from dual;


31-aug-08
 Select last_day(sysdate), last_day(’15-feb-08’), last_day(’10-sep-08’) from dual;
31-aug-08 29-feb-08 30-sep-08

 Select ename, hiredate, add_months(hiredate, 6) “incr day” from emp;


 Select ename, job, sal, hiredate, months_between(sysdate, hiredate) “experience” from
emp;

 Select ename, job, sal, hiredate, round(months_between(sysdate, hiredate))/12 “exp”


from emp;

 Select round(sysdate, ‘day’) from dual; 31-aug-08


 Select round(sysdate, ‘month’) from dual; 1-sep-08
 Select round(sysdate, ‘year’) from dual; 1-jan-09
 Select round(to_date(10-aug-08), month) from dual;  1-aug-08
 Select trunk(sysdate, ‘day’) from dual;  24-aug-08
 Select trunk(to_date(’26-aug-08’), ‘day’) from dual;  24-aug-08

DATE Arthematic:
Supports to perform addition and subtraction on date results are manipulated interns of
days and o/p will be date.

 Select sysdate, sysdate+10, sysdate-10 from dual;


29-aug-08 8-aug-08 10-aug-08
 Select ename, job, sysdate-hiredate “exp” from emp;
 Select sysdate+sysdate from dual;  Error

Date conversion formats:


Dd  29 HH  6
Ddd  242 HH12  6
Dy  FRI HH24  18
Day  Friday mi  55
Mm  08 ss  46
Mon  aug cc  21(century)
Month  august Q  3(quarter of year)
Yy  08 ww  32(week of the year)
Yyyy  2008 w  4(week of the month)
Year  Two thousand eight
Sp  spell out
Ddsp  twenty nine am/pm

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.

 Select to_char(sysdate, ‘ddd’) from dual  242


 Select to_char(sysdate, ‘dd, day, month, year, HH24’) from dual;
29, Friday, august, two thousand eight, 19
 Select to_char(sysdate, ‘dd/mm/yyyy HH:MI:SS AM’) from dual;
29/08/2008 7:05:16 PM
 Select to_char(sysdate, ‘cc’), to_char(sysdate, ‘Q’), to_char(sysdate, ‘ww’),
to_char(sysdate, ‘w’), to_char(sysdate, ‘ddsp’) from dual;
21 3 32 4 twenty nine.
 Select ename, hiredate, to_char(hiredate, ‘day’) from emp;
 Select ename, hiredate, to_char(hiredate, ‘day’) from emp wehre
trim(to_char(hiredate, ‘day’)) = ‘Monday’;

To_date(c, ‘format’):
 Use to convert the given character into date.
 Format indicates in which it is available.

 Select to_date(‘100’, ‘ddd’) from dual;  9-apr-08


 Select months_between(to_date(‘12/24/2009’, ‘mm/dd/yyyy’),
to_date(‘16/10/01’, ‘dd/mm/yyyy’)) from dual;
 Select name, to_char(dob, ‘dd/mm/yyyy’) from student;

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;

Changing system date format:


 Alter session set nls_date_format = ‘dd-mm-yyyy HH:MM:SS’;
 Select sysdate from dual;
 Insert into emp(eno, ename, hiredate) values(101, ‘ram’, ‘1-sep-2008 j10:35:45’);

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.

 Select count(*) from emp;


 Select sum(sal) from emp;
 Select count(*), sum(fee) from student where course = ‘oracle9i’;
 Select count(*), sum(sal), avg(sal), min(sal), max(sal) from emp where deptno = 30;
 Select stddev(sal), variance(sal) from emp;
 Select count(comm), sum(comm), avg(comm.) from emp;

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

 Update student set sex = decode(sex, ‘m’, ‘f’, ‘f’, ‘m’);

 Show user  scott


 Show error
 Show err
 Select uid form dual;
 Select ename, vsize(ename), sla, vsize(sal), hiredate, vsize(hiredate) from emp;
 Select least(‘a’, ‘b’, ‘A’, ‘B’, ‘z’) form dual; A
 Select least(’31-dec-09’, ’31-aug-09’, ’22-aug-08’) from dual;  22-aug-08
NOTE:
Min/max are applicable for table column
Least/greatest are applicable for given list of values

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.

 Select deptno, sum(sal) from emp;  Error


 Select deptno, sum(sal) from emp group by deptno;

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.

 Select * from emp order by name;


 Select ename, job, deptno, sal from emp order by sal desc;
 Select empno, ename, sal, sal*.25 da, sal*.35 HRA, from emp where sal>=7000 order by 5
desc;
 Select course, count(*), sum(fee) from student group by course order by 2 desc; HRA
 Select deptno, job, ename, sal from emp order by deptno, job desc;
Deptno Job
10 salesman
10 manager
10 clerk
20 president
20 mgr
20 analyst

Page 20 of 43
SQL Satya Manchiganti’s

 Select job, count(*), sum(sal), min(sal), max(sal), avg(sal) from emp


where deptno =30
Group by job, empno
Having count(*) >1 or avg(sal) >= 2500
Order by empno desc

Where Group by Count/sum Having Order by

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

 Select worker.name “subordinate”, manager.ename “superior” from emp worker, emp


manager where worker.mgr = manager.eno;

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

Q1 Q2 Union All : ABCDEAB


A E Union : ABCDE
B A Intersect : AB
C B Minus : CD
D

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;

 Select name from student where course = ‘ora9i’ intersect


Select name from student where course = ‘D6i’ intersect
Select name from student where course = ‘unix’;
-- students who joined for all courses.
 Select eno, ename, job, sal, emp.dno, dname, loc from emp, dept where emp.dno =
dept.dno(+) union select eno, ename, job, sal, emp.dno, dname, loc from emp, dept where
emp.dno (+) = dept.dno;
--all employees and all dept details.

Making of copy of table:


 Create table emp as select * from emp;
 Create table stu_oracle as select * from student where course ‘oracle 9i’;
 Create table employ as select * from emp where 1>2;
--copies only structure.
 Create table emp_pays as select empno ecode, sal basic, sal*.25 HRA from emp;

Page 24 of 43
SQL Satya Manchiganti’s

SQL Environment settings:


1. Set:
 Used to provide sql environment settings.
 Valid only per session.
 Set null novalue/space;
 Set feedback off/on  supported with all sql stmts.
 Set heading off/on
 Set pause off/on  page by page display
 Set linesize 200/80  no of characters per line.
 Set pagesize 120/14/24  no of lines per page.
 Set autocommit on/off  valid for DML stmts.

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.

3. SQL editor commands:


I  insert mode, it will add in next line
A  append mode, it adds in same line.
Ed  opens editor.
/  run the buffer content.
L  list the buffer content.
c/old/new  change the column/word in sql stmt.
Save <filename>  stores the buffer context into .sql file.
Ed <filename>  opens file in editor (notepad)
Get <filename>  displays the file.
@<filename>  execute the 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 the employees who got highest pay.


 Select * from emp where sal = (select Max(sal) from emp);

List the employees whose salary is more than avg sal.


 Select * from emp where sal > (select avg(sal) from emp);

Raise salary 20%, if sal is less than avg sal.


 Update emp set sal = sal + sal *.2 where sal < (select avg(sal) from emp);

List the employees who are having sub ordinates.


 Select * from emp where empno in (select distinct mgr from emp);

Remove the employees who didn’t got increments.


 Delete from emp where empno not in (select distinct empno from incr);

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;

Employees who got maximum no of 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) = (select max(count(*)) from incr group by empno);

Page 26 of 43
SQL Satya Manchiganti’s

Special Operators in sub queries:


1. Any or Some:
Fix the smallest value from the result of inner query.
2. All:
Fix the largest value from the result of inner query.
3. Exists:
Returns True/False.
Gives the status of inner query.
If inner query is success it returns true otherwise it returns false.

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);

Any - O/p : 3000 All – O/p: 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);

Correlated Sub Query:


 In a correlated sub query first outer query will be executed and based on the output of outer query
inner query will be executed.
 If outer query retrieves ‘N’ records inner query will be executed for ‘N’ times.
 A column from outer query will be substituted in the inner query condition using a table alias name
is known as “correlated column”.
 There will be continuous relationship between the 2 queries based on correlated column.
Ex:
List the emp details who got more than 1 incr.
 Select * from emp e where 1 < (select count(*) from incr where empno = e.empno);

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.

2. Entity integrity rules:


Use to restrict duplicate values into 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.

3. Referential integrity rules:


Use to establish relationship between two tables.
a. REFERENCES (Foreign key):
 Used to establish relationship between two tables.
 A foreign key can be related to primary key column or unique constraint
column of other table.
 It accepts null values and duplicate values.
T1 T2
C1(pk) C1(fk)

Default: Use to define initial value for


a table column.

Page 29 of 43
SQL Satya Manchiganti’s

To define the constraints, there are two methods…


a) Column constraint syntax.
b) Table constraint syntax.

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);

Constraint error no’s:


NN  can’t insert null into(“SCOTT”.”STUDENT_B”.”SNAME”)
UNQ  check constraint(SCOTT.SYS – C005105) Violated.
CHK  check constraint(SCOTT.SYS –C005104) vilated.

 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);

Dept Insert Delete


------- --------
1 - Dept 3 - Dept
Emp 2 – Emp 2 - Emp
3 – Incr 1 - Incr

Incr

Page 30 of 43
SQL Satya Manchiganti’s

On delete cascade: (clause)


 Automatically removes the child rows whenever parent record is removed.
 It has to be specified with every child table along with references constraint.
 It can’t be assigned separately.
 It is activated by delete stmt on parent table.
Ex:
 Create table emp (eno number(9) primary key, enmae varchar(90) not null, sex char(1) check
(sex in (‘M’, ‘F’)), dno number(9) references dept on delete cascade);
 Create table incr(eno number(9) not null references emp on delete cascade, amt
number(10,2) not null);
 Drop table dept  Error, depending rows exists.
 Drop table dept cascade constraints;

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.

Oracle constraint error no’s:


NOT NULL  -1400
UNIQUE  -00001
CHECK  -2290
REFERENCES -2291 --parent key not found.
-2292 --depending child rows exists.

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));

Adding constraints to existing tables:


 Alter table dept add constraint pk_dept primary key(dno);
 Alter table dept add constraint unq_dname unique(dname);
 Alter table emp add constraint pk_emp primary key(empno);
 Alter table emp add constraint chk_sal check(sal>= 3000);

Page 31 of 43
SQL Satya Manchiganti’s

 Alter table emp add constraint fk_dept foreign key(dno) references dept on delete cascade;

Adding not null & default:


 Alter table emp modify ename varchar2(90) notnull;
 Alter table emp modify hiredate date default sysdate;

Sharing constraints:
Scott:
 Grant references on dept to user1;

Self Reference Key:


 Table referencing to itself.
 Same table acts as a parent to itself.
 Table must have similar column to apply this.

Removing constraints:
Alter table <t_name> drop constraint <cons name>;
-- In place of “DROP”, we can use disable/enable.

 Alter table emp drop constraint chk_sal;


 Alter table emp disable constraint chk-sal;
 Alter table emp modify ename varchar2(90) null; Removing Not Null & Default.
 Alter table emp modify hiredate date default null;

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.

b. Table level locks:


 Used to lock complete table.
3 modes….
 Lock table emp in share mode;
 Lock table emp in share update mode; (It is a dynamic row level lock)
 Lock table emp in exclusive mode;

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

Data Base Objects in Oracle:

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;

Checks for condition


whle inserting data
into view.
It is an clause.
Page 34 of 43
SQL Satya Manchiganti’s

Read Only views:


 View based on arthematic expr’s.
 Create view emp_pays
As
Select eno ecode, sal basic, sal*.25 DA, sal*.35 HRA, sal*.15 PF from emp
where sal >= 7000;

 View based on group functions.


 Create view dept_analysis
As
Select dno count(*) ecount, sum(sal) totsal, avg(sal) avgpay, min(sal) lopay,
max(sal) hipay from emp group by deptno order by dno;

 View based on more than 1 table (JOIN VIEWS).


 Create view edept
As
Select eno, ename, job, sal, emp.deptno, dname, loc from emp, dept
Where emp.dno = dept.dno;

7.0  join views are read only views.


8.0  DML allowed on only one table
Columns through view.
i.e; key preserved tabele(KPT)
9i  DML allowed on both tables of
Views.

Key Preserved Table:


 Table whose key column is not duplicated in view result.
 Emp is KPT & Dept is non-KPT.
 DML allowed on Emp columns through view.
 Update edept set sal = sal + 3000 where eno = 7499;
 Delete from dept where eno = 7920;
 Update edept set dno = 30 where eno = 7900;
 Update edept set dname = ‘Textfile’ where dno = 10;  Error.
-- constraints are automatically activated on views whle
manipulating data

View based on View:


 Create view v1 as select * from emp;
 Create view v2 as select ename, job, hiredate, dno from v1;
 Select * from v1;
 Create table temp as select from emp;
 Select * from temp;
 Drop table emp;
 Select * from v1; --Error, [because we drop that table]
 Select * from temp;
 Create table emp as select * from temp; It is satisfied when the new emp
table must be the same structure
as previous emp table.
Page 35 of 43
SQL Satya Manchiganti’s

 Select * from v1;


 Create view v1 as select * from emp;
 Select * from v1;
 Desc v1;
 Alter table emp add mail_id varchar2(90);
 Update emp set mail_id = ename || ‘@gmail.com’;
 Select * from v1; --Error
 Desc v1; --Error

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;

Public synonym :( DBA)


 create public synonym stu_info for student;
 grant all on stu_info to public;

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;

Minvalue: indicates the sequence startup value when it is reused.


Cycle: allows to repeat the sequence to generate the numbers after
reaching max limit
Cache: allocates the temporary buffer memory to hold the sequence
of numbers generated earlier.

 Alter sequence s1 maxvalue 9999;


 Drop sequence s1;
 Desc user_sequences;
 Select * from user_sequences;

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.

 Create index idx1 on emp(job);


 Select * from emp where job = ‘CLERK’;

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’;

Function based index:


 Create index idx4 on emp(upper(job));
 Select * from emp where upper(job) = ‘CLERK’;
 Drop index idx1;
 Desc user_indexes;
 Select * from user_indexes;

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.

 Create cluster c1(dno number(2));


 Create table dept(dno number(2) primary key,…) cluster c1(dno);
 Create table emp(eno number(4) primary key,……dno number(2) references dept) cluster c1(dno);
 Create index cidx on cluster c1;
 Drop cluster c1;
 Drop cluster c1 including tables;
 Desc user_clusters;
 Select * from user_clusters;

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.

 Create role role1;


 Grant all on emp to role1;
 Grant all on dept to role1;
 Grant all on student to role1;
 Grant insert on incr to role1;
 Grant role1 to user1;
 Grant role1 to user2;
 Revoke role1 from user2;
 Revoke insert on incr from role1;
 Grant select on salgrade to role1;
 Drop role role1;
 Desc user_roles;
 Select * from user_roles;

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.

 Select rowed, dno, dname, loc from dept;


 Select rowid, eno, ename, job, sal from emp;

 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, dname, loc from dept;


 Select rownum, eno, ename, sal from emp;

 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

having mod(rownum, 2)!= 0;  Odd rows


--Retrieving alternate records.

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.

Tools for Tunning….


1. TK Proof:
TK proof is a utility that convert the .trc file(trace file, which is in semi readable
format) into readable format.
Ex:
 Tkproof xyz.trc readme.txt

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.

Explain plan for “your_precious_sql_stmt”, if you do an explain plan, oracle will


analyze the stmt and fill a special table with the execution plan for that stmt. You can
indicate which table has to be filled with the following sql command.

3. SQL Trace / Auto Trace


4. SQL Analyzer.

~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~

Page 43 of 43

You might also like