SQL Material
SQL Material
Management System: It is a software it helps to manage the database management system should
able to
perform the following activities very easily.
1. Inserting the new data.
2. Updating the exiting data.
3. Deleting unnecessary data.
4. Retrieving the require data.
A database along with the software which helps to manage. The database is called database
management
system (DBMS).
A DBMS which is based on relational theory is called as relational database management system.
Examples of RDBMS:
1. ORACLE
2. SQL SERVER
3. DB2
4. MYSQL
5. SYBASE
6. TERA DATA
7. MS ACCESS
SQL:
Structured query language pronounced as (SEQUEL). This language is used to communicate to
oracle database.
Features of SQL:
1. It is a command based language.
2. It is not case sensitive.
3. Every command should end with ;.
4. Every command starts with verb.
5. It is similar to English. This language is developed in the year 1972. Mr.CODD, by IBM
developed by IBM.
SUB LANGUAGE OF SQL:
1. DDL (Data Definition Language)
2. DML (Data Manipulation Language)
3. DRL/DQL (Retrieval/query)
4. TCL (Transaction Control Language)
5. DCL (Data Control Language)
*DDL: This language is used to manage database objects. It is collection of five commands.
CREATE, ALTER, DROP, TRUNCATE, RENAME
*DML: This language is used to manipulate the data you have stored. It is collection of fou
commands.
Page 1 of 36
*DRL: This language is used to retrieve the data from the database. It is collection of only one
command.
SELECT
*TCL: It is used to maintain the transaction of Oracle database. It is collection of three commands.
COMMIT, ROLLBACK, SAVEPOINT
*DCL: This language is used to control the axis of the data to the users it is collection of two
commands.
GRANT, REVOKE
TABLE: Table is an object which is used to store some data. In general it is collection of Rows and
Columns.
Create command: This command is used to create a table.
Syntax:
CREATE TABLE<TABLE_NAME>(COL_NAME1 DATATYPE(SIZE),COL_NAME2 DATATYPE(SIZE),
COL_NAME3 DATATYPE(SIZE));
Ex:
Create table student (SNO number (3), SNAME varchar2(20), MARKS number(3));
*INSERT COMMENT:
Syntax:
INSERT INTO<TABLE_NAME>VALUES(VAL1,VAL2,VAL3,VALn);
EX:
Insert into student values(101,Arun,60);
Error: Arun
Correct: Arun
Insert into student values(101,Arun,60);
Note: for varchar to value we need enclose with single( ) codes.
Insert
Insert
Insert
Insert
into
into
into
into
student
student
student
student
values(102,kiran,86);
values(103,Ajay,50);
values(104,vijay);//this statement is wrong
values(105,vijay,null);
Note: where we use * all the information (ALL the columns and the rows are display).
Syntax2: for insert command:
INSERT INTO <TABLE_NAME> (COL1,COL2,..COLn) VALUES (VAL1,VAL2,.VALn);
Ex: insert into student (SNO,SNAME) values (106,Amit);
*insert the values at runtime using & operator:
Ex: INSERT INTO STUDENT VALUES (&SNO,&SNAME,&MARKS);
*SELECTING SPECIFIC COLUMNS:
Ex:
Select SNO, MARKS from student;
SNOMARKSMARKSSNO
101
60
102
85
------------108
98
101
102
----------
600000
-------
GM
-------
*Columns ALIAS: Column ALIAS user defined column heading given to the required column.
Ex:
Select EMPNO,ENAME,SAL,SAL*12 ANNUAL_SAL,DEPTNO from EMP;
Select EMPNO ROLL_NO,ENAME,SAL from EMP;
Note:
1. Column Alias can be provides for any column.
2. Column Aliases are temporary.
3. The scope of column Alias is to respect to the same query.
Page 3 of 36
*DATA TYPES:
1. CHAR: The data type is used to store alpha numeric values.
It can be also store special symbols like -,:,/,* and etc.
This data type of fixed size. The Maximum size is 255 bytes.
Note: Memory is not used efficiently.
2.VARCHAR2: This data type it can store alphanumeric values special symbols like -,:,_
and etc. This data type is of variable size. Maximum size 4000 bytes.
Note: Memory is efficiently used.
3.NUMBER(P,S): p-precision/s-scale
This data type used to store numeric values maximum size 38 digits.
4.DATE: This data type is used to store date values it will not have size.
Range 01-JAN-4712 BC TO 31-DEC-9999 AD
Default Date format is DD-MM-YY.
Ex:
Create table student1(SNO number(2),
SNAME varchar2(20),
MARKS number(3),
DOJ Date);
Insert into student1 values(101,Ravi,99,SYSDATE);
5.LONG: Similar to varchar2 data type. Maximum size 2 GB.
6.RAW: used to store Images,logos,digital signatures etc. Maximum size 255 bytes.
7.LONG RAW: Similar to RAW data type. Maximum size 2 GB.
8.CLOB:(character large object) used to store characters. Maximum size 4 GB.
9.BLO:(binary large object) used to store binary data. Maximum size 4 GB.
10.BFILE:(binary file)
*Describe command: This command is used to see the structure of the table.
Ex:
DESCRIBE Student //(not use ;)
NAMENULLTYPE
SNO
SNAME
MARKS
NUMBER(2)
VARCHAR2(20)
NUMBER(3)
NOTE:
It is SQL*PLUS command
Short form is DESC
Page 4 of 36
EXIT
CONN
ARE SQL*PLUS
CL SCR
COMMANDS
ALL
iii.
iv.
RENAMING A COLUMN:
Syntax: ALTER TABLE <TABLE_NAME> RENAME COLUMN<OLD_COL_NAME>
TO <NEW_COL_NAME>;
Ex:
ALTER table emp rename column SAL TO WAGES;
3) DROP: This command is used to rename the table from the database.
Syntax: DROP TABLE <TABLE_NAME>;
Ex:
DROP table student;
DROP table emp;
4) TRUNCATE: This command is used to remove all the rows from the table.
Syntax: TRUNCATE TABLE <TABLE_NAME>;
Ex: TRUNCATE table student;
Select * from TAB; // ALL TABLE NAMES ARE DISPLAYED
properties
/
Run the same query
ED
Open the Buffer command
SET NUM
5
SCOTT is a new user
i.
i. Character functions
ii. Number functions
iii.
Data functions
iv.
Conversion functions
Character functions:
a. Upper: converts into lower case to upper case.
Ex: Select upper(oracle) from dual; //ORACLE
b. Lower: This function is convert to the upper to lower case.
Ex: Select lower(ORACLE) from dual; //oracle
Select ENO, lower(ENAME), SAL from emp;
c. INITCAP: First letter is capital and reaming letters are small letters.
Ex: Select INITCAP(oracle training) from dual; //Oracle
Select INITCAP(ORACLE TRAINING) from dual; //Oracle
d. LENGTH: Returns length of the string.
Ex: Select LENGTH(oracle) from dual; //length 6
Select LENGTH(MALLIKHARJUNA) from dual; //length 13
Select * from emp where length(ename) = 4;
e. LPAD: pads the character towards the left side.
Ex: select LPAD(oracle,10,z) from dual; //zzzzoracle
f. RPAD: Rpad the character towards the right side.
Ex: Select RPAD(ORACLE,10,X) from dual; //ORACLEzzzz
Select LPAD(RPAD(ORACLE,8,Z,10,Z) from dual; //Nesting function
g. LTRIM:
Ex: Select LTRIM(zzoracle,z) from dual;
h. RTRIM:
Ex: Select RTRIM(ZORACLEZZZ,Z) from dual; //ZORACLE
Select RTRIM(oracle) from dual; // oracle
Select RTRIM(ORACLE
) from dual; // ORACLE
Select LENGTH(RTRIM(ORACLE )) from dual; // length is 6
i. TRIM: Removes the specified characters from both sides.
Ex: Select TRIM(z from zzoraclezz ) from dual;
Select TRIM(
ORACLE
) from dual;
j. INSTR: Returns the passion of the string
Ex: Select INSTR(ORACLE,A) from dual; //3
Select INSTR(oracle,H) from dual;
Select INSTR(DATABASE,A) from dual; //2
k. SUBSTR: Returns the part of the string.
Ex: Select SUBSTR(ORACLE,2,3) from dual; //RAC
Select SUBSTR(ORACLE,2,4) from dual; //RACLE
Select SUBSTR(ORACLE,2,1) from dual; //R
Select SUBSTR(ORACLE,3,2) from dual; //AC
Select SUBSTR(ORACLE,3,10) from dual; //ACLE
Select SUBSTR(ORACLE,3) from dual; //ACLE
l. CONCAT: To join the two words. It will accept only two character.
Ex: Select concat(MAGA,STAR) from dual; //MAGASTAR
Select concat(concat(MAGA,STAR),CHIRU) from dual;
Page 10 of 36
SNAME
ARUN
ARUN
VIJAY
LENGTH(SNAME)
4
5
5
Number functions:
a. ABS: Returns absolute values
Ex: Select ABS(-40) from dual; // 40
Select ABS(40) from dual; //40
b. SQRT: Returns the squawroot values.
Ex: Select SQRT(25) from dual; // 5
Select SQRT(26) from dual; //5.09901951
c. MOD(A,B): Returns the MOD vaues.
Ex: select MOD(10,3) from dual; // 1
d. POWER(A,B):
Ex: Select POWER(2,5) from dual; // 32
e. CEIL:
Ex: Select CEIL(40.9) from dual; //41
Select CEIL(40.2) from dual; //41
Select CEIL(40.5) from dual; //41
f.
FLOOR:
Ex: Select FLOOR(40.9) from dual; //40
Select FLOOR(40.2) from dual; //40
Select FLOOR(40.5) from dual; //40
iii.
GREATEST:
Ex: Select GREATEST(100,200,300) from dual; // 300
j. LEAST:
Ex: Select LEAST(100,200,300) from dual; // 100
Datafunctions: They are four data functions.
A. ADD_MONTHS
B. MONTHS_BETWEEN
C. NEXT_DAY
D. LAST_DAY
A.ADD_MONTHS: ADD_MONTHS of months to the given date.
Ex: Select ADD_MONTHS(SYSDATE,12) from dual; // 16-JUN-13
Select ADD_MONTHS(11-APR-05,3) from dual; // 11-APR-05
B.MONTH_BETWEEN: Returns number of months b/w given the two months.
Ex: Select MONTHS_BETWEEN(11-JAN-05,11-JAN-04) from dual; // 12
Select MONTHS_BETWEEN(11-JAN-04,11-JAN-05) from dual; // -12
Select EMPNO, ENAME, SAL, HIREDATE from emp; //display emp table
Select EMPNO, ENAME, SAL,MONTHS_BETWEEN(SYSDATE,HIREDATE) from emp;
Select EMPNO, ENAME, SAL MONTHS_BETWEEN(SYSDATE,HIREDATE)/12 from emp;
Select EMPNO, ENAME, SAL, ROUND(MONTHS_BETWEEN(SYSDATE,
HIREDATE)/12) from emp;
Select EMPNO, ENAME, SAL, ROUND(MONTHS_BETWEEN(SYSDATE,
HIREDATE)/12) EXP from emp;
C.NEXT_DAY: Returns date of the specified date.
Ex: Select NEXT_DAY(SYSDATE,MONDAY) from dual; // 18-JUN-12
Select NEXT_DAY(11-JAN-05,MONDAY) from dual; // 17-JAN-05
D. LAST_DAY: Returns the last day of the month.
Ex: Select LAST_DAY(SYSDATE) from dual; // 30-JUN-12
Select LAST_DAY(11-FEB-05) from dual; // 28-FEB-05
iv.
Conversion functions:
Conversion functions are one data type to another data type conversion. They are three
conversion
functions.
TO_CHAR
TO_NUMBER
TO_DATE
a. Number to_char: This function is used only $ or u-rows and number is used 9.
Ex: Select eno,ename, TO_CHAR(sal,9,999) from emp;
Select eno,ename, TO_CHAR(sal,99,99) from emp;
Select eno,ename, TO_CHAR(sal,$9,999) from emp;
Select eno,ename, TO_CHAR(sal,8,888) from emp; // invalid number format
b.Date to_char:
Ex: Select eno,ename,hiredate from emp;
Select eno,ename, TO_CHAR(HIREDATE,DD-MM-YY) from emp;
Select eno,ename, TO_CHAR(HIREDATE,DD-MM-YYYY) from emp;
Select SYSDATE from dual; // 18-JUN-12
Select TO_CHAR(SYSDATE,DD-MONTH-YY) from dual; // 18-JUN-12
Select TO_CHAR(SYSDATE,DAY) from dual; // Monday
Select TO_CHAR(SYSDATE,YYYY) from dual; // 2012
Select TO_CHAR(SYSDATE,MM) from dual; // 06
Select TO_CHAR(SYSDATE,DDD) from dual; // 170
Select TO_CHAR(SYSDATE,DD) from dual; // 18
Select TO_CHAR(SYSDATE,MON) from dual; // MONDAY
Select TO_CHAR(SYSDATE,DY) from dual; // mon
Select TO_CHAR(SYSDATE,DD-MM-YY HH:MI:SS) from dual; //18-06-12 12:40:44
Select * from emp where TO_CHAR(HIREDATE,YYYY) = 1981;
Select * from emp where TO_CHAR(HIREDATE,YYYY) = 1980;
Select * from emp where TO_CHAR(HIREDATE,MON) = DEC;
2.TO_NUMBER:
Ex: Select TO_NUMBER(LTRIM($1400,$)) + 10 from dual; // 1410
3.TO_DATE: This function is used to convert character values to data value.
Ex: ADD_MONTHS
Select ADD_MONTH(11-JAN-05,2) from dual;
Select ADD_MONTH(11-JANUARY-2005 11:45 A.M.,DD-MONTH-YYYY
HH:MI A.M),2) from dual;
Select ADD_MOONTHS(TO_DATE(11-01-2005 11:45 A.M.,
DD-MM-YYYY HH:MI A.M.),2) from dual; //11-MAR-2005
*implicit convertion:
Ex: Select * from emp where DEPTNO = 10;
Select sum(sal) from emp where deptno = 10; //8750
Select sum(sal) from emp where deptno = 20; //10875
Select sum(sal) from emp where deptno = 30; // 9400
*Group By clause: Group By clause is used to divided rows into several group. So that we can apply
group function
on each group.
Ex: Select deptno, sum(sal) from emp Group By deptno;
Page 13 of 36
Deptno
30
20
10
Sal
9400
10875
8750
equal
oracle
*Rule of group by clause: All the column in the select of list should use group functions or should
by included
in group by clause.
Select deptno, sum(sal), ename from emp Group By deptno;
Error: Not a Group By Expression
*Having clause: (to use Group By clause)
Having clause is used to filter the output from Group By clause.
Ex: Select deptno, sum(sal) from emp Group By deptno having sum(sal) > 9000;
Deptno Sum(sal)
30
9400
20
10875
*Order By clause:
Order By clause is used to arrange the rows in the table.
By default order by clause ascending order.
Null values are arranged in the last.
Ex: Select * from emp Order By sal;
Select * from emp Order By ename;
Select * from emp Order By HIREDATE; //Chronological order
1980..1985
Select * from emp Order By eno;
Select * from emp Order By job,sal;
Select * from emp Order By sal DESC; //descending order by depending the query
Page 14 of 36
> 9000
deptno;
deptno
deptno
*INTEGRITY CONSTRAINS:
Constrains are rules which are applied on tables.
Constrains helps in improving the accurency and quality of the data base.
They are five types of constrains.
1. NOT NULL
2. UNIQUE
3. PRIMARY KEY
4. FOREIGN KEY or REFERENTIAL INTEGRITY CONSTRAINS
5. CHECK
Constrains can be created at two levels
a. Column level
b. Table level
1.NOT NULL: This constrains will not accept null values.
NOT NULL constrains can be created only at column level.
Ex:
*Create table student1(Sno number(3) NOT NULL,
Sname varchar2(10),
Marks number(3));
Insert into student1 values(101,Arun,50);
Insert into student1 values(101,Arun,NULL);
Insert into student1 values(101,NULL,50);
Insert into student1 values(NULL,Arun,50);
Error: cannot insert into null to scott, student1, sno.
*Create table student2(Sno number(3) NOT NULL,
Sname varchar2(10),
Marks number(3) NOT NULL);
Insert
Insert
Insert
Insert
into
into
into
into
student2
student2
student2
student2
values(101,Arun,50);
values(101,Arun,NULL);
values(101,NULL,50);
values(NULL,Arun,50);
Insert
Insert
Insert
Insert
Insert
into
into
into
into
into
student3
student3
student3
student3
student3
values(101,Arun,50);
values(102,Arun,NULL);
values(101,NULL,50);
values(NULL,Arun,50);
values(NULL,Arun,50);
into
into
into
into
into
student5
student5
student5
student5
student5
values(101,Arun,50);
values(102,Arun,NULL);
values(101,NULL,50);
values(NULL,Arun,50);
values(NULL,Arun,50);
into
into
into
into
into
into
student9
student9
student9
student9
student9
student9
values(xyz,Arun,40);
values(xyz,Kiran,40);
values(mno,Arun,40);
values(xyz,Kiran,40);
values(NULL,Arun,40);
values(abc,NULL,40);
*Check constraint: Check constraint is used to define domain of a column. Domain of column mean
values a column can store.
Create table student4(sno number(3),
Sname varchar2(10),
Marks number(3));
Insert into student4 values(101,ARUN,66);
Insert into student4 values(102,ARUN,80);
Insert into student4 values(103,ARUN,166);
*Check constraint at table level:
Create table student8(sno number(3),
Sname varchar2(10),
Page 17 of 36
Marks number(3),
Check (sname = upper(Sname)));
Note: Every constraint will have a constraint name in the format of SYS_Cn(where N is number).
Ex: SYS_c004525, SYS_c004526
*ALTER:
*Adding Constraints: Alter command is used to add a constraint to an Existing table.
Ex:
Create table Student10(sno number(3),
Sname varchar2(10),
Marks number(3));
Insert into student10 values(101,Arun,60);
Insert into student10 values(102,Arun,80);
Insert into student10 values(103,Arun,90);
ALTER table student10 ADD(Primary key(Sno));
*Dropping a constraint:
Alter command is used to drop a constraint to an existing table.
Ex:
Alter table student10 DROP Primary key;
*Unique Constraint:
Ex:
Create table Student11(sno number(3),Sname varchar2(10), Marks number(3));
Insert into student11 values(101,Arun,60);
Insert into student11 values(102,Arun,80);
Insert into student11 values(103,Arun,90);
ALTER table student11 ADD(Unique(sno));
ALTER table student11 DROP Unique(Sno);
***JOINS: joins are used to retrieve the data from multiple tables.
Types of Joins:
1. EQUI_JOIN
2. NON EQUI_JOIN
3. SELF JOIN
4. OUTER JOIN
4.1 Right outer join
4.2 Left outer join
4.3 Full outer join
1.EQUI_JOIN: when tables are joined basing on a common column it is called EQUI_JOIN.
Ex: select empno, ename, dname from emp, dept where emp.deptno = dept.deptno;
output: EMPNO
7369
7499
7521
ENAMEDNAME
SMITH
RESEARCH
ALLEN
SALES
WARD
SALES
Page 18 of 36
Note:
We need to mention join conditions in the where clause.
In EQUI_JOINS we along use to equal to operator in join condition.
Ex:
Selete empno, ename, sal, job, dname, loc
from emp, dept
where emp.deptno = dept.deptno;
Selete empno, ename, sal, deptno, dname, loc
from emp, dept
where emp.deptno = dept.deptno;// error
Selete empno, ename, sal, emp.deptno, dname, loc
from emp, dept
where emp.deptno = dept.deptno; //valid
Note: we need to mention table name dot column(emp.deptno) name for the common column to
resolve the any table.
The common column can be retrieved from any of the table.
We can filter the data from the result of join.
Ex:
Select empno, ename, sal, emp.deptno, dname, loc
from emp, dept
where emp.deptno = dept.deptno AND sal > 2000;
To improve the performance of the join we need mention table name dot column name for all th
columns.
Ex:
Select emp.empno, emp.ename, emp.sal,emp.deptno, dept.dname, dept.loc
from emp,dept
where emp.deptno = dept.deptno AND sal > 2000;
*Table alias:
Table alias is an alternate name given to a table.
By using a table alias length of the table reduces and at the same time performance is maintains.
Table alias are create in same clause can be used in select clause as well as where clause.
Table alias is temporary once the query is executed the table alias are losed.
Ex:
Select E.Empno, E.Ename, E.sal, E.deptno, D.Dname, D.loc
from emp E, Dept D
where E.deptno = D.deptno;
*Join the multiple tables(3 tables):
Select * from Areas;
City
State
Newyork AP
Dallas
Mh
Ex: Select E.empno, E.ename, E.sal,D.dname,A.state from emp E, dept D, Areas A
where E.deptno = D.deptno AND D.loc = A.city;
Note: To join n tables we need n-1 conditions.
Page 19 of 36
*NON EQUI JOIN: When we do not use NON EQUI JOIN to operator in the join condition is NON EQU
JOIN.
Ex:
Select * from SALGRADE;
GRADE LOSALHISAL
1
700
1200
2
1201
1400
3
1401
2000
4
2001
3000
5
3001
9999
Select e.empno, e.ename, e.sal, s.grade from emp e, salgrade s
where e.sal BETWEEN s.losal AND hisal;
EMPNO ENAMEGRADE
7369
SMITH
7876
ADAMS
7900
JAMES
1
1
2
*SELF JOIN: When a table is joining to it self it is called self join. In self joins we need to create two
table aliases for
the same table.
Select empno, ename, job, mgr, from emp;
Select e.empno, e.ename, e.job, m.ename from emp e, emp m
where e.mgr = m.empno;
Empno
7902
7869
7900
EnameJobEname
FORD
ANALYST
JONES
SCOTT
CLERK
JONES
JAMES
SALESMAN BLAKE
*CARTESIAN PRODUCT:
When tables are joined without any join condition it is called Cartesian product. In the result we get a
possible
combination.
Select e.empno, e.ename, e.sal, e.deptno, d.dname, d.loc
from emp e, dept d; //14*4=56 rows are selected
*ANSI JOINS: They are the three types.
1. Inner joins: It is same as Equi join.
Ex:
Select e.empno, e.ename, e.sal, e.deptno, d.dname, d.loc
from emp e INNER JOIN dept d ON(e.deptno = d.deptno);
Page 20 of 36
enamesaldeptnodnameloc
james
950
30
adams
1400
20
adams
2000
10
anaylist
sales
clerk
sales
ap
chicago
newyork
india
2. UNION ALL:
Union All Syntax: (All rows)
Select sno from student 10
Union All
// o/p sno: 101 102 103 103 104
Select sno from student 20;
3. INSERT SECT:
Insert Sect Syntax: (common rows)
Select sno from student 10
Insert Sect
Select sno from student 20;
4. MINUS:
Select sno from student 10
Minus
Select sno from student 20;
Select sno from student 20
Minus
Select sno from student10;
Union
Select sno from student10
Union
Select deptno from dept;
// valid
ROLLBACK;
Select * from student3;
// 6 rows
//0 rows
Note: All the save points are lost when the DB is permanent.
***DCL (Data Control Language):
Page 24 of 36
KIRAN
DBA
AJAY
MARKS
90
40
50
50
*Subqueries:
Subqueries are used to get the result based on unknown values. They are different type.
1. Single Row subquery
2. Multiple Row subquery
3. Multiple column subquery
4. Co-related subquery
5. Scalar subquery
6. Inline view
*Single Row Subquery:
When subquery returns one row (1 value). It is called Single RowSubquery.
Ex: write a query to display details are having salary > ALLENS sal ?
Select * from emp where sal > (select sal from emp where ename = ALLEN);
o/p: 1600
Note: Sub queries should always place in the inside.
Sub queries are executed first and then parent query is executed by using the result of sub query.
Level Two query:
Select * from emp where job = (select job from emp where ename = ALLEN)
AND job = (select job from emp where ename = BLAKE);
Level Three query:
Select * from emp where sal > (select sal from emp
Where ename = (select ename from emp
Where empno = 7499));
Note: The above query is three level query.
Sub query can be nested upto 32 levels.
job
salesman
ANALYST
sal
2975
3000
Job
salesman
manager
salesman
sal
1600
1250
2850
Note: In the o/p we get the rows when both the values are matching.
Delete some valuesu:
Select * from student;
Select min(rowid) from student group by sno;
Select max(rowid) from student group by sno;
Delete from student
where rowid not
IN(select min(rowid) from
student group by sno);
*write a query to display the row from emp table who is having the highest salary?
Select * from emp where sal = (select max(sal) from emp);
*write a query to display all the rows who are having salary grater than AVG salary of emp table?
Select * from emp where sal >(select AVG(sal) from emp);
*write a query to display all deptno AVG salary?
Select deptno, AVG(sal) from emp group by deptno;
*Co-RELATED SUBQUERY:
When subquery is executed in relation to parent query, it is called co-related subquery.
*write a query to display all the rows who are having salary grater than AVG salary his department?
Select AVG(sal) from emp;
Select * from emp where sal > (select AVG(sal) from emp group by deptno); //invalid
Select * from emp where sal > (select AVG(sal) from emp where deptno = 10);
sal
1600
deptno
30
Page 29 of 36
2975
2850
3000
5000
3000
20
30
20
10
20
*write a query to display details of employees who are having top 5 salaries?
Select * from emp where Rownum <=5 ORDER BY sal desc;
Select * from (select * from emp ORDER BY sal desc) where rownum <=5;
*write a query to display details of 5th highest salary?
Select * from (select * from emp ORDER BY sal desc)
where rownum <=5)
minus
Select * from (select * from emp ORDER BY sal desc)
where rownum <=4;
clause
select yes
from
yes
where yes
group by no
having yes
order by no
subcaluse
scalar
inline
Page 30 of 36
*views: view is a logical representation of data from one or more then one table.
They are different types
Simple views
Complex views
Read only views
With check option views
Materialized views
*Single views: when view is created using one base table it is called as Single view.
Sybtax:
Create view<view_name> as <select STMT>;
Ex:
Create view v1 as select empno, ename, sal from emp;
View does not contain any data.
View does not consume memory location.
When we write select statement on view, we get the data from the table.
Ex: Select * from v1;
Empno
7369
7499
-------------
Ename
Smith
Allen
-----------
Sal
800
1600
-----------
Tables which are used for creating the view are called as above tables.
Select * from TAB; will gives list of all the tables and view which are the data base tables.
Ex:
Create view emp_V10 AS select empno, ename, sal, deptno, from emp
where deptno = 10;
Create view emp_V10 AS select empno, ename, sal, deptno, from emp
where deptno = 20;
Create view emp_V10 AS select empno, ename, sal, deptno, from emp
where deptno = 30;
Select * from V10;
Select * from V20;
Select * from V30;
We can perform DML operations on simple views.
Any DML operation performed on simple view will be reflected on base table.
To see the structure of the table.
Ex:
DESC V1
Name Null
Type
Empno Notnull
number(4)
Ename
varchar2(10)
Sal
number(7,2)
Page 31 of 36
In user_view from the database we get list of all the view and corresponding select statement used fo
the view.
Select view_name, Text from user_views;
*Complex view:
When a view is created using multiple base tables it is called Complex view.
Ex:
Create view Test_v7
As select e.empno, e.ename, e.sal, e.deptno,
d.dname, d.loc from emp e, dept d where e.deptno = d.deptno;
insert into Test_v7 values(7878,ravi,9000,40,HR,HYD); // Error
msg: DML operations are not allowed in complex views.
Create view Test_v8
As select empno, ename, sal, sal*12 from emp; // Error
Create view Test_v8
As select empno, ename, sal, sal*12 Annual_sal from emp;
Select * from Test_v8;
Insert into Test_v8 values(1212,GMR,1000,12000); // Error
Create view Test_v9
As select empno, ename, Lower(ename) Name from emp;
A view is called as complex view when we use arithmetic operations an functions are group by
clauses.
Create view Test_v10
As select deptno, sum(sal) sum_sal from emp group by deptno;
***Different between simple and complex views?
Simple view
Complex view
1. Created by using only one table.1. Created by using multiple tables.
2. DML operations are allowed.
2. DML operations are not allowed.
3. Should not be created using
3. Can be created using arithmetic
arithmetic operations or functions
operations or functions or group by
or group by clauses.
clauses.
Page 32 of 36
// valid
// error (invalid)
//valid
// invalid
*materialized view:
Materialized views will help improving the performance of select statement on view.
To create materialized view, the based table should have primary key.
Changes to base table will not reflect on materialized view.
Materialized view or previously called as snap short.
Ex:
Create view Test_V14
As select empno, ename, sal, deptno from emp;
Create view Test_V15
As select e.empno, e.ename, e.sal, e.deptno,d.dname,d.loc
from emp e, dept d where e.deptno = d.deptno;
select * from Test_V14;
//performance fast
Page 33 of 36
Syntax:
Create MATERIALIZED view <VIEW_NAME> AS <select STMT>;
Ex:
Create materialized view MV1
As select empno, ename, sal, deptno from emp;
Select * from MV1;
*To Refresh materialized View:
Sql> exec DBMS_SNAPSHOT.REFRESH(MV1);
Select * from MV1;
DBMS_SNAPSHOT-PACKAGE NAME
REFRESH ---procedures
Select view_name from user_views;
//
***INDEX:
Index is an object which is used to improve the performance of select statements.
Types of Indexes: They are two types of Indexes.
1. Simple Index
2. Composite Index
1.Simple Index:
When index is created on one column it is called as simple index.
Syntax:
CREATE INDEX <INDEX_NAME> ON <TABLE_NAME> (COL_NAME);
Ex:
Create index IDX1 on emp(sal);
Index should be created on columns which we regularly use in the where clause.
When a index is created a separate structure is created with first column is ROWID and second
column as indexed column.
Page 34 of 36
The Rows in the index will be arranged in the ascending order of indexed column.
IDX1
ROWID
SAL
800
950
1100
1250
1600
5000
Using which rows are displayed.
*Composite Index: when Index is created multiple columns it is called composite index.
Ex: create index IDX2 on emp(sal,job);
The above index IDX2 is used only when both the columns are used in the where clause.
Disadvantages of index:
Index will consume memory.
The performance of DML command will be decreased.
Page 36 of 36