SQL Training Notes
SQL Training Notes
com
1|Page www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
SQL Training Notes
What is ORACLE?
DBMS
Features of SQL:-
2|Page www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Commands of SQL:-
Table
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));
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.
Example:-
Insert into student values (104, ‘Sumit’, null);
Insert into student values (105, null, null);
Example:-
Insert into student (Sno , Name) values (106, ‘David’);
Select Command : –
Selecting the rows from the table.
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.
Example:-
Select Sno,name from student;
Select name from student;
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;
Operators
Logical operators:-
1. And
2. Or
3. Not
6|Page www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
AND
Sal>2000
Job=’MANAGER’
OR
Output — 3 + 5 — 8
SMITH –F T
MILLER- T F
Not:-
7|Page www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Between: –
Is null : -
Like Operator —%
JONES
JAMES
ADAMS
8|Page www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Underscore:-
WARD
JAMES
MARTIN
WARD
TURNER
FORD
ALLEN
TURNER
MILLER
JAMES
IN
9|Page www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Need details of emp who's job is Salesman & Manager
Distinct keyword is used to get the distinct ( unique ) values. Duplicates will be
suppressed.
Example:-
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.
Functions
Two Types of Functions:-
2) Scalar Functions:-
Initcap ( ):- It converts first letter of each word in upper case, keeling all other letters
in lower case.
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.
RPad: – Pad the character value towards right, to a total width of n character
positions.
Number Functions:-
14 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Trunc:-
Date Function:-
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.
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.
A. To_char
B. To_Date
C. To_number
16 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Select to_char(sysdate, ‘dd’) from dual;
Select ltrim (‘$200’, ‘$’) from dual; – ‘200’ — but ‘200’ is still a character
select lpad(10 + to_number ( ltrim ( ‘$200’ , ‘$’) ) ,4,’$’) Add_num from dual;–$210
17 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Duplicate Table:-
When we already have table name and need to insert rows from other table.
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.
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.
In the above query, first grouping is done based on deptno and sub grouping is
done based on job.
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 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;
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;
Select deptno, MIN (sal), MAX (sal) from emp where job =’CLERK’ GROUP BY deptno
HAVING MIN (sal) < 1000;
Order by clause:-
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.
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;
DDL Commands
DDL: - Create, alter, drop, truncate and rename.
Alter command:-
21 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Adding a new column:-
Example:-
Droping a column:-
Example:-
Modifying a column:-
By using modifying we can increase and decrease the size of the column.
Example:-
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:-
Note:-
To change the datatype, column should be empty.
Rename a column:-
Syntax: -
Example :-
Drop command:-
Syntax:-
Example:-
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:-
Example:-
Truncate table student;
Syntax:-
Example:-
From now, we need to access the table by using the new name.
DML Commands
DML:Insert Update, delete and merge.
Update:-
Syntax:-
24 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
update table_name set col_name = value Where condition;
Example:-
Note:- Update command without where clause , will update all the rows.
Example:-
Delete command:-
Syntax:-
Example:-
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 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:-
Table Level:-
Create table ank_student3 (rollno number (3), name varchar2 (10), Marks number
(3));
Syntax:-
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:-
Example:-
Create table ank_student6 (rollno number (3) unique, name varchar2 (10),
Marks number (3));
28 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Example:-
PRIMARY KEY:-
Example:-
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
Example:-
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
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.
Example:-
32 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Step 4: Inserting row into the child table:-
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.
Note:-
A FOREIGN KEY column will accept duplicate values
A FOREIGN KEY column will accept null values.
Example:-
33 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Select * from school; — 3 rows
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));
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:-
Add constraint so no one can enter marks more than 100 for this we will use check
constraint.
Create table ank_student8 (rollno number (3), name varchar2 (10), marks number
(3));
Create table ank_student9 (rollno number (3), name varchar2 (10),Marks number (3)
check (marks <= 100));
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);
Constraint Name:-
Create table ank_student11 (rollno number (3) primary key, name varchar2 (10),
Marks number (3) check (marks <=100));
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.
Create table ank_student12 (rollno number (3) constraint ankit primary key,
Name varchar2 (10), marks number (3) constraint sunil check (marks <=100));
when primary key is applied on mulitiple columns. Table can have only one primary
key.
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 ) );
Joins
Joins are used to display data from multiple tables.
Types of 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.
Example 1: –
Select empno, ename, sal, dname,loc from emp , dept Where emp.deptno =
dept.deptno;
Example 2:-
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?
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;
Remember:-
Can we mention (table_name) .( col_name) for all the columns in the select clause.
40 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
So, compare the following two queries
Query A
Query B
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.
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:-
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.
Note:-
2 )Non-Equi Joins: –
When tables are joined without using = (equality operator), it is called Non-Equi Join.
When sal is falls between LOSAL and HISAL, we can get the GRADE,
We need to use between operator.
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:-
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.
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:-
44 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Right Outer Join:-
As there is no value 40 in emp table, we are not getting operations and boston in the
output of equi joins.
Compare equi joins and right outer join, the only difference in the right outer join is
plus operator (+).
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
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.
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));
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:-
Example:-
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:-
Example:-
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:-
Example:-
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:-
Example:-
49 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Rules of Set Operators: –
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
A Column which is not present in the table, but can be used in select statement.
Select * from emp where rownum <=5 Minus Select * from emp where rownum <=4;
Row ID
Rownum Rowid
Starts with 1 and increment with 1 Hexadecimal value
Temporary Permanent
Query execution time Row is inserted
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: –
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.
Output is 1600.
Step 2:-
Now, we want all the rows who are having sal > 1600
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:-
Step 2: –
Select * from emp where job = (select job from emp where ename =’BLAKE’);
Example 3:-
Step 2: –
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
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 3: –
Select * from emp where Sal > (Select sal from emp where ename=’ALLEN’)
And job = (Select job from emp Where ename=’BLAKE’);
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:-
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 );
Note:- For multiple row subqueries, we need to use multiple row operators.
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);
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:-
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);
It is something like.
We get the row who are having sal matching with any of the value of the subquery.
When subquery returns more than one column, it is called multiple-column subquery.
IN operator is used with multiple-column subquery.
Example:-
In the above example, as subquery is returning two columns, parent query should
also compare both the columns. Pair-wise comparisons are done.
Example 1:-
Display details of employees who are having sal greater than avg salary of his dept.
Step 1: –
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: –
Select d.deptno, d.dname, d.loc, (select sum (sal) from emp Where deptno =
d.deptno) from dept d;
Inline View: –
Example 1 :-
Step 1:-
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;
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));
Commit;
Create table student54 (rollno number (3), name varchar2 (10), marks number (3));
Create table student55 (rollno number (3), name varchar2 (10), marks number(3));
Rollback Command:-
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));
Create table student57 (rollno number (3), Name varchar2 (10), Marks number (3));
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);
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));
DCL Commands
Grand & Revoke
Grand:-
Create a user: -
Syntax: -
create user <user_name> identified by <password>;
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;
Create table student (rollno number (3), name varchar2 (10), marks number (3));
Commit;
Set sqlprompt ankit>-- to set the name for sql prompt
Set sqlprompt vipan>
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.
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: –
Syntax: –
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.
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.
66 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Create view v30 as select * from emp where deptno=20;
All the above views as they are created using one base table, it is Simple views.
Note:-
Create or replace view v10 as select empno, ename, sal, deptno from emp where
deptno = 10;
67 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Insert into v10 values (2222, ‘BBBB’, 1000, 20);
Complex Views: –
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;
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:-
Create view v50 As select empno, ename , sal, sal*12 annual_sal , deptno from emp;
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.
We can only read the view.Reading is executing select statement on the view.
We cannot perform DML Operations on these views.
Now, we cannot perform insert, update and delete operations on View v70.
We can execute only select stmt on the view.
Create or replace view v80 as select empno, ename, sal,deptno from emp Where
deptno = 10 with check option;
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;
Indexes
Indexes is an object used to improve the performance of the select statement.
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.
Types of Indexes: –
1) Simple indexes
2) Composite indexes
1) Simple Indexes: –
Syntax: –
Assume emp table is having 1 million records, the query performance is slow.
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:-
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
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: –
Select * from emp Where sal > 2000 and job = MANAGER;
Example:-
These kind of indexes which are created on multiple columns, are called as composite
index.
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: –
Example:-
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;
Drop Index: –
Sequences
Syntax: –
Example: –
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:-
Nextual:-
sequence_name.nextval
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: –
Example:-
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:-
Example 3:-
Important
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.
Drop sequence: –
Synonyms
Syntax: –
Example:-
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.
Drop synonym: –
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: –
Examples: –
NVL Function
The NVL( ) function is available in Oracle. This function is used to replace NULL value
with another value.
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.
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.
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));
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: -
82 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
For Practice:-
Employees
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:-
Example 2:-
Example 3:-
Example 4:-
84 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Equi Joins:-
Example 1: -
d.department_name, d.location_id
Example 2: -
regions r, countries c
Example 3: -
l.postal_code, c.country_name
85 | P a g e www.selfonlinetraining.wordpress.com
Email: - Mailankitnarula@gmail.com
Example 4:-
d.department_name,c.country_name,l.city
Self Join: -
Select e.employee_id,e.first_name,e.last_name,e.salary,
86 | P a g e www.selfonlinetraining.wordpress.com