ORACLE
Database: It is collection of meaningful data.
Ex:
SNO SNAME MARKS
101 MALLI 99
102 SREE 98
103 KRISH 97
104 VISH 96
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 ';'.
Page 1 of 46
4. Every command starts with ”verb”.
5. It is similar to English. This language is developed in the year 1972. [Link], 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
four commands.
INSERT, UPDATE, DELETE, MERGE
*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));
Page 2 of 46
Ex:
Create table student (SNO number (3), SNAME varchar2(20), MARKS number(3));
Default username: Scott
Password: tiger
SQL*PLUS: It is a client environment where the developer will write the queries and
submit the queries is execution.
*TO ESTABLISH CONNECTIO:
SQL>CONN
USER NAME: SCOTT
PASSWORD: TIGER
CONNECTED
*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 into student values(102,'kiran',86);
Insert into student values(103,'Ajay',50);
Insert into student values(104,'vijay');//this statement is wrong
Insert into student values(105,'vijay',null);
Note: Null is a keyword which is used to represent unavailable or undefined symbol.
Insert into student values(106,null,null);
*SELECT: This commend is used to return the data from the table.
Page 3 of 46
Syntax1: SELECT * FROM <TABLE_NAME>;
Ex: select * from student; // * represent ALL
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; Select MARKS, SNO from student;
SNO MARKS MARKS SNO
101 60 60 101
102 85 85 102
−−−− −−−− −−−− −−−−
−−−− −−−− −−−− −−−−
108 98 98 −−−−
Select SNO, SNO, SNAME from student;
Select * from student;
Select * From student; // not case sensitive
Create table employee(ENO number(2),ENAME varchar2(20),SALARY number(5),JOB
varchar2(20));
Insert into employee values(101,'vijay',10000,'HR');
Insert into employee values(102,'ABC',33000,'GM');
*write the one column to be display in the student?
Select SNAME from student;
Select EMPNO,ENAME,SAL,JOB FROM EMP;
We can perform some calculation using Arithmetic operations to desired output.
Page 4 of 46
Ex:
Select EMPNO,ENAME,SAL,SAL*12,DEPTNO from EMP;
EMPNO ENAME SAL SAL*12 DEPTNO
101 Mallikarjuna 50000 600000 GM
102 −−−− −−−− −−−− −−−−
103 −−−− −−−− −−−− −−−−
*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.
*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),
Page 5 of 46
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.
[Link]:(character large object) used to store characters. Maximum size 4 GB.
[Link]:(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 ;)
NAME NULL TYPE
SNO NUMBER(2)
SNAME VARCHAR2(20)
MARKS NUMBER(3)
NOTE:
It is SQL*PLUS command
Short form is DESC
Page 6 of 46
*where clause: class is used to select specific rows basing on a condition.
Ex:
Select * from emp where sal>2000;
SAL
2975
2875
3000
Select * from emp where deptno = 10;
Select * from student where sno < = 103;
Select eno,ename,sal,deptno from emp where dept = 20;
Note: Data which is stored the inside the table is case sensitive.
Ex:
Select * from emp where job = 'clerk';
Select * from student where comm is NULL;
Note: is NULL is operator which is use to retrieve the rows based on NULL values.
Ex:
Select * from student where marks is NULL;
Select * from student where sname is NULL;
Distinct Keyword: it is display distinct values (unique values).
Duplicates of suppressed.
Ex: select distinct deptno from emp;
DEPTNO
30
20
10
Select distinct job from emp;
*update: The command is used to change data present in the table.
Syntax:
Update<TABLE_NAME> set <COL_NAME> = <VALUE> where <CONDITION>;
Ex:
Update student set marks = 30 where sno = 102;
Update emp set sal = 1000 where ename = 'scott';
Update emp set ename = 'Arun' where eno = 7369;
Page 7 of 46
Update emp set comm = 500 where eno = 7698;
NOTE: when where clunse is not use, all the rows are updated.
Ex:
Update emp set sal = 5000;
Update emp set sal = 3500 where comm is NULL;
Update student set marks = NULL where sname = 'kiran';
Update emp set sal = NULL where comm is NULL;
Update emp set job = 'HR', sal = 5000 where ename = 'Alen';
*DELETE: This command is used to remove the complete row from the table.
SYSTAX: Delete from <table_name> where <condition>;
*write a
Ex:
query delete command?
Delete from student where sno = 101;
Update student set sname = null, marks = null where sno = 101;
Note: when where clause is not use all the rows delete.
Ex:
Delete from student1;
*LOGICAL OPERATORS: There are three logical operators. They are
1. AND
2. OR
3. NOT
1. AND( T AND T = T):
Systax: select * from EMP where SAL > 2000 AND JOB = 'MANAGER';
Note: AND operator will return the rows when all the conditions are satisfied.
Select * from emp where SAL >2000 AND JOB = 'MANAGER' AND deptno = 30;
Select * from emp where DEPTNO = 10 OR DEPTNO = 20;
Select * from emp where SAL >2000 AND SAL < 4000;
Write a query to delete first and last rows?
Page 8 of 46
Ex:
Select * from empno = 7499 OR 7521 OR 7566;
Select * from empno =7499 OR empno = 7521 OR empno = 7566;
Note: query to display the rows who are not managers?
Select * from emp where NOT job = 'MANAGER';
Select * from emp where NOT deptno = 30;
BETWEEN: between operator is used to display the rows which is following in the
range of values.
Select * from EMP where SAL BETWEEN 2000 AND 3000;
Note: Extreme values are included
Always specify first lower limit first and then higher limit.
*IN OPERATOR:
1. IN operator will be return the rows when the values are matching in the list.
2. IN operator can be use as a replacement of OR operator.
Ex: Select * from EMP where EMPNO IN(7369,7499,7521);
Select * from EMP where DEPTNO IN(10,20);
Select * from EMP where DEPTNO IN(10,20,30);
*PATTERN MATCHING OPERATOR: They are two pattern matching operator.
1. Percentage (%)
2. Under score (_)
1. Percentage (%): This command is used to select the letters.
Ex: Select * from emp where ename like 'S%'; //starts with letter 'S'
Select * from emp where ename like 'R%'; //ends with letter 'R'
Select * from emp where ename like 'J%S'; // first letter J and last letter S
Select * from emp where ename like '%A%'; //middle letter A
Select * from emp where NOT ename like '%A%'; //not middle letter A
Page 9 of 46
2. Under Score: This command is also select the letters.
Ex: Select * from emp where ename like '_A%';
Select * from emp where ename like ' A%';
Can we display the rows who's emp name ends with last position 'E'.
Select * from emp where ename like '%E_';
Select * from emp where ename like ' ';
Note: Like keyword is used with pattern matching operator.
Select * from emp where deptno NOT IN(10,20);
*DDL (DATA DEFINITION LANGUAGE):
1. CREATE
2. ALTER
3. DROP
4. TRUNCATE
5. RENAME
2) ALTER: By using ALTER command we can perform the following task.
2.1. ADDING A NEW COLUMN
2.2. DROPING AN EXISTING COLUMN
2.3. MODIFYING A COLUMN
2.4. RENAMING A COLUMN
i. ADDING A NEW COLUMN:
Syntax: ALTER TABLE <TABLE_NAME> ADD (COL1_NAME DATA TYPE(SIZE),
(COL2_NAME DATA TYPE(SIZE));
Ex: ALTER table student ADD(city varchar2(10));
ALTER table student ADD(state varchar2(10), pincode number(6));
Note: New column can be added only at last.
The new column will have null values.
Update student set city = 'Hyderabad' where sno = 101;
Update student set state = 'Andra pradesh' where sno = 101;
Update student set pincode = 500082 where sno = 101;
ii. DROPING AN EXISTING COLUMN:
Syntax: ALTER TABLE <TABLE_NAME> DROP(COL1_NAME,COL2_NAME);
Page 10 of 46
Ex: ALTER table student drop(state);
ALTER table student drop(city,pincode);
iii. MODIFYING A COLUMN: (increasing/decreasing the size of columns)
Syntax: ALTER TABLE <TABLE_NAME> MODIFY(COL1_NAME DATA TYPE(SIZE));
Ex:
ALTER table student modify(Sname varchar2(10));
ALTER table student modify(Sname varchar2(8));
Note: .we can increase and decrease as well as the size of the column.
.We can decrease the column size only when existing column values can
fit into new size.
.By using modify keyword we can change the data type of a column.
.Column should be empty to change it's data type.
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 NAME'S ARE DISPLAYED
*Difference between TRUNCATE and DELETE?
DELETE TRUNCATE
• We can Roll Back the data. * We cannot Roll Back the data.
• Rows are deleting temporally. * Rows are deleting permanently.
• Where clause can be used. * Where clause cannot be used.
Page 11 of 46
• Delete is sub language DML. * Delete is sub language DDL.
5) Rename: This command is used to change the table name.
Syntax: RENAME <OLD_TABLE_NAME> TO <NEW_TABLE_NAME>;
Ex: Rename student To student1;
Rename SALGRADE To GRADE;
NOTE: When we use a Truncate command the table gets dropped and re−created. As
the structure is effected is called as a DDL command.
All DDL command are permanent.
All DML command are Temporary.
*To see list of all the tables of a user: Select * from TAB;
*Creating duplicate tables or backup tables: By using the combination of create and
select. We can create copy of a table.
Ex:
Create table emp1 AS select * from emp; //total table copy
Create table emp2 AS select * from emp where deptno = 30; // only deptno = 30
Create table emp3 AS select * from emp where 10; // only deptno =10 is copy
Create table emp4 AS select empno, ename, wages, deptno from emp where
deptno = 20; //empno,ename,wages,deptno is coped by emp4 table
Create table emp5 AS select *from emp where 1=2; //This mean total table copy
Select * from emp where 1 = 1;
Select * from 'malli' from emp;
***Right click properties options and select quick edit modifier and ok.
/ Run the same query
ED Open the Buffer command
SET NUM 5
SCOTT is a new user
***Creating a new user:
Connect in the database AS DBA.
*user_name: /AS SYSDBA
*create user: create user malli Identified by malli123; //user and password created
Page 12 of 46
*giving permissions to the user;
*GRANT CONNECT, RESOURCE TO malli; //Grant Succeeded
*SHOW user To connect the current user.
**FUNCTIONS: Functions will manuplate the data items and gives the result. They are
two types of functions.
1. Group functions or multiple row functions
2. Scalar functions or single row function
1) Group functions or multiple row functions: This functions act on group of rows.
i. AVG: select AVG(sal) from emp;
ii. SUM: select SUM(sal) from emp;
iii. MAX: select MAX(sal) from emp;
iv. MIN: select MIN(sal) from emp;
v. COUNT(*): select COUNT(*) from emp; //Return total [Link] rows in the table
[Link](EXPR): Return [Link] values present in the column.
Ex: Select COUNT(sal) from emp;
Select COUNT(empno) from emp;
Select COUNT(comm) from emp;
Dual table: It is a dummy table which is generally used to perform some calculation is
seeing to the system date and etc. Dual table is collection of one row and one column
with 'X' in it.
Ex: Select SYSDATE from dual;
Select 10+20 from dual;
Select 20+40, 50+60 from dual;
2) Scalar functions or single row functions: Scalar function are decided into four
types. They are given that.
i. Character functions
ii. Number functions
iii. Data functions
iv. Conversion functions
i. 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
Page 13 of 46
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
Page 14 of 46
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;
Select * from test1;
SNO SNAME MARKS
101 ARUN 80
102 ARUN 80
103 VIJAY 80
Select * from test1 where SNAME = 'ARUN'; //101 ARUN 80
Select SNO, SNAME, LENGTH(SNAME) from test1;
SNO SNAME LENGTH(SNAME)
101 ARUN 4
102 ARUN 5
103 VIJAY 5
Select * from test1 where RTRIM(SNAME) = 'ARUN';
Select * from test1 where TRIM(SNAME) = 'ARUN';
Update test1 set SNAME = TRIM(SNAME);
Select SNO, SNAME, LENGTH(SNAME) from test1;
ii. 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
Page 15 of 46
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
g. TRUNC:(TRUNCATE) Remove the decimal points.
Ex: Select TRUNC(40.9) from dual; // 40
Select TRUNC(40.2) from dual; // 40
Select TRUNC(40.5) from dual; // 40
Select TRUNC(40.1234,2) from dual; // 40.12
Select TRUNC(685.195364,3) from dual; // 685.195
Select TRUNC(6854,−1) from dual; // 6850
Select TRUNC(6854,−2) from dual; // 6800
Select TRUNC(7777,−3) from dual; // 7000
h. ROUND: Rounds of the nearest value.
Ex: Select ROUND(40.9) from dual; //41
Select ROUND(40.2) from dual; //40
Select ROUND(40.5) from dual; //41
Select ROUND(123.863,2) from dual; //123.86
Select ROUND(123.868,2) from dual; //123.87
Select ROUND(856.81766,3) from dual; //856.818
Select ROUND(123,−1) from dual; //120
Select ROUND(140,−2) from dual; //100
Select ROUND(127,−3) from dual; //130
Select ROUND(17763,−3) from dual; //18000
i. GREATEST:
Ex: Select GREATEST(100,200,300) from dual; // 300
Page 16 of 46
j. LEAST:
Ex: Select LEAST(100,200,300) from dual; // 100
iii. 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.
Page 17 of 46
TO_CHAR
TO_NUMBER
TO_DATE
1. TO_CHAR: This functions is having two functionalities.
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.',
Page 18 of 46
'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;
Deptno Sal
30 9400
20 10875
10 8750
Select deptno,min(sal),max(sal) from emp Group By deptno;
Deptno Min Max
30 950 2850
20 800 3000
10 1300 5000
Select job, avg(sal) from emp Group By job;
Select job,count(*) from emp Group By job;
Select job,count(job) from emp Group By job;
Select Deptno, sum(Sal), min(Sal), max(Sal), avg(Sal), count(*) from emp
Group By deptno;
We can use the combination of where clause and Group By clause.
First where clause is executed on the result of where clause Group By clause is
apply.
Select deptno, sum(sal) from emp where deptno <> 10 Group By deptno;
Select deptno, job, sum(sal) from emp Group By deptno, job;
*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.
Page 19 of 46
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
Note: Order by clause should be the last change of the query.
Select deptno, sum(sal) from emp Group By deptno Having sum(sal) > 9000
Order By sum(sal) DESC;
Select deptno, sum(sal) from emp where ename <> 'King' Group By deptno;
Select deptno, sum(sal) from emp where ename <> 'King' Group By deptno
Having sum(sal) > 9000;
Select deptno, sum(sal) from emp where ename <> 'King' Group By deptno
Having sum(sal) > 9000 Order By sum(sal) DESC;
*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
Page 20 of 46
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);
Page 21 of 46
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 into student2 values(101,'Arun',50);
Insert into student2 values(101,'Arun',NULL);
Insert into student2 values(101,NULL,50);
Insert into student2 values(NULL,'Arun',50);
2. UNIQUE CONSTRAINS: This constrains will not accept duplicate values.
This constrains can be created at column level as well as table level.
Ex: Creating unique constraint at column level.
* Create table student3(Sno number(3) UNIQUE,
Sname varchar2(10),
Marks number(3));
Insert into student3 values(101,'Arun',50);
Insert into student3 values(102,'Arun',NULL);
Insert into student3 values(101,NULL,50);
Insert into student3 values(NULL,'Arun',50);
Insert into student3 values(NULL,'Arun',50);
Note: UNIQUE constraint will accept multiple will values.
*Create table student4(Sno number(3) UNIQUE,
Sname varchar2(10),
Marks number(3) UNIQUE);
Insert into student4 values(101,'Arun',50);
Insert into student4 values(102,'Arun',50);
Creating unique constraint at table level:
Ex:
* Create table student5(Sno number(3),
Sname varchar2(10),
Page 22 of 46
Marks number(3),
UNIQUE(Sno));
Insert into student5 values(101,'Arun',50);
Insert into student5 values(102,'Arun',NULL);
Insert into student5 values(101,NULL,50);
Insert into student5 values(NULL,'Arun',50);
Insert into student5 values(NULL,'Arun',50);
Note: There is no different when a constrain at column level or table level.
**3. PRIMARY KEY CONSTRIANS:
A primary key constrains of a combination of NOT NULL and UNIQUE.
A primary key constrains will not accept null values as well as duplicate values.
Primary key column is used to uniquely every row in a table.
A table can have only one primary key.
Primary key constrains can be created at column level or table level.
Create primary key constraint at column level:
Ex:
* Create table student6(Sno number(3) PRIMARY KEY,
Sname varchar2(10),
Marks number(3));
Insert into student6 values(101,'Arun',50);
Insert into student6 values(102,'Arun',50);
Insert into student6 values(101,Arun,50);
Insert into student6 values(NULL,'Arun',50);
Insert into student6 values(103,'Arun',50);
Create Primary key constraint at table level:
Ex:
* Create table student7(Sno number(3),
Sname varchar2(10),
Marks number(3)
PRIMARY KEY(Sno));
***[Link] PRIMARY KEY:
When primary key is applied a multiple columns it is called composite primary key.
Page 23 of 46
Composite primary key can be applied only at table level.
*Creating composite primary key constraint at table level:
Ex:
Create table student9(Surname varchar2(10),
Firstname varchar2(10),
Marks number(3),
PRIMARY KEY(Surname,Firstname));
Insert into student9 values('xyz','Arun',40);
Insert into student9 values('xyz','Kiran',40);
Insert into student9 values('mno','Arun',40);
Insert into student9 values('xyz','Kiran',40);
Insert into student9 values(NULL,'Arun',40);
Insert into student9 values('abc',NULL,40);
***[Link] KEY CONSTRAINS or REFERENTIAL INTEGRITY:
These constraints establish relationship between tables.
This relationship is called as parent and child relationship. It is also called master detail
relationship.
A foreign key column in the child table will only accept values which are their the
primary key column or unique column of parent table.
Creating the parent table:
Create table school(sno number(3),
Sname varchar2(10),
Marks number(3),
primary key(sno));
Insert Rows parent table:
Insert into school values(101,'Arun',90);
Insert into school values(102,'Kiran',92);
Insert into school values(103,'Amit',45);
Creating the child table:
Create table library(sno number(3) REFERENCES school(sno),
Book_name varchar2(10));
Insert Rows child table:
Page 24 of 46
Insert into library values(102,'java');
Insert into library values(103,'c++');
Insert into library values(103,'oracle');
Insert into library values(108,'dotnet'); //error
Insert into library values(Null,'DBA'); //valid
Foreign key column name need not match with primary key column name or unique
column name. But the data type should match.
To establish relationship it is mandatory that the parent table should have primary key
constraint or at least unique constraints.
Delete from school where sno = 101;
1 row deleted
Delete from school where sno = 102; //error
Message: child record found
Note: we can not delete to the row from the parent table in the corresponding value
existing child table.
*Using on delete cascade:
When using on delete cascade. We can delete the rows from the parent table and the
corresponding child table rows deleted automatically.
Create the parent table:
Create table school1(sno number(3),
Sname varchar2(10),
Marks number(3),
primary key(sno));
Insert Row parent table:
Insert into school1 values(101,'Arun',90);
Insert into school1 values(102,'Kiran',92);
Insert into school1 values(103,'Amit',45);
Creating the child table:
Create table library1(sno number(3) REFERENCES school1(sno)
on delete cascade,
Book_name varchar2(10));
Page 25 of 46
Insert Rows child table:
Insert into library1 values(102,'java');
Insert into library1 values(103,'c++');
Insert into library1 values(103,'oracle');
Insert into library1 values(108,'dotnet'); //error
Insert into library1 values(Null,'DBA'); //valid
Delete from student1 where sno = 101; //valid
1 row deleted
Delete from student1 where sno = 102; //valid
1 row deleted
One row will be deleting from parent table.
One row will be deleting from child table automatically.
*On delete set null: When delete the row from parent table. The corresponding value
will be changed to null.
Create the parent table:
Create table school2(sno number(3),
Sname varchar2(10),
Marks number(3),
primary key(sno));
Insert Row parent table:
Insert into school2 values(101,'Arun',90);
Insert into school2 values(102,'Kiran',92);
Insert into school2 values(103,'Amit',45);
Creating the child table:
Create table library2(sno number(3) REFERENCESschool2(sno)
on delete set null,
Book_name varchar2(10));
Insert Rows child table:
Insert into library2 values(102,'java');
Insert into library2 values(103,'c++');
Insert into library2 values(103,'oracle');
Insert into library2 values(108,'dotnet'); //error
Page 26 of 46
Insert into library2 values(Null,'DBA'); //valid
Delete from school2 where sno = 102; //valid
One row from parent table is deleted.
Foreign key column value 102 is changed to null.
*Create foreign key constraint at table level:
Create table school3(sno number(3),
Sname varchar2(10),
Marks number(3),
primary key(sno));
Insert Row parent table:
Insert into school3 values(101,'Arun',90);
Insert into school3 values(102,'Kiran',92);
Insert into school3 values(103,'Amit',45);
Creating the child table:
Create table library3(Rollno number(3),
Book_name varchar2(10),
Foreign key (Rollno)
REFERENCES school3(sno) on delete cascade);
*Check constraint: Check constraint is used to define domain of a column. Domain of
column means 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);
*Domain: Create table student5(sno number(3),
Sname varchar2(10),
Marks number(3) check(marks <=100));
Page 27 of 46
Insert into student5 values(101,'ARUN',60);
Insert into student5 values(102,'ARUN',80);
Insert into student5 values(103,'ARUN',160); //Error
Msg: check constraint violated
Insert into student5 values(101,'ARUN',−160);
Create table student6(sno number(3),
Sname varchar2(10),
Marks number(3) check(marks between 0 AND 100));
Insert into student6 values(101,'ARUN',60);
Insert into student6 values(101,'ARUN',80);
Insert into student6 values(101,'ARUN',160);//Error
Create table student7(sno number(3),
Sname varchar2(10);
Marks number(3),
City varchar2(10) check(city IN('HYDERABAD','CHENNAI','DELHI'));
Insert into student7 values(101,'ARUN',66,'HYDERABAD');
Insert into student7 values(101,'ARUN',66,'DELHI');
Insert into student7 values(101,'ARUN',66,'CHENNAI');
Insert into student7 values(101,'ARUN',66,'NELLORE'); //Error
Create table student8(sno number(3),
Sname varchar2(10) check(Sname = upper(sname)),
Marks number(3));
Insert into student8 values(101,'ARUN',60);// Valid
Insert into student8 values(101,'ARuN',60);// error
Insert into student8 values(101,'arun',60);// error
*Check constraint at table level:
Create table student8(sno number(3),
Sname varchar2(10),
Marks number(3),
Check (sname = upper(Sname)));
Page 28 of 46
Note: Every constraint will have a constraint name in the format of SYS_Cn(where N is
number).
Ex: SYS_c004525, SYS_c004526
*Data Dictionary tables:
Select TABLE_NAME, CONSTRAINT_NAME,CONSTRINT_TYPE from USER_CONSTRAINT;
Set of predefined table which constraints meta data information are called as data
dictionary table.
Ex: USER_CONSTRAINT
Query to find constraint_name and constraint_type of the table.
Select TABLE_NAME, CONSTRAINT_NAME, CONSTRAINT_TYPE from USER_CONSTRINT
where TABLE_NAME = 'student5'; or 'student7';
We can also provide user defined constraint_name
Ex:
Create table student9(sno number(3) CONSTRAINT MY_UN UNIQUE,
Sname varchar2(10),
Marks number(10));
In the above query ”MY_UN” is the constraint_name.
*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:
Page 29 of 46
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 [Link] = [Link];
output: EMPNO ENAME DNAME
7369 SMITH RESEARCH
7499 ALLEN SALES
7521 WARD SALES
Note:
We need to mention join conditions in the where clause.
In EQUI_JOINS we along use to equal to operator in join condition.
Page 30 of 46
Ex:
Selete empno, ename, sal, job, dname, loc
from emp, dept
where [Link] = [Link];
Selete empno, ename, sal, deptno, dname, loc
from emp, dept
where [Link] = [Link];// error
Selete empno, ename, sal, [Link], dname, loc
from emp, dept
where [Link] = [Link]; //valid
Note: we need to mention table name dot column([Link]) 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, [Link], dname, loc
from emp, dept
where [Link] = [Link] AND sal > 2000;
To improve the performance of the join we need mention table name dot column
name for all the columns.
Ex:
Select [Link], [Link], [Link],[Link], [Link], [Link]
from emp,dept
where [Link] = [Link] 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 [Link], [Link], [Link], [Link], [Link], [Link]
from emp E, Dept D
where [Link] = [Link];
Page 31 of 46
*Join the multiple tables(3 tables):
Select * from Areas;
City State
Newyork AP
Dallas Mh
Ex: Select [Link], [Link], [Link],[Link],[Link] from emp E, dept D, Areas A
where [Link] = [Link] AND [Link] = [Link];
Note: To join 'n' tables we need n−1 conditions.
*NON EQUI JOIN: When we do not use NON EQUI JOIN to operator in the join
condition is NON EQUI JOIN.
Ex:
Select * from SALGRADE;
GRADE LOSAL HISAL
1 700 1200
2 1201 1400
3 1401 2000
4 2001 3000
5 3001 9999
Select [Link], [Link], [Link], [Link] from emp e, salgrade s
where [Link] BETWEEN [Link] AND hisal;
EMPNO ENAME GRADE
7369 SMITH 1
7876 ADAMS 1
7900 JAMES 2
Select [Link], [Link], [Link] from emp e, salgrade s
where [Link] BETWEEN [Link] AND [Link] AND [Link] = 4;
*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 [Link], [Link], [Link], [Link] from emp e, emp m
where [Link] = [Link];
Empno Ename Job Ename
Page 32 of 46
7902 FORD ANALYST JONES
7869 SCOTT CLERK JONES
7900 JAMES SALESMAN BLAKE
*CARTESIAN PRODUCT:
When tables are joined without any join condition it is called Cartesian product. In the
result we get all possible combination.
Select [Link], [Link], [Link], [Link], [Link], [Link]
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 [Link], [Link], [Link], [Link], [Link], [Link]
from emp e INNER JOIN dept d ON([Link] = [Link]);
2. NATURAL JOIN: It is same as Equi join.
Ex:
Select empno, ename, sal, deptno, dname,loc from NATURAL JOIN dept;
3. CROSS PRODUCT/CROSS JOIN: It is same as Cartesian product.
Ex:
Select [Link], [Link], [Link], [Link], [Link], [Link]
from emp e CROSS JOIN dept d; //14*4 = 56 rows are displayed.
*DEFAULT:
Ex:
Create table stu1(sno number(3),
Sname varchar2(10),
Marks number(3) default 100,
Doj Date DEFAULT sysdate);
Insert into stu1(sno, sname) values(101,'malli');
Insert into stu1 values(102,'ARUN',40,'11−JAN−09');
Insert into stu1 values (103,'KIRAN',NULL,'12−FEB−10');
SNO SNAME MARKS DOJ
101 malli 100 26−JUN−12
102 ARUN 40 11−JAN−09
Page 33 of 46
103 KIRAN 12−FEB−10
*SUPER KEY: Combination of columns which can be used unique key identify every
row is called as super key.
Table object
Column Attributes
Row Tuple/Record
*OUTER JOINS: It is extension of EQUI JOINS.
In outer joins we get match as well as non matching rows.
(+) This called as outer join operator.
1. RIGHT OUTER JOIN:
SQL Syntax:
Select [Link], [Link], [Link], [Link], [Link], [Link]
from emp e, dept d
where [Link](+) = [Link]; //14 + 1 = 15 rows
empno ename sal deptno dname loc
7900 james 950 30 sales chicago
8963 adams 1400 20 clerk newyork
6798 adams 2000 10 sales india
anaylist ap
*ANSI SYNTAX OF RIGHT OUTER JOIN:
ANSI SYSTAX:
Select [Link], [Link], [Link], [Link], [Link], [Link]
from emp e RIGHT OUTER JOIN dept d ON([Link] = [Link]);
2. LEFT OUTER JOIN:
SQL Syntax:
Select [Link], [Link], [Link], [Link], [Link], [Link]
from emp e, dept d
where [Link] = [Link](+); //14+3 = 17 row displayed
ANSI SYNTAX OF LEFT OUTER JOIN:
ANSI SYNTAX:
Select [Link], [Link], [Link], [Link], [Link], [Link]
from emp e LEFT OUTER JOIN dept d ON([Link] = [Link]);
Page 34 of 46
3. FULL OUTER JOIN:
ANSI SYNTAX:
Select [Link], [Link], [Link], [Link], [Link], [Link]
from emp e FULL OUTER JOIN dept d ON([Link] = [Link]);
//14 + 2 + 3 = 19 rows are displayed.
*SET OPERATORS: Set operators are used to retrieve the data from multiple tables.
They are different types.
1. UNION:
Select * form student10;
Sno sname marks
101 Arun 40
102 Arun 50
103 Arun 69
Select * from student20;
Sno sname marks
103 Arun 90
104 Arun 60
Union Syntax: (no duplicates)
Select sno from student 10
Union //0/p sno: 101 102 103 104
Select sno from student 20;
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 // o/p sno: 103
Select sno from student 20;
Page 35 of 46
4. MINUS:
Select sno from student 10
Minus //o/p sno: 101,102
Select sno from student 20;
Select sno from student 20
Minus // o/p sno: 104
Select sno from student10;
RULES OF SET OPERATORS:
1. Number of columns used in the query should match.
2. Column data type should match for the queries in set operators.
Select empno from emp
Union
Select sno from student10
Union
Select deptno from dept; // valid
**TCL (Transaction Control Language): It is collection of three commands. They are
1. COMMIT
2. ROLLBACK
3. SAVE POINT
*Commit: This command is used to make changes permanent to the data base.
Syntax: COMMIT;
Ex:
Create table student(sno number(3),
Name varchar2(10),
Marks number(3));
Insert into student values(300,'Arun',69);
Insert into student values(301,'Kiran',69);
Insert into student values(302,'Naga',69);
Page 36 of 46
Select * from student300;
Create table student1(sno number(3),
Name varchar2(10),
Marks number(3));
Insert into student1 values(300,'Arun',69);
Insert into student1 values(301,'Kiran',69);
Insert into student1 values(302,'Naga',69);
COMMIT;
In three ways we can make changes permanent to the data base.
1. By using command COMMIT
2. By using DDL command
3. By using the environment using EXIT command
*ROLLBACK: The rollback will undo the changes which are not permanent.
Syntax:
ROLLBACK;
Ex:
Create table student2(sno number(3),
Name varchar2(10),
Marks number(3));
Insert into student2 values(300,'Arun',69);
Insert into student2 values(301,'Kiran',69);
Insert into student2 values(302,'Naga',69);
COMMIT;
Insert into student2 values(304,'Arun',69);
Insert into student2 values(305,'Kiran',69);
Select * from student2; //display 5 rows
ROLLBACK;
Select * from student2; //display 3 rows there are permanently
Page 37 of 46
*SAVE POINT: Save points are logical marking given for series of transaction.
Instead of complete rollback we can rollback to a save point.
Syntax: SAVEPOINT<SAVEPOINT_NAME>;
Ex:
Create table student3(sno number(3),
Name varchar2(10),
Marks number(3));
Insert into student3 values(300,'Arun',69);
Insert into student3 values(301,'Kiran',69);
Insert into student3 values(302,'Naga',69);
Insert into student3 values(303,'Arun',69);
Insert into student3 values(304,'Kiran',69);
SAVEPOINT A;
Insert into student3 values(305,'Naga',69);
Insert into student3 values(306,'Kiran',69);
Insert into student3 values(307,'Naga',69);
Select * from student3; //8 rows displayed
ROLLBACK;
Select * from student3; //5 rows are displayed
Create table student4(sno number(3),
Name varchar2(10),
Marks number(3));
Insert into student4 values(300,'Arun',69);
Insert into student4 values(301,'Kiran',69);
SAVEPOINT P;
Insert into student4 values(302,'Naga',69);
Insert into student4 values(303,'Naga',69);
Page 38 of 46
SAVEPOINT Q;
Insert into student4 values(304,'Naga',69);
Insert into student4 values(305,'Naga',69);
Select * from student4; // 6 rows
ROLLBACK;
Select * from student4; //0 rows
Note: All the save points are lost when the DB is permanent.
***DCL (Data Control Language):
They are two Data Control Languages.
1. GRANT
2. REVOKE
Schema: Schema is a memory location which is associated to a user.
It is collection of objects.
Privilege: privileges are permissions (rights given to a user)
They are two types of privileges.
1. System Privileges
2. Object Privileges
*System Privileges: These privileges are given by DBA to user.
*Object Privileges: These Privileges are given by one user to another user.
*GRANT: Grant command is used to Grant the privileges to the user.
Syntax:
GRANT <PRIVILEGE_NAME1>,<PRIVILEGE_NAME2> TO <USER_NAME>;
Ex:
Create user kiran IDENTIFIED by kiran123;
Create user naga IDENTIFIED by naga123;
DBA> GRANT CONNECT, RESOURCE to kiran;
*Object Privileges: These privileges are given by one user to another user.
Page 39 of 46
DBA
KIRAN> create table student(Sno number(3),
Name varchar2(10),
Marks number(3));
KIRAN> insert into student values(101,'Arun',99);
KIRAN> insert into student values(101,'Anil',97);
KIRAN> insert into student values(101,'Anitha',95);
COMMIT;
Select * from student;
AJAY> select * from student; //There is no response
KIRAN> GRANT select ON student TO AJAY; // KIRAN given privileges to AJAY
Examples of object privileges are select, insert, update, drop and alter etc.
KIRAN> GRANT insert, update ON student TO AJAY;
AJAY> insert into [Link] values(104,'Nandini',89);
AJAY> update [Link] set sno = 102 where ename = 'Arun';
KIRAN> GRANT ALL ON student TO AJAY,ANIL;
KIRAN> GRANT select ON student TO public;
**REVOKE: This command is used to get back the privileges which are granted.
Syntax: REVOKE<privilege_name><privilege_name> ON <table_name> from
<user_name>;
Ex:
KIRAN> REVOKE select, insert ON student from AJAY;
Page 40 of 46
KIRAN> REVOKE ALL ON student from AJAY_ANIL;
KIRAN> REVOKE select ON student from public;
**DML (data manipulation language)
MERGE: MERGE command is used as a combination of insert and update.
Select * from student10; // 3 rows are displayed
SNO SNAME MARKS
101 Arun 30
102 Anil 40
103 Kiran 50
Select * from student20; // 2 rows are selected
SNO SNAME MARKS
101 James 90
105 Smith 50
KIRAN> merge into student10 s1
2> using student20 s2
3> on([Link] = [Link])
4> when matched
5> then updated set sname = s2, sname, marks = s2, marks
6> when not matched
7> then insert(sno, sname, marks) values([Link], [Link], [Link]);
o/p: 2 rows merge
SNO SNAME MARKS
101 James 90
102 Anil 40
103 Kiran 50
105 Smith 50
Note: There will be no changes student20 table.
Delete from emp where ename = null;
Select * from emp where eno = 7369 or eno = 7499 or eno = 7521;
Select * from emp where eno IN(7369,7499,7521);
**PSEUDO COLUMNS:
Page 41 of 46
1. ROWNUM: It is ROWNUM is a pseudo column which starts with one and
increment by 1. (1 and 1+1)
Ex:
Select Rownum, empno, ename, sal, deptno from emp;
Rownum values are temporary.
Rownum values are generated when query is executed.
Rownum values generation always starts with one and increment by one.
*Query to display first three rows from emp table?
Select * from emp where Rownum <=3;
Select * from emp where Rownum <=10;
*write a query to display 5th row of emp table?
Select * from emp where Rownum <=5
Minus
Select * from emp where Rownum <=4; //5th row is display
*write a query to display 3rd row to 7th row?
Select * from emp where Rownum <=7
Minus
Select * from emp where Rownum <=2; //3rd to 7th row display
**ROWID:
ROWID is pseudo column which contains hexadecimal values.
ROWID value indicates the address where the row is store in the database.
ROWID values are permanent.
Ex:
Select ROWID, empno, ename, sal, deptno from emp;
*Difference between ROWNUM and ROWID?
ROWNUM ROWID
1. Rownum values starts with 1 and 1. Rowid's are hexadecimal values.
increment by one.
2. Rownum values are temporary. 2. Rowid values are permanent.
3. Rownum values are generated 3. The Rowid values are generated when
when query is exiecuted. Row is created or inserted.
Page 42 of 46
Create table student(Sno number(3),
Sname varchar2(10),
Marks number(3));
Insert into student values(101,'Arun'60);
Insert into student values(101,'Arun'60);
Insert into student values(101,'Arun'60);
Insert into student values(102,'Arun'70);
Insert into student values(102,'Arun'70);
Select * from student;
Delete from student where Rownum IN(1,2,3); // this is not right query
Select Rowid, sno, sname, marks from student;
Select min(Rowid) from student;
Select min(Rowid) from student group by sno;
*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:
Subqueries should always place in the inside.
Subqueries 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');
Page 43 of 46
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.
**Multiple Row Subquery:
When subquery returns multiple rows. It is called multiple row salary.
Note: we should multiple row operators with multiple row subqueries. They are three
multiple row operators.
1. IN
2. ANY
3. ALL
*ALL: Select * from emp
Where sal > ALL(Select sal from emp
Where deptno = 30);
Empno ename job sal
7369 SMITH salesman 2975
7860 ALLEAN ANALYST 3000
Ex: Select * from emp where sal < ALL(1600,2500,1250,3000,950);
*ANY: Select * from emp where sal > ANY(select sal from emp
where deptno = 30);
Select * from emp where sal < Any(select sal from emp where deptno = 30);
*IN: Select * from emp where ename IN('ALLEN', 'KING','FORD');
Select * from emp where sal IN(select sal from emp where deptno = 30);
*MULTIPLE COLUMN SUBQUERY:
When subquery return more then one column. It is called multiple column subquery.
We should use in operator with multiple column subqueries.
Page 44 of 46
Ex:
Select * from emp where(job,sal) IN(select job, sal from emp where deptno = 30);
o/p: Job sal
salesman 1600
manager 1250
salesman 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;
Page 45 of 46
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);
***Select * from emp e
where sal > (select AVG(sal) from emp where deptno = [Link]);
o/p: sal deptno
1600 30
2975 20
2850 30
3000 20
5000 10
3000 20
The above example is a co−related subquery.
In co−related subquery, parent query is executed first and then subquery is executed in
relation to result of parent query.
*SCALAR subquery: when we use subquery in the select clause. It is called as Scalar
subquery.
*write a query to display following output?
Deptno Dname loc sumsal
10 Accounting New York 8750
20 Research Dallas 10875
30 Sales Chicago 9400
40 Operations Boston −−−−−−
Select deptno, dname, loc, (Select sum(sal) from emp where deptno = [Link])
Sum_sal from dept d;
Scalar subquery are also called sub select.
Page 46 of 46