Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

SQL Training Notes

The document provides an overview of SQL and Oracle database concepts. It defines what Oracle and RDBMS are, describes the main SQL sublanguages and commands, and provides examples of using SQL commands like SELECT, INSERT, and functions.

Uploaded by

Venkat Giri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

SQL Training Notes

The document provides an overview of SQL and Oracle database concepts. It defines what Oracle and RDBMS are, describes the main SQL sublanguages and commands, and provides examples of using SQL commands like SELECT, INSERT, and functions.

Uploaded by

Venkat Giri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

Email: - Mailankitnarula@gmail.

com

1|Page www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
SQL Training Notes
What is ORACLE?

Oracle is a RDBMS product.

RDBMS: - Relational database management system.

RDBMS divided in two parts

DBMS

DB: Database: Collection of meaning full data.

MS: Management system: software which helps to manage the database.

DBMS which follows relational theory is called RDBMS.


____________________________________________________________________
SQL stands for Structured Query Language. It is pronounced as SEQUEL.

Features of SQL:-

1. This language is used to communicate to oracle database.


2. It’s a command based language.
3. Commands are not case sensitive.
4. Data stored inside the database is case sensitive.
5. Every Command should end with ( ; ) semicolon.
6. All the data stored in oracle database are stored in the form of tables.

SQL Sub Languages:-

SQL is divided in 5 sub languages:-

1. DDL:- Data Definition Language


2. DML:- Data Manipulation Language
3. DRL/DQL :- Data Retrieval Language/Data Query Language
4. TCL:- Transaction Control Language
5. DCL :- Data Control Language

2|Page www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Commands of SQL:-

1. DDL: - This language is used to create and manage database objects.


Commands of DDL:-
Create, Alter, Drop, Truncate and Rename
2. DML: - This Language is used to manage data present in the table.
Commands of DML: -
Insert, Update, Delete and Merge
3. DRL/DQL: - This language is used to retrieve data from the table.
Commands of DRL/DQL:-
Select
4. TCL: - This language is used to maintain transactions of the database.
Commands of TCL:-
Commit, Rollback and Save point
5. DCL:-It is used to control the data and maintain security.
Commands of DCL:-
Grant and Revoke

Total we Have 5+4+1+3+2=15 commands.

Table

Is an object used to store the data.


In General, It is a collection of rows and columns.

Roll No Name Marks


101 Arun 76
102 Karan 87
103 Vipan 60
104 Sumit 80
105 Alex 78
106 David 90

Open the below mention link & copy the commands & run the commands in SQL
Developer.

https://sites.google.com/view/sqltables

3|Page www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Datatypes:-
They’re lot of data types used in oracle database.
But 3 Data types which are used mostly in database.

1. Varchar2 (size): - Used to store alphanumeric values and the values always put
it in a single courts ‘____’.
2. Number (size): - Used to store number values.
3. Date: - Used to store date values and the values always put it in a single courts
‘____’ and oracle date format is ‘DD-MMM-YY’.

SQL Commands
First Command we will learn is DDL Command.

Create:-
It is used to create a table.

Create table
(Table name) (Col_name1 datatype(size),
Col_name2 datatype(size),
Col_name3 datatype(size));

Example:-
Create table Student (Rollno number (3), Name varchar2 (10), Marks number (3));

Output we will get is table created.

Now we learn one DML Command.

Insert:-
It is used to insert the rows into the table.

Syntax:-
Insert into table_name values (value1, value2, value3);

Example:-
Insert into student values (101, ‘Arun’, 76);
Insert into student values (102, ‘Karan’, 87);
Insert into student values (103, ‘Vipan’, 60);
4|Page www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
For every insert command, the response we get is 1 row inserted.

Using null keyword: –


Null keyword is used, if we do not have value for a column.

Example:-
Insert into student values (104, ‘Sumit’, null);
Insert into student values (105, null, null);

Second syntax of insert command:-


Insert into student (Column1, Column2, Column3) Values (value1, value2, value3);

Example:-
Insert into student (Sno , Name) values (106, ‘David’);

The leftover column will have null value.

Select Command : –
Selecting the rows from the table.

To retrieve the rows from the table select command is used.

Syntax:-
Select * from (table_name);

Example:-
Select * from student;
In the above command * is the special character which is used to display all the
information from the table.

To select specific columns:-


Select (column_name1, column_name2) from table_name;

Example:-
Select Sno,name from student;
Select name from student;

Selecting specific rows:-


Where clause is used to filter the rows from the table.

5|Page www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Syntax:-
Select */ column_name from (table_name) where (condition);

Example:-
Select * from student where marks >80;

Select * from student where name =’Arun’;

Note: -Data stored inside the table is case sensitive.

Combination of selecting specific row and selecting specific columns:-

Select sno,name from student where marks >70;

Using Arithmetic operations with select command:-

select empno, ename , sal, sal* 12 , deptno from emp;

Using Column Alias:-

Column alias is process of providing user defined column heading.


Column alias is temporary.

Select empno, ename , sal, sal* 12 annual_sal , deptno from emp;

In the above query annual_sal is the column alias.

Operators

Logical operators:-

1. And
2. Or
3. Not

6|Page www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
AND

Sal>2000
Job=’MANAGER’

Select * from emp


Where sal>2000 and job=’MANAGER’;

Sal > 2000


Job = ‘MANAGER’
deptno = 10

Select * from empWhere sal>2000 and job=’MANAGER’ and deptno=10;

Only the rows which are satisfying all the condition.

OR

Select * from empWhere deptno = 10;

Select * from empWhere deptno = 20;

Output — 3 + 5 — 8

Select * from empWhere deptno =10 and deptno = 20;

SMITH –F T
MILLER- T F

Select * from empWhere deptno =10 or deptno = 20;

Not:-

Select * from EMP;

Select * from empWhere job =’CLERK’;

Select * from empWhere not job = ‘CLERK’;

7|Page www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Between: –

Sal – 1000 – 2000

Select * from empWhere sal between 1000 and 2000;

Always specify lower limit first and then upper limit

Is null : -

Display the rows those are having null.

Select * from empWhere comm = null;


Null is not a value

Select * from empWhere comm is null;

Select * from student Where marks is null;

Like Operator —%

Need all the ename first letter start with A & J

Select * from EMP Where ename like ‘A%’;

Select * from EMP Where ename like ‘J%’;

Need all the ename last letter with S

JONES
JAMES
ADAMS

Select * from empWhere ename like ‘%S’;

8|Page www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Underscore:-

Underscore is used to skip the word.

Need all the ename whose 2nd letter is A

WARD
JAMES
MARTIN

Select * from empWhere ename like ‘_A%’;

Need all the ename whose 3rd letter is R

WARD
TURNER
FORD

Select * from empWhere ename like ‘__R%’;

Need all the ename whose second last is E

ALLEN
TURNER
MILLER
JAMES

Select * from emp


Where ename like ‘%E_’;

IN

In operator is same as OR operator just change in syntax.

Need details of emp who work in dept no 10 and 20

Select * from empWhere deptno = 10 or deptno =20;

Select * from empWhere deptno in (10, 20);

9|Page www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Need details of emp who's job is Salesman & Manager

Select * from empWhere job in (‘SALESMAN’, ‘MANAGER’);

Need details of emp who's job is Salesman , Manager& Clerk

Select * from empWhere job in (‘SALESMAN’, ‘MANAGER’, ‘CLERK’);

Using Distinct keyword:-

Distinct keyword is used to get the distinct ( unique ) values. Duplicates will be
suppressed.

Example:-

Need all the deptno from emp table.

select deptno from emp;

In the above command result you will see lot of duplicate values but we don't want
duplicate values for this we are going to use Distinct Keyword.

select distinct deptno from emp;

Need distinct Jobs from emp table.

Select distinct job from emp;

Functions
Two Types of Functions:-

1) Group Functions/ Aggregate Functions:-


These Functions act on group of rows.
Sum, Max, Min, Avg, Count (*), Count (Column_name)

2) Scalar Functions/ Single Row Functions:-


These functions act on every row of the table.
A. Character/String function
B. Number function
10 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
C. Date Function
D. Conversion Function

1) Group Functions/ Aggregate Functions:-

SUM ( ):-Returns sum of value of the column.

Select sum (sal) from EMP;

Select sum (sal) from emp where deptno=10;

MAX ( ):-Returns maximum value of the column.

Select Max (sal) from emp;

Select max (sal) from emp where deptno=20;

MIN ( ):-Returns Minimum value of the column.

Select Min (Sal) from emp;

Select min (sal) from emp where deptno=10;

AVG ( ):-Returns Average value of the column.

Select avg (sal) from emp;

Select avg (sal) from emp where deptno=10;

Count (*):-Returns no of rows in the table.

Select count (*) from emp;

Select count (*) from emp where deptno=10;

Count (Column_name):-Returns no of values present in the column.

It ignores null values in the column.


Select count (comm) from emp;
Select count (deptno) from emp where deptno=10;
11 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Dual: – It is a dummy table, used to perform calculations and system date.
It is collection of one row and one column, with value X in it.
Select * from dual;
Select 10+20 from dual; —30
Select Sysdate from dual; — current date
Select systimestamp from dual; — current date, time & time zone
Select user from dual;–current user

Sysdate,Systimestamp,User are known as Pseudo Column.

2) Scalar Functions:-

Character functions: – These functions accept characters as input.

Lower ( ):- It converts upper case letters to lower case.

Select lower (‘ORACLE’) from dual;

Select empno , ename , lower(ename) from emp;

Upper ( ):- It converts lower Case letters to upper case.

Select upper (‘oracle’) from dual;

Initcap ( ):- It converts first letter of each word in upper case, keeling all other letters
in lower case.

Select initcap (‘oracle’) from dual;

Select initcap (ename) from emp;

Concat ( ):- It concatenates two strings.It accepts two or more parameters.

Select concat(‘sunil’, ‘kartik’) from dual;

Select ‘sunil’||’kartik’ from dual;

Select ‘sunil’||’ ‘||’kartik’ from dual;

select first_name||’ ‘||Last_name as Name from employees;


12 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Substr(value,m,n):- Returns characters from the starting position ‘m’ to ‘n’ characters
long.

If ‘N’ is 0 or less than 0, Null is returned.


If ‘N’ is omitted, all the characters to the end of the string is returned.

Select substr(‘oracle’,2,3) from dual; –rac


Select substr(‘oracle’,2,4) from dual; –racl
Select substr(‘oracle’,3,2) from dual; –ac
Select substr(‘oracle’,4,0) from dual; –null
Select substr(‘oracle’,2) from dual; –racle

Use emp table with same examples

Length:- Returns no of characters in the value.

Select length (‘oracle’) from dual;


Select ename,empno, length(ename) from emp;
Select * from emp where length (ename) =4;

Instr: – Returns position of the string.

Select Instr (‘oracle’,’a’) from dual;–3

Select Instr (‘database’,’a’) from dual;–2

Returns first occurrence of the character in the string.

Select Instr (‘stabilizer’,’i’) from dual;–5

Select Instr (‘stabilizer’,’h’) from dual;–0

Returns 0 when the character does not exist.

Select Instr (‘oracle’,’acl’) from dual;–3—2nd parameter can be string.

Select Instr (ename,’a’) from emp;–0-because data stored in the database is case
sensitive.

13 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Lpad: – Pad the character value towards left, to a total width of n character positions.

Select lpad (‘oracle’, 10 , ‘h’) from dual;–hhhhoracle

Select lpad(ename,10,’H’) from emp;

RPad: – Pad the character value towards right, to a total width of n character
positions.

Select rpad (‘oracle’, 10 , ‘h’) from dual;–oraclehhhh

Select rpad(ename,10,’H’) from emp;

Ltrim: – Removes the specified character towards left side.

Select ltrim(‘zzzzoracle’,’z’) from dual;–oracle


Select ltrim(‘zzzzorazcle’,’z’) from dual;–orazcle

Rtrim: – Removes the specified character towards right side.

Select rtrim(‘oraclezzzzzz’,’z’) from dual;–oracle


Select rtrim(‘orazclezzzzzzz’,’z’) from dual;–orazcle

Number Functions:-

Abs: – It returns absolute value of ‘N’.


Select abs (-324) from dual;

Sqrt: – It returns square root of ‘N’ as real value.

Select sqrt(25) from dual;–5


Select sqrt(28) from dual;– 5.29150262212918118100323150727852085142

Select sqrt(-28) from dual;–error


The value ‘N’ cannot be negative.

Power: – Returns ‘M’ raised to the power of ‘N’.

Select power (2, 5) from dual;–32

14 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Trunc:-

Select trunc(40.945234,0) from dual;–40


Select trunc(40.945234,3) from dual;–40.945

Round: – Round off the nearest value.

Select round (40.9) from dual;–41


Select round (40.2) from dual;–40
Select round (40.5) from dual;–41

Empno Ename Sal Dailt_Sal

Select empno, ename, sal, sal/30 from emp;

Select empno, ename, sal, round (sal/30) Daily_sal from emp;

Date Function:-

Create table ank_student1 (rollno number (3), name varchar2 (10),


Marks number (3), doj date);

Insert into ank_student1 values (101,’Arun’, 80, sysdate);

Insert into ank_student1 values (102, ‘Karan’ , 60, ’12-mar-18′)

Rollno Name Marks DOJ


101 Arun 80 Current date
102 Abc 60 12-MAR-18

Date value should be enclosed in ‘____ ‘. Single court.

Add_Months:- Select add_months(sysdate,12) from dual;

select add_months ( ’19-jan-18′ , 5 ) from dual; — 19-JUN-18

Months_Between:- It returns numbers of months between dates Date1 and date2.

Select months_between (’16-mar-18′ , ’16-mar-17′) from dual; — 12

15 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Select months_between (’16-mar-17′ , ’16-mar-18′) from dual; — -12
If Date 1 is later than date 2 then the result is positive number else negative.

Empno Ename Sal Experience

Select empno, ename, sal, months_between ( sysdate, hiredate ) from emp;–Get only
months between till date.

select empno, ename, sal, months_between ( sysdate, hiredate ) /12 exp from emp;–
Get years but with long value we need to do round.

Select empno, ename, sal, round (months_between ( sysdate, hiredate ) /12 ) exp
From emp;

Conversion Functions: – These functions convert values from one data type to other.

Three types of conversion functions:-

A. To_char
B. To_Date
C. To_number

To _char:- Convert date to characters.

Select Sysdate from dual—current date—dd-mon-yy

Select to_char (sysdate, ‘dd/mm/yyyy’) from dual;

Select empno, ename, sal, to_char (hiredate, ‘dd/mm/yyyy’) from EMP;

Select sysdate from dual;

Select to_char(sysdate, ‘dd-mon-yyyy’) from dual;

Select to_char(sysdate, ‘mon-dd-yyyy’) from dual;

Select to_char(sysdate, ‘yyyy-dd-mm’) from dual;

Select to_char(sysdate, ‘yyyy’) from dual;

16 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Select to_char(sysdate, ‘dd’) from dual;

Select to_char(sysdate, ‘mm’) from dual;

Select to_char(sysdate, ‘mon’) from dual;

To_number:- Convert character to number.

Select 10 +20 from dual—30


Select 10+’$200′ from dual; —error
Need to convert character to number
‘$200’ ———- > 200

Select ltrim (‘$200’, ‘$’) from dual; – ‘200’ — but ‘200’ is still a character

‘200’ ——–> 200 now we need to convert character to_number

Select 10 + to_number (ltrim (‘$200’, ‘$’)) Add_num from dual; –210


If we need result like $210 then.

select lpad(10 + to_number ( ltrim ( ‘$200’ , ‘$’) ) ,4,’$’) Add_num from dual;–$210

To_Date:- It converts characters to date values.

Select add_months (’15-mar-18′, 2) from dual; –15-MAY-18


Select add_months (’03-15-18′, 2) from dual; –error

select add_months ( to_date ( ’03-15-18′ , ‘mm-dd-yy’) , 2 ) from dual;–15-may-18


If we need to change the date format.

Select to_char(add_months ( to_date ( ’03-15-18′ , ‘mm-dd-yy’) , 2 ), ‘mm/dd/yy’)


from dual; –05/15/18

17 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Duplicate Table:-

Create table emp1 as select * from emp;--table created.

Create duplicate table with three columns from emp table:-


Empno Ename Job

Create table emp2 as select empno,ename,job from emp;

Create table where deptno=30:-

Create table emp3 as select * from emp where deptno=30;

If we need to create a duplicate table but with only column names.

Create table emp4 as select * from emp where 1=2;

When we already have table name and need to insert rows from other table.

Insert into table_name select * from table_name;


Clauses
Clauses Divided into Three parts:-

1. Group By Clause
2. Having Clause
3. Order By Clause

Group by clauses:-

Group by clause is used to divide the rows of a table into several groups.
So, that we can apply group function on each group.

Select sum ( sal ) from emp;–29025


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
18 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Deptno Sum(Sal)
10 8750
20 10875
30 9400

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

As the standard emp tables has 3 types of deptno (10, 20, 30) 14 rows of the table are
divided into 3 groups. Sum ( ) function is applied on each group.

Need avg salary for every job.

Select job,avg(sal) from emp group by job;

Need sum_sal, max_sal,min_sal,avg_sal, count_of_employees from every deptno.

Select deptno,SUM (sal) SUM_sal, MAX(sal) max_sal, MIN(sal) min_sal,


Round (AVG (sal)) avg_sal, COUNT(*) count_of_employees from emp group by
deptno;

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

In the above query, first grouping is done based on deptno and sub grouping is
done based on job.

Select deptno,ename,sum(sal) from emp group by deptno;–error

The rule of GROUP BY clause:-

All the columns in the select list should use group functions or should be included in
the group by clause.

Group functions: – Sum, Max, Min, Avg, Count (*), Count (Column_name)

19 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Having Clause:-Having clause is used to filter the results of group by clause.

Deptno Sum(sal)
10 8750
20 10875
30 9400

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


We want the result Sum (sal) > 9000

Select deptno, Sum (sal) from emp group by deptno where sum (sal) > 9000;–error

But generally we use where clause to filter the data but here we are not able to use
where clause but these values are not present in the data. This is the processed
data.When we want to filter the result by group by clause just the use the word
having instant of where.

Select deptno, Sum (sal) from emp group by deptno having sum (sal) > 9000;

Query Execution process:-


1) First the rows are grouped.
2) Second the group function is applied on the identified groups.
3) Third the groups that match the criteria in the having clause are displayed.

AVG Salary Greater than 2500 and sum of sal and deptno :-

Select deptno, round (AVG (sal) avg_sal, SUM (sal) sum_sal from emp group by
deptno Having AVG (sal) > 2500;

Required deptno,min_sal,max_sal, job=clerk, min_sal <1000: -

Select deptno, MIN (sal), MAX (sal) from emp where job =’CLERK’ GROUP BY deptno
HAVING MIN (sal) < 1000;

Order by clause:-

Order by clause is used to arrange the rows in ascending or in descending order.

Select * from emp order by sal;

20 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Select * from emp order by sal desc;
The default ordering of the data is ascending.

Select * from emp order by ename;

Numbers: – Ascending Order—0 to 9


Characters: – Alphabetical—A to Z
Date: – Chronological order—Earliest to latest
Null: – Move to last

Select ename , job, deptno, hiredate from emp ORDER BY hiredate;

Select * from emp ORDER BY job, ename;

First job order by clause in ascending order and then ename use order by clause In
ascending order.

Select ename , job, sal from emp where sal > 2500 ORDER BY JOB, ename DESC;

Select empno, ename, sal, sal*12 annual_sal from emp ORDER BY annual_sal;

We can use temporary Column or column alias as a temporary column.

Order by clause should be the last clause of the query.

DDL Commands
DDL: - Create, alter, drop, truncate and rename.

Alter command:-

Alter command is used to change the structure of the table.


We can perform following activities using Alter command

1) Adding a new column


2) Droping an existing column
3) Modifying a column
4) Renaming a column

21 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Adding a new column:-

Alter table (table_name) add (column_name datatype(size));

Example:-

Alter table student add ( city varchar2(10), state varchar2(10));

Output we will get is Table altered.

Note:- The new columns will have null values.

Droping a column:-

Alter table drop (column_name);

Example:-

Alter table student drop ( city, state);

Output we will get is Table altered.

Modifying a column:-

By using modifying we can increase and decrease the size of the column.

Example:-

Alter table student modify ( name varchar(20));

Output we will get is Table altered.

Decreasing the size:-

Alter table student modify ( name varchar(15));

Output we will get is Table altered.

22 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Note:-
To decrease the size , the existing table data should fit into new size.
By using Modify keyword , we can also change the datatype of the column.

Example:-

Alter table student modify ( name number(15));

Note:-
To change the datatype, column should be empty.

Rename a column:-

Syntax: -

Alter table <table_name> rename column <old_name> to <new_name>;

Example :-

Alter table student rename column rollno to sno;

Output we will get is Table altered.

Drop command:-

This command is used to remove the table from the database.

Syntax:-

Drop table < table_name >;

Example:-

Drop table student1;

Output we will get is Table dropped.

Truncate command:-

This command is used to remove all the rows from the table.
23 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Syntax:-

Truncate table < table_name>;

Example:-
Truncate table student;

Difference between drop and truncate:-


Drop will remove the table from the database and truncate only remove rows/data
from the table.
Rename command:-

This command is used to change the table name.

Syntax:-

Rename <old_table_name > to < new_table_name>;

Example:-

Rename student to student1;

Output we will get is Table renamed.

From now, we need to access the table by using the new name.

DML Commands
DML:Insert Update, delete and merge.

Update:-

This command is used to change the data present in the table.

Syntax:-

24 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
update table_name set col_name = value Where condition;

Example:-

update student set marks = 95 where rollno =101;

Output we will get is 1 row updated.

Updating multiple columns:-

update student set name=’uday’ , marks =48 where rollno =102;

Note:- Update command without where clause , will update all the rows.

Example:-

update student set marks=80;

Delete command:-

Delete command is used to delete the rows from the table.

Syntax:-

Delete from < table_name> where < condition >;

Example:-

Delete from student where sno=103;

Output we will get is 1 row deleted.

25 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Note:-
Delete command without where clause will delete all the rows.

Example:-

delete from student;


( All the rows are deleted )

Option 1: truncate table emp;


Option 2: delete from emp;
Differences between Delete and Truncate.

Delete Truncate
Rows are delete temporary. Rows are deleted permanent.
We can perform rollback. We cannot perform rollback.
Where clause can be used. Where clause cannot be used.

Constraints
Constraints are rules applied on tables.
Constraints increase in integrity or quality of the database.

Types of Constraints:-

1) NOT NULL
2) UNIQUE
3) PRIMARY KEY
4) FOREIGN KEY (or) Referential Integrity Constraint
5) CHECK

Declaration Style:-

Constraint can be created in two levels:-


1) Column Level
2) Table Level
26 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Column Level:-

They are declared as part of the definition of the individual column.

Table Level:-

They are declared as part of the table definition.

Create table ank_student3 (rollno number (3), name varchar2 (10), Marks number
(3));

Insert into ank_student3 values (101, ‘arun’, 40);


Insert into ank_student3 values (102, ‘ravi’, null);
Insert into ank_student3 values (101, null, 80);
Insert into ank_student3 values (null, ‘john’, 80);
Insert into ank_student3 values (101, ‘arun’, 40);

By Default – every column accepts null and duplicates.

1) NOT NULL Constraint:-

NOT NULL constraint does not accept NULL values.


To satisfy this constraint, every row in the table must contain a value.
NOT NULL constraint can be created only at column level.

Syntax:-

Create table (table_name) ( col_name1 datatype(size) NOT NULL,col_name2


datatype(size) ,col_name3 datatype(size) );

Example:-

Create table ank_student4 (rollno number (3) not null, name varchar2 (10),
Marks number (3));

27 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
insert into ank_student4 values ( 101, ‘arun’, 40);
insert into ank_student4 values ( 102, ‘ravi’, null);
insert into ank_student4 values ( 101, null, 80);
insert into ank_student4 values ( null, ‘john’, 80); — error
insert into ank_student4 values ( 101, ‘arun’, 40);

UNIQUE Constraint:-

UNIQUE constraint does not accept duplicate value.


UNIQUE constraint can be created at column level or at table level.
UNIQUE constraint will accept NULL value.

Syntax of UNIQUE Constraint at column level:

Create table (table_name) ( col_name1 datatype(size) UNIQUE, col_name2


datatype(size),col_name3 datatype(size));

Example:-

Create table ank_student6 (rollno number (3) unique, name varchar2 (10),
Marks number (3));

insert into ank_student6 values ( 101, ‘arun’, 40);


insert into ank_student6 values ( 102, ‘ravi’, null);
insert into ank_student6 values ( 101, null, 80); — error
insert into ank_student6 values ( null, ‘john’, 80); — valid

Note:- UNIQUE constraint will accept any number of NULL values

Syntax of UNIQUE constraint at table level:-

Create table < table_name>( col_name1 datatype(size), col_name2 datatype(size),


col_name3 datatype(size),UNIQUE ( col_name1));

28 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Example:-

Create table student3 ( rollno number(3) , name varchar2(10), marks number(3),


UNIQUE ( rollno ));

insert into student3 values ( 101, ‘arun’,40); — valid


insert into student3 values ( 102, ‘kiran’,75); — valid
insert into student3 values ( 101, ‘vijay’,55); — error
insert into student3 values ( null,’ashok’,85); — valid
insert into student3 values ( null,’vinay’,81); — valid

There is no difference practically , when a constraint is created at column level


or table level. You can follow any syntax.

PRIMARY KEY:-

A PRIMARY KEY constraint is combination of NOT NULL and UNIQUE constraint.


A PRIMARY KEY column will not accept NULL values and DUPLICATE values.
A PRIMARY KEY column is used to uniquely identify every row in the table.
A Table can have only one PRIMARY KEY
A PRIMARY KEY Constraint can be created at column level or at table level.

Syntax of PRIMARY KEY at Column Level:-

Create table table_name ( col_name1 datatype(size) PRIMARY KEY, col_name2


datatype(size),col_name3 datatype(size));

Example:-

Create table ank_student7 ( rollno number(3) primary Key, name varchar2(10),


Marks number (3));

insert into ank_student7 values ( 101, ‘amit’, 40 );

29 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
insert into ank_student7 values ( 102, ‘jyoti’, 40 );
insert into ank_student7 values ( null, ‘aarti’, 40 );–error
insert into ank_student7 values ( 101, ‘amit’, 40 );–error

Syntax of PRIMARY KEY at table level:-

Create table < table_name>( col_name1 datatype(size), col_name2 datatype(size),


col_name3 datatype(size),PRIMARY KEY ( col_name1));

Example:-

Create table student5 ( rollno number(3) , name varchar2(10),


marks number(3),PRIMARY KEY ( rollno ));

insert into student5 values ( 101, ‘arun’,40); — valid


insert into student5 values ( 102, ‘kiran’,75); — valid
insert into student5 values ( 101, ‘vijay’,55); — error
insert into student5 values ( null,’ashok’,85); — valid
insert into student5 values ( null,’vinay’,81); — valid

There is no difference practically , when a constraint is created at column level


or table level. You can follow any syntax.

FOREIGN KEY Constraint:-

A Foreign key constraint establishes relationship between tables.


This relationship is called as Parent-child relationship.
It is also called as Master-Detail relationship.
Foreign key column in child table will accept only the values present in the primary
key column of the parent table.
A foreign key constraint can be created at column level or at table level.

TO understand this FOREIGN KEY Constraint , have a look at this scenario:-

30 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
I have started a school.Assume only 4 students joined in my school.I create a table
with name school and enter the student details in it. Every student will have student
roll no. Roll no is primary Key.
SCHOOL
Rollno Name Age
101 Arun 25
102 Kiran 27
103 Sreeja 22
104 Sunil 30

I have appointed librarian for my school. If any student borrows book, librarian
should enter the Roll no and book name.
I create a table with name library . Every Sunday i visit my school to check whether it
is running properly or not, surprisingly , i have the following data in my library table.

Library
Rollno Book_name
104 C++
103 Java
103 Dotnet
108 Unix

If you observe, there is no student 108 in our school.


So the last row is invalid row. Probably this could be data entry mistake.
I do not want these kind of invalid data into my library table.
That means, i should create library table in such a way that it should accept only the
Rollno values which are in school table.
So, we should create a relationship between these table. This relationship is called as
parent-child relationship.

In our scenario,
School is the parent table.
Library is the child table.
Rollno column in the library table is called as FOREIGN KEY column.

31 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Note: A Foreign key column in the child table will only accept the values present in
the PRIMARY KEY column of the parent table.

Lets practically workout this scenario:-

Step 1: Creating the parent table


Step 2: Inserting rows into the parent table
Step 3: Creating child table which contains FOREIGN KEY
Step 4: Inserting rows into the child table and understand the behaviour of the
FOREIGN KEY column

Step 1: Creating parent table:-

create table school ( rollno number(3) PRIMARY KEY, name varchar2(10),


age number(2));

Step 2: Inserting rows into the parent table:-

insert into school values ( 101, ‘arun’ , 25);


insert into school values ( 102, ‘kiran’, 27);
insert into school values ( 103, ‘sreeja’, 22);
insert into school values ( 104, ‘sunil’, 30);

Step 3:- Creating Child Table

Syntax of foreign key constraint at column level:-

Create table (table_name) ( col_name1 datatype(size) REFERENCES(parent table) (


primary key col_name), col_name2 datatype(size),col_name3 datatype(size) );

Example:-

create table library ( rollno number(3) REFERENCES school ( rollno),


book_name varchar2(10));

32 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Step 4: Inserting row into the child table:-

insert into library values ( 104, ‘oracle’); — valid


insert into library values ( 103, ‘java’); — valid
insert into library values ( 103, ‘c++’); — valid
insert into library values ( 108, ‘unix’); — error

Note:-
As we have established relationship in school and library table, library table is not
accepting roll no 108. This relationship helps in improving the accuracy of the
database.

Insert into ank_library values (null, ‘oracle’); — valid

Note:-
A FOREIGN KEY column will accept duplicate values
A FOREIGN KEY column will accept null values.

Syntax of Foreign key constraint at table level:-

Create table (table_name) ( col_name1 datatype(size), col_name2 datatype(size),


FOREIGN KEY ( col_name1) REFERENCES (Parent Table) ( primary key col name ) );

Example:-

create table library ( rollno number(3), book_name varchar2(10) REFERENCES school (


rollno));

Deleting Rows from tables.

Select * from school; — 4 rows


Select * from library; — 4 rows

Delete from school where rollno = 101;

33 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Select * from school; — 3 rows

Select * from library; — 4 rows

Delete from school where rollno = 104; — error

Note:-
we cannot delete row from the parent table if corresponding row is present in child
table. If we want to delete the row we need to use on delete cascade.

On Delete Cascade:-

When we delete row from parent table , corresponding row from child table is
deleted automatically.

Create table ank_school2 (rollno number (3) primary key, NAME VARCHAR2 (10),
Marks number (3));

Insert into ank_school2 values (101, ‘karan’, 40);


Insert into ank_school2 values (102, ‘arun’, 40);
Insert into ank_school2 values (103, ‘amit’, 40);
Insert into ank_school2 values (104, ‘nisha’, 40);

Create table ank_library2 ( rollno number(3) references ank_school2 (rollno) on


delete cascade, book_name varchar2(10));

Insert into ank_library2 values (104, ‘c++’);


Insert into ank_library2 values (103, ‘java’);
Insert into ank_library2 values (103, ‘dotnet’);
Insert into ank_library2 values (108, ‘oracle’); — error
Insert into ank_library2 values (null, ‘oracle’);

Select * from ank_school2; — 4 rows


Select * from ank_library2; — 4 rows

34 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Delete from ank_school2 where rollno = 104;
Select * from ank_school2; — 3 rows
Select * from ank_library2; — 4 rows
Delete from ank_school2 where rollno = 103;

Check constraint:-

Check constraint is used to define domain of a column. Domain of a column means,


values a column can store.

Add constraint so no one can enter marks more than 100 for this we will use check
constraint.

Check Constraint is us in banking sector for minimum balance.

Create table ank_student8 (rollno number (3), name varchar2 (10), marks number
(3));

Insert into ank_student8 values (101, ‘arun’, 80);


Insert into ank_student8 values (102, ‘vijay’, 190);

Select * from ank_student8;

Create table ank_student9 (rollno number (3), name varchar2 (10),Marks number (3)
check (marks <= 100));

Insert into ank_student9 values (101, ‘arun’, 80);


Insert into ank_student9 values (102, ‘vijay’, 190);–error

SELECT * from ank_student9;

Add a constraint to an existing table:-


Create table ank_student10 (rollno number (3), name varchar2 (10),Marks number
(3));

35 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Insert into ank_student10 values (101, ‘arun’, 40);
Insert into ank_student10 values (102, ‘amit’, 40);
Insert into ank_student10 values (103, ‘ankit’, 40);
Insert into ank_student10 values (104, ‘vipan’, 40);
Insert into ank_student10 values (105, ‘karan’, 40);

Select * from ank_student10;

Add primary key — rollno

Alter table ank_student10 add primary key (rollno);

Alter table ank_student10 drop primary key;

Alter table ank_student10 add unique (rollno);

Alter table ank_student10 drop unique (rollno);

Alter table ank_student10 add check (marks <= 100);


But check constraint is not able to delete without constraint name.

Constraint Name:-

Create table ank_student11 (rollno number (3) primary key, name varchar2 (10),
Marks number (3) check (marks <=100));

Insert into ank_student11 values (101, ‘sunil’, 40);


Insert into ank_student11 values (102, ‘arun’, 40);
Insert into ank_student11 values (103, ‘ram’, 40);
Insert into ank_student11 values (104, ‘lucky’, 40);
Insert into ank_student11 values (105, ‘deepak’, 40);

Select * from ank_student11;

36 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Type Primary_key Check_constraint
Name Constraint name Constraint name

For Constraint Name right click on the query and go to open declaration and then
constraint tab.

Alter table <table_name> drop constraint <Constraint_name>;

Create table ank_student12 (rollno number (3) constraint ankit primary key,
Name varchar2 (10), marks number (3) constraint sunil check (marks <=100));

Type Primary_key Check_constraint


Name Ankit Sunil

Composite Primary key: –

when primary key is applied on mulitiple columns. Table can have only one primary
key.

Create table school21 (first_name varchar2 (10),last_name varchar2(10),


Marks number (3), primary key (first_name, last_name));

Insert into school21 values (‘ABC’, ‘VIJAY’, 40);


Insert into school21 values (‘ABC’, ‘KIRAN’, 40);
Insert into school21 values (‘XYZ’, ‘KIRAN’, 40);
Insert into school21 values (‘XYZ’, ‘KIRAN’, 40); — error

Branch code Account number


0642 100043434
0642 100043435
0642 100043436
0642 100043437

Composite primary is mainly used in banks where every branch have its own branch
code and unique account number.

37 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Create table school22 (first_name varchar2 (10),last_name varchar2(10),
marks number(3) , constraint aaaa primary key ( first_name, last_name ) );

Alter table school22 drop constraint aaaa;

Joins
Joins are used to display data from multiple tables.

Types of joins: –

1) Equi Joins/ Inner Joins/ Natural Joins


2) Non-Equi Joins
3) Self Joins
4) Outer Joins
5) Cross Joins

Types of outer Joins: –

1) Right Outer Join


2) Left Outer Join
3) Full Outer Join

I want the following output:-

Empno Ename Sal Dname Loc


From Emp table From Dept table

Look at the above output,


Empno, Ename, Sal are from emp table,
Dname are from dept table.
So, we need to get the data from two table, which can be done by using joins.

38 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
1) Equi Joins: –

Consider emp and dept tables, there is a common column i.e. deptno.
When tables are joined basing on common column , it is called Equi join.

In Equi Joins , we always use = ( equality operator ) in join condition.

Example 1: –

Select empno, ename, sal, dname,loc from emp , dept Where emp.deptno =
dept.deptno;

In the above query emp.deptno = dept.deptno is called as join condition.


We mention join condition in where clause.

Example 2:-

I want the Following output :-

Empno Ename Sal Deptno Dname Loc


From Emp table From Dept table

It you look at the above requirement, it is almost similar to previous query

Try writing query by yourself.


In select clause , list out all the columns you want.
In from clause, mention the table from which you want to pull the data.
In where clause, write the join condition.

Select empno, ename , job, sal, deptno, dname , loc


From emp , dept
Where emp.deptno = deptno.deptno; — error

But, the above query will give an error.


The problem with the column deptno.
39 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
As deptno column is present in both emp and dept tables.
There will be ambiguity, from which table it needs to pull the data.

There is no ambiguity problem for columns like empno, ename, job, dname ,loc
As it is either available from emp or from dept table.
How can we resolve the ambiguity?

We can resolve the ambiguity by mentioning the (table_name) .(col_name) in the


select clause.

Answer:-
Select empno, ename, sal, emp.deptno, dname, loc from emp, dept
Where emp.deptno = dept.deptno;

The common column ie deptno can also be retrieved from dept table also.

Select empno, ename, sal, dept.deptno, dname, loc from emp, dept
Where emp.deptno = dept.deptno;

The above two queries will give the same result.

Remember:-

We need to mention (table_name). (col_name) in select clause to resolve the


ambiguity.

Can we mention (table_name) .( col_name) for all the columns in the select clause.

Why not, definitely Yes

You query will look like this:

Select emp.empno, emp.ename, emp.job, emp.sal, emp.deptno, dept.dname ,


dept.locFrom emp, deptWhere emp.deptno = dept.deptno;

40 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
So, compare the following two queries

Query A

Select empno, ename , job, sal, emp.deptno, dname , loc


From emp , dept
Where emp.deptno = deptno.deptno;

Query B

Select emp.empno, emp.ename, emp.job, emp.sal, emp.deptno, dept.dname ,


dept.loc
From emp, dept Where emp.deptno = dept.deptno;

Both Query A and Query B will give the same result.


Developer tend to prefer writing Query A rather than Query B, as the length of the
query is small.

But from performance point of view


Query B will run faster than Query A

So, according to coding standards, we should mention < table_name> .< col_name>
for all the columns which helps in performance.

But when we mention (table_name) . (col_name) for all the columns , the length of
the query will be long.

To overcome the length problem, we use the table alias.

Table alias: –

Table alias helps in reducing the length of the query and at the same time,
performance is maintained.
Table alias are created in from clause, can be used in select and where clause.

41 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Example:-

Select e.empno, e.ename , e.job, e.sal, e.deptno, d.dname , d.loc


From emp e, dept d
Where e.deptno = d.deptno;

E is table alias for emp table.


D is table alias for dept table.

Not only two tables , we can join three for n table .

Empno Ename Deptno Dname Loc State


Emp Table Dept Table AreasTable

Total no of columns in the output :- 6

We know, we can join emp and dept tables by using the common column deptno.
We can join dept and Areas tables by using the common column Loc and city.

Remember:-

For joining table, it is not the column name which should match.
The column values should match.

The Query to get the above output.

Select e.empno, e.ename, d.deptno, d,dname, d.loc, a.state


From emp e, dept d, areas a
Where e.deptno = d.deptno and d.loc = a.city.

Note:-

To join 2 tables, we need 1 condition


To join 3 tables, we need 2 conditions
To join n tables, we need n-1 conditions.
42 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Note:-

Equi joins always use = ( Equality operator) in join condition.

2 )Non-Equi Joins: –

When tables are joined without using = (equality operator), it is called Non-Equi Join.

Need the below mention output from Emp& salgrade table.

Empno Ename Sal Salgrade


Emp table Salgrade table

All the employees are categorized into grades basing on sal.

What is the grade of SMITH?


SMITH sal is 800. His sal is falling between 700 and 1200, he is grade 1 employee.

What is the grade of CLARK?


CLARK sal is 2450. His sal is falling between 2001 and 3000, so he is grade 4
employee.

To retrieve the data from multiple tables , we need joins.


So, we need to join EMP and SALGRADE table.
Observe, there is no common column between EMP and SALGRADE.
Hence we cannot use = ( equality ) operator.

When sal is falls between LOSAL and HISAL, we can get the GRADE,
We need to use between operator.

Select e.empno, e.ename, e.sal, s.grade from emp e, salgrade s


Where e.sal between s.losal and s.hisal;

Note:-
When = ( equality operator ) is not used, it is called NON EQUI-JOIN
43 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
3) Self Joins:-

When a table is joined to itself, it is called self join.

I want the following output: –

Empno Ename Sal MGR Name

Empno, ename , sal,mgr we can straight forward get from EMP table.
Mgr name, are also available in EMP table.
We can get Mgr name by comparing mgr with empno column.

We need to join EMP table with EMP table.


When a table is joined to itself, it is called SELF JOIN.

Select e.empno, e.ename, e.sal, m.ename from emp e, emp m where e.mgr =
m.empno;

Note:-
In self joins, we create two table aliases for the same table.

4) Outer Joins:-

Outer joins are extension of equi joins.


In equi joins we get only the matching data.
In outer joins we get both matching and non matching data.
(+) — Outer Join Operator

Look at the equi join: –


Select e.empno, e.ename, e.sal, e.deptno, d.dname, d.loc from emp e, dept d where
e.deptno = d.deptno;

44 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Right Outer Join:-

Emp Table Dept Table


Deptno Column Deptno Column
10 10
20 20
30 30
+ 40

As there is no value 40 in emp table, we are not getting operations and boston in the
output of equi joins.

Right Outer Join will give 14 + 1 = 15 rows in the output.


+ — lack of data.

we want below mention output:-

Empno Ename Job Sal Deptno Dname Loc


Emp Table Dept Table

Select e.empno, e.ename , e.job, e.sal, e.deptno, d.dname , d.loc


From emp e, dept d Where e.deptno (+) = d.deptno;

Compare equi joins and right outer join, the only difference in the right outer join is
plus operator (+).

Left Outer Join:-

Insert below mention rows for better understand of Left outer joins.

Insert into emp (empno, ename, sal, deptno) values (1111, ‘aaaa’, 2000, 16);
Insert into emp (empno, ename, sal, deptno) values (2222, ‘BBBB’, 2000, 17);
Insert into emp (empno, ename, sal, deptno) values (3333, ‘cccc’, 2000, 18);

45 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Emp Table Dept Table
Deptno Column Deptno Column
10 10
20 20
30 30
16 40
17
+
18

Empno Ename Job Sal Deptno Dname Loc


Emp Table Dept Table

Select e.empno, e.ename, e.job, e.sal, e.deptno, d.dname , d.loc


from emp e, dept d where e.deptno = d.deptno(+);

Full Outer Join:-


With above both the examples you can easily guess the full outer join.

You can get not 18 rows 14 match rows from both table & 3 not matching rows of
emp table & one dept table non matching row.

Select e.empno, e.ename, e.sal, e.deptno, d.dname, d.loc


From emp e full outer join dept d on (e.deptno = d.deptno);

Now delete those which we enter the table before left outer join.
Delete from emp where JOB is null;

Cross Join:-
When tables are joined without join condition.

14 x 4 = 56

Select e.empno, e.ename, e.sal, e.deptno, d.dname , d.loc from emp e, dept d;

In the cross join we just remove he condition from the equi join statement.

46 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
SET Operator
Types of SET Operator:-

1) Union
2) Union all
3) Intersect
4) Minus

Before learning the SET Operator run the below mention script.

Create table
Student28 (Rollno number (4), Name varchar2 (10), Marks number (3));

Insert into student28 values (101, ‘Arun’,76);


Insert into student28 values (102, ‘Karan’,87);
Insert into student28 values (103, ‘Vipan’,60);
Insert into student28 values (104, ‘Sumit’ ,null);
Insert into student28 values (105,null,null);

Create table student29 as select * from student28;


Delete from student29;

Insert into student29 values (101, ‘Kiran’,76);


Insert into student29 values (106, ‘Ankit’,87);
________________________________________________

1) Union

The UNION operator is used to combine the result-set of two or more SELECT
statements.
The UNION operator selects only distinct values by default.

47 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Syntax:-

SELECT column_name(s) FROM table1


UNION -- Select Only Distinct Values
SELECT column_name(s) FROM table2;

Example:-

Select rollno from student28


Union
Select rollno from student29;

2) Union ALL

The UNION operator is used to combine the result-set of two or more SELECT
statements.
The UNION ALL operator selects all the values.

Syntax:-

SELECT column_name(s) FROM table1


UNION all --- Select All the values.
SELECT column_name(s) FROM table2;

Example:-

Select rollno from student28


Union all
Select rollno from student29;

3) INTERSECT

The SQL INTERSECT operator is used to combine two SELECT statements, but returns
rows only from the first SELECT statement that are identical to a row in the second

48 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
SELECT statement. This means INTERSECT returns only common rows returned by the
two SELECT statements.

Syntax:-

SELECT column_name(s) FROM table1


Intersect -- Select Only Common Values
SELECT column_name(s) FROM table2;

Example:-

Select rollno from student28


Intersect
Select rollno from student29;

4) Minus:-

The MINUS operator is used to subtract the result set obtained by first SELECT query
from the result set obtained by second SELECT query. In simple words, we can say
that MINUS operator will return only those rows which are unique in only first SELECT
query and not those rows which are common to both first and second SELECT
queries.

Syntax:-

SELECT column_name(s) FROM table1


Minus --- Minus remove common values & show
SELECT column_name(s) FROM table2; only values pending in first table

Example:-

Select rollno from student28


Minus
Select rollno from student29;

49 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Rules of Set Operators: –

1) No of columns in the query should match.


2) Column data type is match.

Select rollno, name from student28


Union
Select rollno from student29; — error

Select name from student28


Union
Select rollno from student29;–error

Pseudo Column

Pseudo Column are not actual columns in a table but they behave like columns.

We already learn some pseudo columns before start learning Scalar Functions.

Now we are going to learn two more pseudo columns which are very important.

Rownum & Rowid

Rownum

A Column which is not present in the table, but can be used in select statement.

Starts with one and increment by 1


Rownum values are temporary.
Rownum generation start with 1.

Select Rownum, empid,ename from emp;

Select empid,ename, Rownum from emp;


50 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
To get first five rows from the emp table.

Select * from emp where rownum <=5;

To get only fifth rows from the emp table.

Select * from emp where rownum <=5 Minus Select * from emp where rownum <=4;

Row ID

It is hexadecimal value, indicates the address/physical location of the rows.

Select rowid,empno,ename,sal from emp;

For every insert row rowid is created.

Difference between Rownum & Rowid: -

Rownum Rowid
Starts with 1 and increment with 1 Hexadecimal value
Temporary Permanent
Query execution time Row is inserted

Greater than is not work with Rownum.

Sub queries

When we write a query inside another query, the inner query is called sub query.
Outer query is called parent query.

Always sub query is executed first and parent query is executed by using the result of
sub query.

Sub queries are used to get the results based on unknown values.

51 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Types of sub query: –

1) Single Row sub queries


2) Multiple row sub queries
3) Multiple column sub queries
4) Co-related sub query
5) Scalar sub query
6) Inline view

1) Single row sub queries: –

When sub query returns one row (one value),it is called row sub query.

Example 1:-

Display the rows who are having sal greater than ALLEN sal.

Step 1:- We need to find ALLEN sal


Query to get ALLEN sal

Select sal from emp Where ename=’ALLEN’ ;

Output is 1600.

Step 2:-
Now, we want all the rows who are having sal > 1600

Select * from emp


Where sal > (Select sal from emp
Where ename=ALLEN);

Subquery is highlighted in blue color.

Always subquery should be used in parenthesis.

52 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
As we know, subquery is executed first , it returns 1600.
And then parent query will display all the rows who are having sal > ALLEN SAL

Example 2:-

Display the rows whose job is same as BLAKE Job.

Step 1:- Find BLAKE job

Select job from emp where ename=’BLAKE’;

Step 2: –

Select * from emp where job = (select job from emp where ename =’BLAKE’);

Example 3:-

Display details of emp, who is having highest sal.

Step 1: – Find MAX salary

Select max (sal) from emp;

Step 2: –

Select * from emp where sal = (select max(sal) from emp);

Example 4:-

Display details of employees who are having sal greater than average sal of emp
table.

53 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Step 1: – Find AVG Salary

Select avg(sal) from emp;

Step 2: –

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

Example 5:-

Display the rows who are having sal > ALLEN sal and job same as BLAKE job.

Step 1: – Find Allen Salary

Select sal from emp where ename=’ALLEN’;

Step 2: – Find Blake Job

Select job from emp Where ename=’BLAKE’;

Step 3: –

Select * from emp where Sal > (Select sal from emp where ename=’ALLEN’)
And job = (Select job from emp Where ename=’BLAKE’);

Please provide the answer for this sub query.

Select empno,ename from emp


Where sal > (select sal from emp
Where ename = (select ename from emp
where empno = 7499));

54 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
2) Multiple row subquery: –

When subquery returns more than one row ( more than one value ),
They are called multiple-row subquery.

Example:-

Select * from emp


Where sal >( select sal from emp
Where deptno = 30);

As there are six employees in deptno 30, the subquery returns six values.

It is something like

Select * from emp Where sal >( 2850, 1600, 1250, 1250,1500, 950 );

But, the above query will fail.


Operators like = ,> , >= , < , <= , <> expects only one value in right hand side.
Here our subquery is returning 6 values. Hence the query will give us error.

Note:- For multiple row subqueries, we need to use multiple row operators.

Three types of multiple row sub queries: –

1) All
2) Any
3) In

ALL: –

In this we will get the greater value than maximum value of the sub query.

Select * from emp where sal >ALL (select sal from emp where deptno = 30);

55 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
When we run the sub query it return six values.

Select * from emp where sal >ALL (1600, 1250, 1250, 2850, 1500, 950);

Note: -In other words, we get the four rows. They are having sal greater than
maximum value of the sub query.

Select * from emp where sal < ALL (select sal from emp where deptno = 30);

ANY: –

In this we will get the greater value than minimum value of the sub query.

Select * from emp where sal >Any (select sal from emp where deptno = 30);

When we run the sub query it return six values.

Select * from emp Where sal >ANY ( 1600, 1250, 2850, 1250,1500, 950 );

Note:-In other words, we get the above twelve rows are they are having sal greater
than minimum value of the subquery.

IN: –

In Operator will display the rows who are matching with the list of values provided.

Example:-

Select * from emp where job in ( ‘CLERK’, ‘MANAGER’);

In the output, we get all the employees who are working as CLERK and MANAGER.

Similarly,

56 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Select * from emp
Where sal IN ( select sal from emp
Where deptno=30);

When we run the subquery, we know it returns six values.

It is something like.

Select * from emp


Where sal IN ( 1600, 1250, 2850, 1250,1500, 950 );

We get the row who are having sal matching with any of the value of the subquery.

3) Multiple column subquery: –

When subquery returns more than one column, it is called multiple-column subquery.
IN operator is used with multiple-column subquery.

Example:-

Select * from emp


Where ( sal, job ) IN ( select sal, job from emp
Where deptno=30);

In the above example, as subquery is returning two columns, parent query should
also compare both the columns. Pair-wise comparisons are done.

The Following are the values returned by the sub query.


Sal Job
2850 Manager
1600 Salesman
1250 Salesman
1250 Salesman
1500 Salesman
950 Clerk
57 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Now the parent query will return the rows when combinations of values are matching
with the above result.
Co-related sub query: –

When sub query is executed in relation to parent query.

Example 1:-

Display details of employees who are having sal greater than avg salary of his dept.

Step 1: –

Select deptno, avg (sal) from emp group by deptno;

Deptno Avg(Sal)
10 2916
20 2175
30 1566

Select * from emp e where sal > (Select avg(sal) from emp Where deptno =
e.deptno);

If parent query table alias, is used in sub query, it is co-related sub query.

In normal sub query, sub query is executed first but in co-related sub query it is a
reverse process first parent query will executed then sub query will executed.

Example 2:-

Display details of employees who are having sal greater than min salary of his dept.

Select * from emp e where sal > (Select min (sal) from emp Where deptno =
e.deptno);

58 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Solve the below mention query:-

Display details of employees who are having sal less than max salary of his dept.
Scalar Sub query: –

When sub query is used in select clause.

Deptno Dname Loc Sum(sal)


10 Accounting New York 8750
20 Research Dallas 10875
30 Sales Chicago 9400
40 Operations Boston

Select d.deptno, d.dname, d.loc, (select sum (sal) from emp Where deptno =
d.deptno) from dept d;

Write the query for below mention table:-

Deptno Dname Loc AVG(sal)


10 Accounting New York 2916
20 Research Dallas 2175
30 Sales Chicago 1566
40 Operations Boston

Inline View: –

When we write subquery in from clause.

Example 1 :-

Query to get details of top 5 height salary.

Step 1:-

Select * from emp Where rownum <=5;

59 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com

Step 2:-
Select * from emp order by sal desc;
Step 3:-

Select * from (select * from emp order by sal desc) where rownum <= 5;

Query to get 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;

TCL Commands

Commit Command:-

The COMMIT command is the transactional command used to save changes invoked
by a transaction to the database.

The COMMIT command is the transactional command used to save changes invoked
by a transaction to the database. The COMMIT command saves all the transactions to
the database since the last COMMIT or ROLLBACK command.

Syntax:-

Commit;

Create table student53 (rollnonumber (3), name varchar2 (10), marksnumber (3));

Insert into student53 values (101,'arun', 40);


Insert into student53 values (102,'arun', 40);
Insert into student53 values (103,'arun', 40);
Insert into student53 values (104,'arun', 40);
Insert into student53 values (105,'arun', 40);
60 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com

Commit;

Select * from student53;

Create table student54 (rollno number (3), name varchar2 (10), marks number (3));

Insert into student54 values (101,'arun', 40);


Insert into student54 values (102,'arun', 40);
Insert into student54 values (103,'arun', 40);

Create table student55 (rollno number (3), name varchar2 (10), marks number(3));

Insert into student55 values (101,'arun', 40);


Insert into student55 values (102,'arun', 40);

Select * from student54;

Select * from student55;

In two ways we can make the changes permanent to the database.


1)Commit.
2)By using any DDL Command.
Create, Alter, Drop, Truncate and Rename commands are auto commit.

Rollback Command:-

The ROLLBACK command is the transactional command used to undo transactions


that have not already been saved to the database. This command can only be used to
undo transactions since the last COMMIT or ROLLBACK command was issued.

Syntax:-

Rollback;
61 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Create table student56 (rollno number (3), name varchar2 (10), marks number (3));

Insert into student56 values (101,'arun', 40);


Insert into student56 values (102,'arun', 40);
Insert into student56 values (103,'arun', 40);
Commit;

Insert into student56 values (104,'arun', 40);


Insert into student56 values (105,'arun', 40);

Select * from student56;


Rollback;

Create table student57 (rollno number (3), Name varchar2 (10), Marks number (3));

Insert into student57 values (101,'arun', 40);


Insert into student57 values (102,'arun', 40);
Insert into student57 values (103,'arun', 40);

Select * from student57;


Rollback;

Savepoint Command:-

A SAVEPOINT is a point in a transaction when you can roll the transaction back to a
certain point without rolling back the entire transaction.

Syntax:-

Savepoint (name);

Syntax of rollback using save point: –

Rollback to (name);

62 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Create table student43 (rollno number (3), name varchar2 (10), MARKS number (3));

Insert into student43 values (101, 'arun', 40);


Insert into student43 values (102, 'arun', 40);
Insert into student43 values (103, 'arun', 40);
savepoint a;

Insert into student43 values (104, 'arun', 40);


Insert into student43 values (105, 'arun', 40);
Select * from student43;
Rollback to a;

DCL Commands
Grand & Revoke

Privileges – are permissions given to user.

Grand:-

Grant command is used to give the privileges to user.


Revoke command is used to get back the privileges from user which are granted.

Create a user: -

Syntax: -
create user <user_name> identified by <password>;

Connect as DBA> username – system password - manager

DBA> create user ankit identified by ankit123;

Syntax of grant: -
Grant <privilege_name> to <user_name>;
DBA> Grant connect, resource to ankit;
63 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Query to check DBA privileges
SELECT * FROM DBA_SYS_PRIVS;

Query to check current user privileges


SELECT * FROM USER_SYS_PRIVS;

Create one more user:-


DBA> create user vipan identified by vipan123;

DBA> grant connect, resource to vipan;

Schema: - Schema is a memory location associated to a user. It is collection objects


specific to a user.

Create table student (rollno number (3), name varchar2 (10), marks number (3));

Insert into student values (101, 'arun', 40);


Insert into student values (102, 'arun', 40);
Insert into student values (103, 'arun', 40);

Commit;
Set sqlprompt ankit>-- to set the name for sql prompt
Set sqlprompt vipan>

Ankit> grant select on student to vipan;


Grant insert on student to vipan;
Grant all on student to vipan;
Grant select on student to public;
vipan> select * from ankit.student;
vipan> insert into ankit.student values ( 105, 'aaaa', 40);
Revoke insert on student from vipan;
Revoke all on student from vipan;
Revoke select on student from public;

64 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Two types of privileges: -

1)System Privileges: - are given by DBA to user. For eg: -Connect, resource.
2)Object Privileges: - given on one user to other user. For eg: -Insert, update, delete.

Alter user: -Alter user user_name identified by password;

Drop User:-Drop User User_name cascade;

Views
View is a logical representation of data from one or more than one table.

Types of views: –

1) Simple views
2) Complex Views
3) Read Only views
4) With check option views
5) Materialized views

Simple Views: –

When view is created using one base table.

Syntax: –

Create view view_name as select statement;

What is the need for view?

Let's say I want to display the rows from emp which satisfies following conditions
Condition 1: employee should be working in deptno 30
Condition 2: job should be SALESMAN
Condition 3: sal should be greater than 1400
65 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
So, your query should be
Select * from emp
Where deptno =30 AND job =SALESMAN AND sal > 1400;

If you always want to retrieve the data which satisfies the above three conditions,
better to create a view so that your work is simplified.

Example:-

Create view v1
As select * from emp
Where deptno =30 AND job =SALESMAN AND sal > 1400;

View created.

In the above example , the name of the view is V1


Now, when you want to retrieve the data which satisfies the above three conditions,
You query will be very simple ie

Select * from v1;

Table which is used for creating the view is called as base table.
In the example, name of the view is v1 and the table emp is called base table.

Few more Examples:-

Create view v10 as select empno , ename , job from emp;

Select * from v10;

Create view v20 as select * from emp where deptno=10;

Select * from v20;

66 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Create view v30 as select * from emp where deptno=20;

Select * from v30;

All the above views as they are created using one base table, it is Simple views.

We can perform DML operations on simple views.


Any DML operations performed on simple views will be reflected to base table.

Insert into v10 values (111, ‘aaaa’, ‘HR’);

Note:-

Views does not occupy memory.


When we write a select statement on a view, we get the data from the base table.

List of all the table, views: – Select * from tab;

List of all the table: – Select table_name from user_tables;

List of all the views: – Select view_name from user_views;

Two types of tables: –

1) User defined table


2) Data dictionary tables—Predefined tables—Example:- user _views, user_tables

We can add or drop columns in a view by using create or replace clause.

Create or replace view v10 as select empno, ename, sal, deptno from emp where
deptno = 10;

select * from v10;

67 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Insert into v10 values (2222, ‘BBBB’, 1000, 20);

Where clause is not working, when DML Operations are performed.

Complex Views: –

when views are created using multiple tables.

Example 1:-

Create view v40 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 v40;

The view v40, is created using more than one base table, it is a complex view.

Note:- DML Operations are not allowed on complex views In SQL But
with Triggers (Timing : – instead of) in Pl/SQL you can insert the rows in
Complex view.

Example 2:-

When a view is created using arithmetic operations or functions of group by clause, it


is also called complex views.

Create view v50 As select empno, ename , sal, sal*12 annual_sal , deptno from emp;

Select * from v50;

Annual_Sal column is not present in the base table, we are calculating it in the view.

Example 3:-

Create view v60 As Select deptno, sum(sal) sum_sal From emp Group by deptno;
68 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Select * from v60;

V60, is also an example of complex views. As we have used group functions / group
by clause.

Read only views:-

We can only read the view.Reading is executing select statement on the view.
We cannot perform DML Operations on these views.

Create view v70 As select empno, ename , sal from emp


with read only;

Now, we cannot perform insert, update and delete operations on View v70.
We can execute only select stmt on the view.

Insert into v70 values (666, ‘CCCC’, 1200, 30);

Select * from v70;

With check option views:-

DML operations are allowed only when where clause is satisfied.

Create or replace view v80 as select empno, ename, sal,deptno from emp Where
deptno = 10 with check option;

Select * from v80;

Insert into v80 values (1111, ‘aaaa’, 1000, 20);

When we perform DML operations on WITH CHECK OPTION views, it validates the
where clause.

69 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
DML operations are allowed only when WHERE clause is satisfied.

Materialized view: –

Materialized view are also called the snapshot. Any changes done to the base table
will not reflect on materialized view.

Create materialized view mv1 as select empno, ename , sal from emp;

Select * from mv1;

Insert into mv1 values (666, ‘fff’, 30);

DML operations are not allowed.

Drop View: - drop view view_name;

Drop Materialized view: –dropMaterialized view view_name;

Indexes
Indexes is an object used to improve the performance of the select statement.

Look at this query for understand about index

Select * from emp Where sal > 2000;

As our emp table is having 14 rows, it compares row by row.

It compares 1st row salary 800 > 2000, condition is FALSE.


It compares 2nd row salary 1600 > 2000, condition is FALSE.
It compares 3rd row salary 1250 > 2000, condition is FALSE.
It compares 4th row salary 2975 > 2000, condition is TRUE.

70 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
It compares all the rows, finally rows which are satisfying the condition are retrieved.
The point it the no of comparisons.
As the emp table is having 14 rows, it performs 14 comparisons.

Assume if emp table is having 1 million rows, query need to perform 1 million
comparisons.
Performing 1 million comparisons takes long time, thus query performance is
decreased.

When there are more no of rows, query needs to perform more no of comparisons.
When there are more no of comparisons, the performance is decreased.

So, to increase the performance, indexes need to be used.

Types of Indexes: –

1) Simple indexes
2) Composite indexes

1) Simple Indexes: –

When index is created using one Column.

Syntax: –

Create index index_name on table_name (column_name);

Look at this query


Select * from emp Where sal > 2000;

Assume emp table is having 1 million records, the query performance is slow.

Look at the where clause of the query, sal column is used.


Index should be created on columns which are used in where clause.

71 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
To improve the performance, we need to create index on sal column.

Example:-

Create index ID1 in emp (sal);

After creating the index, if you run the query

Select * from empWhere sal > 2000;

The performance of the query is increased.

When we create index, a separate structure is created with two columns.


First column is the ROWID.
Second column is the column on which index is created.
Rows in the index are arranged in ascending order of the indexed column.

We can visualise the index as follows.

RowID Sal
AABqJuAB+AAA2O4AAA 800
AABqJuAB+AAA2O4AAL 950
AABqJuAB+AAA2O4AAK 1100
AABqJuAB+AAA2O4AAC 1250
AABqJuAB+AAA2O4AAE 1250
AABqJuAB+AAA2O4AAN 1300
AABqJuAB+AAA2O4AAJ 1500
AABqJuAB+AAA2O4AAB 1600
AABqJuAB+AAA2O4AAG 2450
AABqJuAB+AAA2O4AAF 2850
AABqJuAB+AAA2O4AAD 2975
AABqJuAB+AAA2O4AAH 3000
AABqJuAB+AAA2O4AAM 3000
AABqJuAB+AAA2O4AAI 5000

72 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Now, when we run the query

Select * from emp Where sal > 2000;

Instead of searching row by row in the table, searching is done on the index using
algorithms
Gets the bulk of ROWID, using which rows are displayed.

2) Composite indexes: –

When index is created on multiple columns.

Select * from emp Where sal > 2000 and job = MANAGER;

Look at the where clause of the query.


Sal and job columns are used.
We know, index should be created on columns which are used in WHERE clause.
As WHERE clause contains SAL and JOB columns, we need to create index on two
columns.

Example:-

Create Index ID2 on emp ( sal, job );

These kind of indexes which are created on multiple columns, are called as composite
index.

Query to see list of all the indexes


Select index_name , table_name From user_indexes;

Query to see the list of indexes and its corresponding table names and column names
Select index_name , table_name , column_name From user_indexes;

73 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Index can also be categorised in two types.

1) Unique Index
2) Non-unique index.

1) Unique index: –

When index column contains unique values. Unique index is created automatically,
when table is created with primary key or unique constraint.

Create table ank_table (rollno number (3) primary key, name varchar2 (10),
Marks number (3));

So, we never create unique index manually, It is created automatically when table is
create with primary key or unique constraint.

2) Non-unique index: –

When Index column have duplicates.

Create index id1 on emp(sal);

There may be two or more employees having same salary.


So the indexed column sal can contain duplicates, it is called Non-unique index.
Index ID1 is an example of simple index as well as Non-unique index.

Function based index:-

When index is created using functions, it is called function based index.

Example:-

Create index ID3 on emp ( lower(ename) );

74 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Index ID3 is used when the function lower is used in where clause.
I.e. select * from emp Where lower (ename)=king;

Note:- Index is an object which is used to improve the performance of select


statement.

Drop Index: –

Drop index index_name;

Sequences

Sequence is an object which is used to generate numbers.

Syntax: –

Create sequence (seq_name) start with (value) increment by (value);

Example: –

Create sequence seq1


Start with 100
Increment by 1;

In the above example, name of the sequence is seq1; it generated number 1, 2, 3…

How can we use the sequence?

I want to create a table ank_student3, and insert 5 rows into it.

Create table ank_student3 (rollno number(3), name varchar2 (10), Marks number
(3));

75 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Instead of hard coding the values, in the insert command, I can use the sequence
seq1 which we have created.

Note:-

Nextval is a pseudo column which is used to generate the numbers.

Nextual:-

For generating number syntax: –

sequence_name.nextval

Insert into ank_student3 values (seq1.nextval, ‘arun’, 40);


Insert into ank_student3 values (seq1.nextval, ‘arun’, 40);
Insert into ank_student3 values (seq1.nextval, ‘arun’, 40);
Insert into ank_student3 values (seq1.nextval, ‘arun’, 40);
Insert into ank_student3 values (seq1.nextval, ‘arun’, 40);

In the above insert commands, we are not hard coding the values of the sno column.
We are using sequence_name.nextval , it will generate the number.

Currval: –

Currval is also a pseudo column which is used to know the latest number generated.

Syntax: –

Select sequence_name.currval from dual;

Example:-

Select seq1.currval from dual;

76 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
So, whenever we want numbers to generate automatically, we use sequence.
Like credit card numbers, mobile numbers, sim card numbers, bank account numbers
etc;
Let’s look at few more examples so; whenever we want numbers to generate
automatically, we use sequence.

Example 2:-

create sequence seq2


Start with 100
Increment by 1
Maxvalue 110;

We can restrict sequence to a maximum number by using Maxvalue option.

Example 3:-

Create sequence seq3


Start with 1
Increment by 1
Maxvalue 10
Cycle;

After sequence reaching Maxvalue, it again starts generating number 1, 2, so on


Sequence with cycle option, cannot be used for primary key columns as it may
generate duplicate values.

Important

There are two pseudo columns, related to sequences.

1) Nextval
2) Currval

77 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Nextval will generate the next number.
Currval will return the latest number generated.

List of all the sequence: –

Select * from user_sequences;

Drop sequence: –

Drop sequence sequence_name;

Synonyms

Synonyms is an alternate name (extra name) given to a table.

Syntax: –

Create synonym synonym_name for table_name;

Example:-

Create synonym s10 for emp;

We can use synonym for select statement & DML commands.

What is the advantage of creating synonym?

Generally, table name will be long.


Instead of using lengthy table’s names in the SQL queries, we can use synonyms.

What is difference between table aliases and synonyms?

Do you remember, we have learnt table alias concept in joins, which helps in
reducing the length of the query.
78 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Table alias is temporary, where as synonym are permanent.

List of the entire synonym: –

Select * from user_synonyms;

Drop synonym: –

Drop synonym synonym_name;

Drop synonym s10;

Decode

Decode is a function in oracle and is used to provide if then else type of logic to SQL.
Decode is a pseudo column is not permanent.

Syntax: –

Decode (value, Search_value, result, default_result) from table_name;

Default_result is not mandatory.

Examples: –

select decode ('ankit', 'ankit','true','false') from dual;

Select decode (‘ankit’, ‘narula’,’true’,’false’) from dual;

Select empno, ename,sal, decode ( job , ‘PRESIDENT’, ‘DIRECTOR’,


‘MANAGER’, ‘BOSS’,
‘SALESMAN’, ‘MKTG’,
‘CLERK’, ‘TYPIST’,
‘ANALYST’, ‘SCIENTIST’,
79 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
‘UNKNOWN’) JObFrom emp;
IF Job = PRESIDENT Then result = DIRECTOR;
IF Job = MANAGER Then result = BOSS;
IF Job = SALESMAN Then result = MKTG;
IF Job = CLERK Then result = TYPIST;
IF Job = ANALYST Then result = SCIENTIST;

Level Pseudo Column

LEVEL returns the level number of a node in a tree structure.

President—–> Manager———-> Assistant Manager——->Team Leader

Select, level, col1, col2, col3 from table_name


Start with condition
Connect with prior condition;

Select Level, empno, ename, sal, job, mgr


From emp
Start with ENAME = ‘KING’
CONNECT by PRIOR EMPNO = MGR
Order by level, mgr;

NVL Function

The NVL( ) function is available in Oracle. This function is used to replace NULL value
with another value.

From emp table: –

Empno Ename Sal Total_sal

Total sal :- Salary + commission

80 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Select empno,ename,sal, sal+comm as total_sal from emp;
In some rows we get the null value because if we do any calculation with null we get
the result null.

Select empno, ename , sal, sal+nvl(comm,0) as total_sal from emp;

NVL2 Function

The Oracle/PLSQL NVL2 function extends the functionality found in the NVL function.
It lets you substitutes a value when a null value is encountered as well as when a non-
null value is encountered.

Syntax :-
NVL2( string1, value_if_not_null, value_if_null )

Example:-

In Comm column we have some values & some have null .Those value i want to be as
200 and null as 100.

Select empno, ename , sal, sal+nvl2(comm,200,100) as total_sal from emp;

Merge Command
Merge: - act like a combination of insert and update. With merge statement you can
perform both tasks in a single statement.

Create table student10 (sno number (3), sname varchar2 (20),marks number (3));

Insert into student10 values (101, 'arun', 30);


Insert into student10 values (102, 'anil', 40);
Insert into student10 values (103, 'kiran', 50);

Create table student20 (sno number (3),sname varchar2(20),marks number(3));


Insert into student20 values (101, 'JOHN', 30);
81 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Insert into student20 values (105, 'SMITH', 50);
Syntax: -

MERGE targetable
Using source table
ON merge Condition
WHEN MATCHED
THEN update Statement
WHEN NOT MATCHED BY TARGET
THEN insert Statement
WHEN NOT MATCHED BY SOURCE
THEN delete Statement;

Example: -

Merge into student10 s1


Using student20 s2
On (s1.sno = s2.sno)
When matched
Then update set sname=s2.sname, marks = s2.marks
When not matched
Then insert (sno,sname,marks ) values (s2.sno,s2.sname,s2.marks);

82 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com

For Practice:-
Employees

Employee_id First_name Last_name Hire_date Department_id Manager_id Salary

Departments
Department_id Department_name Manager_id Location_id

Countries
Country_id Country_name Region_id

Regions
Region_id Region_name

Locations
Location_id Street_address Postal_code City State_province Country_id

83 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Equi Joins Examples:-
Example 1:-

Employee_id First_name Last_name Department_name Location_id

Example 2:-

Region_id Country_id Country_name Region_name

Example 3:-

City Street_address Postal_code Country_name

Example 4:-

Employee_id First_name Last_name Department_name Country_name City

Self Joins Example:-

Employee_id First_name Last_name Salary Manager_name

84 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Equi Joins:-

Example 1: -

select e.employee_id,e.first_name, e.last_name,

d.department_name, d.location_id

from employees e,departments d

where e.DEPARTMENT_ID = d.DEPARTMENT_ID;

Example 2: -

Select r.region_id, c.country_id,

c.country_name, r.region_name from

regions r, countries c

where c.region_id =r.region_id;

Example 3: -

Select l.city, l.street_address,

l.postal_code, c.country_name

from locations l, countries c

where l.COUNTRY_ID = c.COUNTRY_ID;

85 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Example 4:-

select e.employee_id,e.first_name, e.last_name,

d.department_name,c.country_name,l.city

from employees e,departments d,countries c,locations l

where e.DEPARTMENT_ID = d.DEPARTMENT_ID

and c.COUNTRY_ID = l.COUNTRY_ID

and d.location_id = l.location_id;

Self Join: -

Select e.employee_id,e.first_name,e.last_name,e.salary,

m.first_name as Manager_name from employees e,

Employees m where e.manager_id = m.employee_id;

86 | P a g e www.selfonlinetraining.wordpress.com

You might also like