SlideShare a Scribd company logo
1 of 137
SQL
1
 Basics on Database
 What is SQL
 Features of SQL
 History of SQL
 SQL sub Languages
 Data types & Constraints
 SQL Operators
2
 SQL Functions
 SQL Clauses
 Sub-Queries
 Nested & Correlated Queries
 Normalisation
3
Employee
Salary Emp_Id Dept_no
• It is a raw fact which describes the attributes of an entity
Name
Ram 15000 Mail 10
Entity
Attributes
Raw Fact
• Data can be valid/Invalid depending upon the scenario on which
the Data is being provided.
• The collection of Data becomes information.
• We will store only valid Data in the Database.
• Simply just storing the Data is not important , how fast we can retrieve it
when it is required to be used is also important
4
• Database is medium to store the Data in an organised and systematic manner.
• Every Database should have these following functionalities
i. Insert the Data
ii. Retrieve the Data
iii. Modify the Data
iv. Delete the Data
• The DB user should be able to do all the above operations
5
• DBMS is a software(set of programs) which is used to create,manage and manipulate
the DB
• The Data stored in the form of files(with different extensions)
so we can’t establish the relationship between the Data.
• It provides the security to the DB.
• It provides authorization to the user
• To communicate with the DBMS we use a language called Query language
6
1. SQL
2. My SQL
3. Mongo DB
4. SQL Server
5. Postgres
6. DB2
• A DBMS software may have any of the following models to store the data
i. Relational Model
ii. Network Model
iii. Object Model
iv. File/Document Model
7
• A DBMS is a software which store the Data in a systematic manner by using
relational Model such a DBMS is known as RDBMS.
• According to the relational model the data must be stored in the form of Tables.
•A Table is a logical structure consists of Rows and Columns and Cells.
Here,
 Rows are referred as Records/Tuple.
 Columns are referred Attributes/Fields.
 Table is referred as Object/Relation.
8
• SQL – Structured Query Language
• It is defined as, SQL is a query language which is used to communicate with DBMS
• Communicate in the sense we can create,manage and manipulate DB
by using Queries
9
• IBM developed the 1st relational model based DBMS called System-R in 1970.
• To interact with that they developed the language called SEQUEL.
• Later it is assigned with ANSI standards and then its named as SQL
• The current Owner of SQL is Oracle.
• We are using Oracle 10g ,current version is 19c and the first version is 1i
• The Father of SQL is Raymond Boyce.
• Co-father is E.F Codd.
10
• SQL is used to access the Data from RDBMS.
• SQL can execute Queries against the DB.
• SQL used to describe the Data in the DB and manipulate it when needed.
• SQL is used to create and drop DB and Table.
• SQL allows users to set permissions on tables, procedures and views.
11
I. Clear Screen[ Cl Scr] : Which is used to clear the screen.
II. SET lines: To adjust the no of characters to be in a line.
III. SET pages: To adjust the no of lines to be in a page.
IV. Connect user: To connect one user to another.
V. Show user: To show the current user.
VI. Desc: To describe the particular table.
VII. Show recycle bin
VIII. Desc recycle bin
12
There are 5 types in it
1. Data Definition Language
i. Create
ii. Alter
iii. Rename
iv. Drop
v. Truncate
2. Data Manipulation Language
i. Insert
ii. Update
iii. Delete
13
3. Transaction Control Language
i. Commit
ii. Save point
iii. Rollback
4. Data Control Language
i. Grant
ii. Revoke
5. Data Query Language
i. Select
14
DQL is used retrieve the data
• SELECT statement is used to simply retrieve the Data from the DB.
15
Syntax,
SELECT Col_name /Exp
FROM Table_name;
Example,
SELECT * or
FROM emp;
SELECT ename
FROM emp;
Note: The SQL
statements are
case insensitive but
the Table Data is
Case sensitive;
Note: * represents
All the details
1. Display all the tables present in existing user
Q . SELECT *
From Tab;
2. Write a query to display all the employee’s manager number
Q. SELECT mgr
From emp;
3. WAQTD all the employees empno and commission
Q. SELECT empno,comm
From emp;
16
• This statement is used to return only distinct(different) values.
• Inside a table a column may often contains duplicate values and
sometimes you only want to list the different(distinct) values then we
will go for Distinct Statement.
• It can accepts any no of arguments.
Syntax,
SELECT Distinct colm_name from emp;
Example,
1
Q.
Q.
SELECT distinct ename from emp;
SELECT distinct ename, job,deptno from emp;
1. Arithmetic Operator [+, - , * , /]
2. Concatination Operator [||]
3. Comparison Operators [ = , != or <>]
4. Relational Operators [ > , < , >= , <= ]
5. Logical Operators:
AND , OR , NOT
6. Special Operators:
IN , NOT IN , Like , Not Like , Between , Not Between , Is , Is Not
7. Sub-Query Operators:
ALL , ANY , EXISTS , NOT EXISTS
8. Set Operators:
UNION , UNION ALL , INTERSECT , MINUS.
17
• Aliasing is the alternate name given to the column.
• Aliasing is for user convenience(optional)
Syntax,
SELECT Col_name/Exp as alias_name
From Table_name
18
Example,
WAQTD salary as annual_sal from employee table
SELECT Sal as annual_sal
From emp;
Q.
Note:
 we can’t use
alias names in
where clause
 We can use in
order by clause
Note:
 By giving space
we can alias the
column
19
• These operators are used to perform arithmetic Operations such as Addition, Substitution,
Division and Multiplication.
QUERIES:
1. WAQTD the total salary of the employee from the emp table
SELECT sal+comm or
From emp;
SELECT sal+comm as total_sal
From emp;
2. WAQTD all the employee’s annual salary from employee table
SELECT sal*12 or
From emp;
SELECT sal*12 as annual_sal
From emp;
3. WAQTD half yearly salary of all the employees from employee table
SELECT sal*6
From emp;
4. WAQTD all the employee’s sal with 20% hike in the salary
SELECT (sal+(sal*20/100))
From emp;
5. WAQTD employee’s total annual salary from emp table
SELECT (sal*12)+comm as “annual salary”
From emp;
6. WAQTD quarterly salary of employees from emp table
20
Note:
 We can’t perform
arithmetic
operations for null
values
 WE can use ‘_’ or
“ “ for multiple
strings in select
statement
• Where clause is used to filter the records or This clause is used to display the
records based on the condition
21
Syntax, SELECT col_name/Exp
From table_name
Where <Condition>;
Example,
WAQTD all the details of the employee who are working in dept
20
Q. SELECT *
From emp
Where deptno=20;
• Concatenation operator is used to join the two or more strings by using
22
pipe operator.
• We will get the result in sentences.
QUERIES:
1. WAQTD Mr Smith your salary is 2000Rs
SELECT ‘Mr ’||ename||’ your salary is ‘||sal||’ Rs’
From emp;
2. WAQTD Mr Scott your promoted from designation to Manager
SELECT ‘Mr ’||ename||’ your promoted from ‘||job
||’ to ‘||’ Manager’
From emp;
Note:
 ||  Pipe
Operator
Note:
 If want single
output then
we will use the
DUAL table
DUAL is a dummy
table present in
the DB. It is used
for the purpose of
calculation
without using
User table
Comparison Operators are used when we have to return single record or output.
• We have = , != or <>
Example,
1
Q WAQTD names of the employees who are working as Salesman.
SELECT ename from emp
Where Job = ‘SALESMAN’;
Q WAQTD employee no of employees who are not working under manager
7389.
SELECT empno from emp
Where mgr != 7389;
OR
Where mgr <> 7389;
Relational Operators are used when we have to return Greater than , >= , less
than , <= conditions in a single output.
Example,
1
Q. WAQTD the names of employees who are getting salary more than
3000.
SELECT ename from emp
Where sal > 3000;
Q WAQTD details of the employees who are working behind the dept 30
SELECT * from emp
Where deptno <30;
Example
In the following expression multiplication has a higher precedence than addition, so Oracle first
multiplies 2 by 3 and then adds the result to 1.
1+2*3 You can use parentheses in an expression to override operator precedence. Oracle evaluates
expressions inside parentheses before evaluating those outside.
1
Operator Operation
( ) Parentheses
*, / multiplication, division
+, -, || addition, subtraction, concatenation
=, !=, <, >, <=, >=, IS NULL, LIKE, BETWEEN, IN comparison
NOT exponentiation, logical negation
AND conjunction
OR disjunction
1. OR,
A B R
0 0 0
0 1 1
1 0 1
1 1 1
• OR Operator will return the records based on both the 1st
condition.
• If the 1st condition is false then only it will check the 2nd
condition.
• If the 1st condition is true then it won’t check the 2nd condition
directly it will return the output.
• If any one condition satisfies or If any one of the condition is
true then it will display the output.
Note:
 0 = False
 1 = True
Syntax,
SELECT col_name/exp
From emp
where (col_name/exp or col_name/exp);
A
B
23
A+B
2. AND,
A B R
0 0 0
0 1 0
1 0 0
1 1 1
• AND Operator will return the records based on both the
conditions.
• If the 1st condition is true then also it will check the 2nd
condition.
• If both the conditions satisfies or If both the conditions are
true then only it will display the output.
Syntax,
SELECT col_name/exp
From emp
where (col_name/exp and col_name/exp);
A
B
A.B
24
1. WAQTD all the details of an employee whose mgr number is 7839 or 7566
SELECT *
From emp
Where mgr =7839 or mgr =7566;
2. WAQTD names of all the manager hired after April 81 SELECT
ename
From emp
Where job=‘MANAGER’ and hiredate> ’30-APR-81’;
3. WAQTD name of the clerk if he works in dept 10 or 20 or 30 SELECT
ename
From emp
Where deptno=10 or deptno=20 or deptno=30;
4. WAQTD all the details of the employees who is working as manager or clerk in dept 10/30 SELECT *
From emp
Where (job=‘MANAGER’ or Job=‘CLERK’) and (deptno=10 or deptno=30);
25
5. WAQTD details of the employees working as analyst hired after 1985 getting salary > 2500 but less
than 4000.
6. WAQTD all the employee details who is working under dept 30.
7. WAQTD all the employee name whose manager number is 7698.
8. Display emp name and emp number who is getting salary 1600 and 1500.
9. Write AQTD all emp details who is getting salary > 1250 and < than
1600.
10. Display manager number for all emp working in dept number 10.
26
11. WAQTD all employees whose salary is 1600.
12. WAQTD empno,job of all the employees whose mgr no is 7698.
13. WAQTD all the employees who does not belongs to dept 20.
14. WAQTD all employees who are working in dept 20 or job is manager.
15. WAQTD all the employees whose mgr no is 7839 or job is select.
16. Display all the employees whose comm is<=100 and job is salesman.
17. WAQTD all the employees whose mgr is 7698 and joined from 20-FEB-81.
18. WAQTD the employees who doesn’t belongs to dept 20 and getting some comm.
19. WAQTD the employees working in dept 10 or 20 and job is manager or salesman.
20. WAQTD the employees whose mgr is either 7698 or 7839 or job is manager or joined from 20-SEP-81.
27
1. IN Operator : In operator is a multi-valued operator which can accept single
value at LHS and multiple values at RHS .
Example;
To select a manager working in either of deptno 10 or 20 or 30
• Instead of using comparison operator we can use IN operator here,
SELECT *
From emp
Where job=‘MANAGER’ and deptno IN(10,20,30);
• IN operator works similar to OR operator.
• IN operator is generally preferred when we have multiple conditions with
respect to LHS
28
2. NOT IN Operator : It is an operator which accept multiple values or single values in
RHS to filter the records with respect to LHS
Syntax,
29
WHERE col_name NOT IN(V1, V2, V3);
Example,
1. WAQTD the names of the employees who are not working in dept 20 and dept 10
SELECT ename
From emp
Where deptno not in(10,20);
2. WAQTD names of the employees except smith from table emp
SELECT ename
From emp
Where ename not in(‘SMITH’);
3. Between Operator is used whenever we have range of values (Lower range and
Higher range)
• Between Operator works including the ranges.
• Interchange of lower and higher range is not possible
Syntax,
Where colm_name/exp between(L_range and U_range);
30
Example,
WAQTD name,deptno of employees whose salary is in the range of 800
and 3000
SELECT ename,deptno
From emp
Where Sal between 800 and 3000;
4. Not between Operator is used whenever we have a range of values and
this operator works excluding the ranges
Syntax,
Where colm_name/exp not between(L_range and H_range);
31
Example,
WAQTD name,deptno of employees whose salary is in the range of 800
and 3000
SELECT ename,deptno
From emp
Where Sal between 800 and 3000;
5. IS Operator is used to check whether the values present at the LHS is
null or not.
• This Operator is only used to check the null values.
Syntax,
Where Colm_name/exp is null;
32
Example,
WAQTD the details of employees who are not getting any commission
from table emp
SELECT *
From emp
Where comm Is null;
6. IS NOT Operator is used to verify the value present in the LHS is
not null
Syntax,
Where Colm_name/exp Is not null;
33
Example,
WAQTD the name of the employees who are getting some commission
SELECT ename
From emp
Where comm is not null;
7. LIKE Operator is used to perform pattern matching or Wild card searching.
Syntax,
Where colm_name/exp Like ‘Pattern’;
34
• If we want to specify multiple pattern then we should specify like operator
multiple times
• The pattern is case sensitive and it should be in the form of regular
expression
• Regular expression is noting but combination of ordinary characters and
meta characters ( % , _ )
• Meta characters are also called Wildcards
• Percentile(%) can take any no of memory
• Underscore(_) can take exactly one value
Example,
• Name starting with S  ‘ S% ’
• Name ending with S  ‘%S’
• S having anywhere in the name  ‘%S%’
• Name starts with J ends with S  ‘J%S’
• Name has A in the second space  ‘ _A%’
• Name has A in the second last space  ‘%A_’
• A name has 4 characters  ‘ ’
Note: Not like Operator works opposite to the Like Operator
Syntax,
Where colm_name/exp not like ‘Pattern’;
35
Note: Like operator is
also called as wild
card operator
1. WAQTD Name of the employee if his name consists of character A and ends with S
SELECT ename
From emp
Where ename like ‘ %A%S ’;
2. WAQTD name and salary of an emp who gets 3 digits salary
SELECT ename and sal
From emp
Where Sal like ‘ ’;
3. WAQTD total salary needed to pay employees hired in FEB
SELECT sal+comm From emp
Where hiredate like ‘%FEB%’;
4. WAQTD the employees who joined company in the year 1987
SELECT *
From emp 36
• Functions are defined as the set of instructions or block of codes which are used to perform
particular task
• Functions consists of 3 major components
1. Function name
2. No of arguments
3. Return type
• There are two types of functions such as
1. Single row Functions :
SRF can take one input ,process and generates results for the single input. If we pass n no of
inputs for a SRF we will get n no of outputs.
2. Multi row Functions :
MRF will aggregate or combine all the inputs and generates single output If we pass n no of
inputs we will get a single output
37
• SRF can take one input ,process and generates results for the single input.
• If we pass n no of inputs for a SRF we will get n no of outputs.
• SRF can take one or more arguments as input.
• We can use any number of SRF( ) in Select Clause.
 SRF mainly have 5 types functions in it
1. Case Manipulation Functions
2. Character Manipulation Functions
3. General Functions
4. Number Functions
5. Date Functions
38
Case Manipulation function will takes a string value as an argument and returns a string
There are 3 types of functions in it
i. UPPER( )
ii. LOWER( )
iii. INITCAP( )
1. UPPER( ) : It takes string as an argument and converts it into upper case
Eg, SELECT Upper(‘smith’) from dual;
2. LOWER( ) : It takes string as an argument and converts it into lower case
Eg, SELECT Lower(‘SMITH’) from dual;
3. INITCAP( ) : It takes string as an argument and converts the initial alphabets
into Upper case
Eg, SELECT Initcap(‘smith’) from dual;
39
1. Concat( )
2. Length( )
3. Substr( )
4. Instr( )
5. Replace( )
1. CONCAT( ):
• This function add two or more strings/expressions together.
• It takes exactly two parameters as an argument.
41
Syntax,
SELECT Concat( Exp1,Exp2 ) from table_name;
Example,
SELECT Concat( Ename, ‘is a clerk’) from emp;
Parameters Description
Exp1 , Exp2 Required, The expression to
add together
2. LENGTH( ):
• This functions returns the length of a string(in a Bytes).
• It takes exactly one parameter as an argument.
42
Parameter Description
Exp1 Required, the string to count the length for
Syntax,
SELECT Length(exp1) from table_name;
Example,
Q.
Q.
SELECT sal,length( sal) from emp;
SELECT sal,length(sal) from emp
Where length(sal)=3;
Parameter Description
Exp 1 Required, The string to extract from
Exp 2 Required, The string position can be both +ve or -ve
Exp 3 Optional, The no of characters to extract
Syntax,
SELECT substr(exp1,exp2,exp3) from table_name;
Example,
Q.
Q.
SELECT substr(‘Jspiders’,2,7) from dual;
SELECT substr(‘Jspiders’,-2,7) from dual;
3. SUBSTR( ):
• This function extracts a substring from a string(sorting at any position)
• It takes 3 parameters as an arguments(1 optional pmtr)
Note: Positions of String
(-1, -2 -3 ,-4,-5, -6, -7,-8)
(J , S , P , I , D , E , R , S)
( 1 , 2 ,3 , 4 ,5 , 6 , 7 , 8)
Note: The optional string can’t
be -ve
43
4. INSTR( ):
• It returns the position of the first occurrence of a string in another string
• It takes exactly 2 values as an arguments.
44
Parameter Description
Exp1 Required, The string that will be searched
Exp2 Required, The string to search in string1
Note:
 It returns ‘0’ if
string is not
found
Note:
 Exp2 is Case
sensitive
Syntax,
SELECT instr(exp1,exp2) from dual;
Example,
Q.
Q.
Q.
SELECT instr(‘Jspiders’ , ’s’) from dual;
SELECT instr(‘Jspiders’ , ‘S’) from dual;
SELECT instr(‘Jspiders’ , ‘sp’) from dual
5. REPLACE( ):
• It replaces all the occurrence of the substring within a sting with new string.
• It takes maximum of 3 parameters as arguments.
45
Parameters Description
Exp1 Required, The original string
Exp2 Required, The substring to be replaced
Exp3 Required, The new replacement substring
Note:
 Exp 2 is Case
sensitive
Syntax,
SELECT Replace(exp1,exp2,exp3) from dual;
Example,
SELECT Replace(‘SALESMAN’, ‘SALES’, ‘SUPER’) from dual;
1. MOD( )
2. POWER( )
3. SQRT( )
4. ROUND( )
5. TRUNC( )
1. MOD( ):
• This function is used to obtain the modulus of the input(%)
• It will always returns the reminder values of a no divided by another no.
• It takes exactly 2 numbers as an argument.
Syntax,
SELECT mod(no1,no2) from table_name;
Example,
46
Q.
Q.
SELECT mod(20,3) from dual;
SELECT mod(2,4) from dual;
2. POWER( ):
• It returns the value of a no is raised to the power of another value.
• It takes exactly 2 values as an argument.
Syntax,
SELECT power(a , b) from table_name;
47
Example,
SELECT power(2,4) from dual;
Parameter Description
No 1 Required, A number(Base)
No 2 Required, A number(Exponent)
3. SQTR( ):
• SQRT functions returns the square root of the number or char.
• It accepts exactly one value as an argument.
Syntax,
SELECT sqrt( no ) from table_name;
48
Parameter Description
No1 Required, A no to calculate the
square root of, must be > 0
Example,
SELECT sqrt(64) from dual;
4. ROUND( ):
• Round function will rounds a number to specified no of decimal places.
• It will accept either 1 or 2 values as an argument.
Syntax,
SELECT round(no1,no2) from table_name;
49
Example,
Q.
Q.
SELECT round(23.333) from dual;
SELECT round(23.333,1) from dual;
Parameter Description
No Required, The no to be rounded
Decimals Optional, No of decimal places to round
the number
Note:
 Rounds to the nearest
whole no
5. TRUNC( ):
• It truncates the no to specified decimal places.
• It will accept either 1 or 2 values as an argument.
Syntax,
SELECT trunc( no1 , no2 ) from table_name;
50
Example,
Q.
Q.
Q.
SELECT trunc (23.777) from dual;
SELECT trunc (23.44) from dual;
SELECT trunc (23.45454,2) from dual;
Parameter Description
No Required, The no to be truncated
Decimal Optional, The no of decimal places to
be truncated
1. NVL( )
2. NVL2( )
1. NVL( ):
• NVL accepts 2 parameters as arguments. If exp1 evaluates null, then nvl( )
returns exp2.If exp1 is not null then it will return exp1.
51
Syntax,
SELECT nvl (exp1 , exp2) from table_name;
Example,
Q.
Q.
Q.
SELECT nvl (null , 2) from dual;
SELECT nvl (2 , 2) from dual;
SELECT nvl( comm , 0) from emp;
Note: Expressions are of same
or different data types
2. NVL2( ):
• It accepts 3 parameters as arguments. If exp1 is null nvl( ) returns exp3, if exp 1 is
not null it will return exp2.
Syntax,
SELECT nvl2 (exp1 , exp2 , exp3) from table_name;
Example,
52
Q.
Q.
SELECT nvl2 (null , 1, 2) from dual;
SELECT nvl2( comm , 40, 0) from emp;
• MRF( ) will aggregate or combine all the inputs and generates single output.
• If we pass n no of inputs we will get a single output.
• MRF( ) will ignore the null values.
• We cannot write MRF( ) in where clause and group clause
• In select Clause we cant use any other column name or expression with MRF( ).
•We can use any no of MRF( ) in Select Clause.
Types of MRF( ) functions:
53
1. MAX( )
2. MIN( )
3. COUNT( )
4. SUM( )
5. AVG( )
Note: MRF( ) accepts only
single value as an
argument, which is
colm_name/exp
1. MAX( ):
• This function used to obtain the maximum value from a column.
Syntax,
SELECT max(Colm_name/exp) from table_name;
Example,
Q. WAQTD the maximum salary of employee from table emp
SELECT Max(sal) from emp;
2. MIN( ):
• This function used to obtain the minimum value from a column.
Syntax,
SELECT min( colm_name/exp) from table_name;
Example,
Q. WAQTD the min(sal) from emp; 54
3. SUM( ):
• This function is used to obtain the summation of all the values present in a
column.
Syntax,
SELECT sum(Colm_name/exp) from table_name;
Example,
Q. WAQTD total salary needed to pay employees hired in FEB
SELECT sum(sal)
From emp
where hiredate like ‘%FEB%’;
55
56
4. AVG( ):
• It used to obtain the average of all the values present in a column.
Syntax,
SELECT avg(Colm_name/exp) from table_name;
Example,
Q. WAQTD average salary needed to pay all the employees
SELECT avg(sal) from emp;
5. COUNT( ):
• This function is used to count the no of records present in the table.
Syntax,
SELECT */colm_name/exp from table name;
Example,
Q. WAQTD the no of employees getting salary less than 2000 in dept no 10
SELECT *
From emp
where sal<2000 and deptno=10;
1. WAQTD total salary needed to pay employees working as Clark.
SELECT sum(sal)
From emp
Where ename =‘CLARK’
2. WAQTD no of employees having A as there first character.
SELECT count(*)
From emp
Where ename like ‘A%’;
3. WAQTD no of employees working as Clerk or Manager.
SELECT count(*)
From emp
Where job= ‘CLARK’ or job= ‘MANAGER’;
4. WAQTD no of employees reporting to 7839 mgr.
SELECT count(*)
5. WAQTD no of employees earning commission in deptno 20 from emp
SELECT count(*)
From emp
Where comm is not null and deptno=20
6. WAQTD avg salary,total salary,no of employees and maximum salary of the
employees who are working as president.
7. WAQTD the no of employees who are having A in their names.
8. WAQTD the no of employees and total salary needed to pay the employees
who have two consecutive Ls in their name
9. WAQTD no of departments present in employee table
• A Query written inside another query known as sub query.
Working principle:
Outer Query
Result Inner Query
O/p
I/p
• The inner query executes first.
• The output of the inner query is given as input to the outer query.
• Taking the input the outer query executes completely generating a result.
• Therefore we can say that the outer query is dependent on inner query.
A. CASE 1
Whenever we have unknown values we go for sub-query.
Example,
Q. WAQTD name of the employees who are earning more than smith.
SELECT ename
From emp
Where sal > (SELECT sal
From emp
Where ename=‘SMITH’;)
Note: The datatype on the
conditions must be exactly
same , irrespective of columns
Mgr = Number(4)
Empno =Number(4)
In above query salary of smith is unknown, therefore we wrote a sub-query
to find the unknown.
Example,
Q. WAQTD all the details of employees having same designation as Ward
SELECT *
From emp
Where job in(select job from emp
Where ename=‘WARD’;
Q. WAQTD name and salary of the employees earning less than jones
SELECT sal,ename
From emp
Where sal<(select sal from emp where ename=‘JONES’;)
B. CASE 2
Whenever the data to be selected belongs to two different tables.
Example,
Q WAQTD loc of the employees who are getting salary greater than 3000
SELECT loc
From dept
Where deptno in (select deptno from emp Where sal>3000;)
Q. WAQTD dept name of jones
SELECT dname
From dept
Where deptno in (select deptno
From emp
Where ename=‘JONES’;)
1. wAQTD name of the employees who are working in the same dept as Turner.
2. WAQTD name and sal of the employees earning less than Jones.
3. WAQTD all the details of the employees working in the same designation as James.
4. WAQTD no of the employees working for King.
5. WAQTD name and hiredate of employees who are getting sal more than Smith but less than Clark.
6. WAQTD no of employees who are hired after Martin and getting salary less than King.
7. WAQTD name and job of the employee who earn comm and get salary less than Scott.
8. WAQTD dept name Adams.
9. WAQTD location in which Smith works.
10. WAQTD name and dept of the employees who works in accounting dept.
11. WAQTD name and deptno of the employees who earn more than Ward and work in Research.
12. WAQTD no of employees working in Boston.
13. WAQTD name and salary of the employees who are working as Clerk in Chicago.
14. WAQTD all the details of the employees who are earning less than King and working in Smith’s dept.
15. WAQTD all the details of the employees who are working as manager in new york.
16. WAQTD name of the employees working the same job as Scott , getting salary more than Adams and working
in dept in which Martin works.
1. Single Row Sub-Query.
2. Multi Row Sub-Query.
1. Single Row Sub-Query:
• If the sub-query returns exactly one record then it is referred as SRSQ.
• If it returns one record, we can use normal operators , such as = , != or <> ,
>= , <= , < , >.
Example,
Q. WAQTD names of employees who are getting comm more than James.
SELECT ename
From emp
Where comm > (select comm from emp
Where ename= ‘JAMES’);
2. Multi Row Sub-Query:
• If the sub-query returns more than one record then it is called MRSQ.
• When it returns more than 1 records we can’t use normal operators
instead we use special operators or sub-query operators such as ALL , ANY.
Q.
WAQTD the name of employee whose manager works in new york.
SELECT ename
From emp
Where mgr in(select empno from emp
Where deptno in (select deptno from emp
Where loc= ‘NEWYORK’));
• When we write more than one sub-query , then it is called nested sub-query.
• We can nest up to 225 sub-queries at the max.
Example,
Q. WAQTD 2nd minimum salary.
SELECT min(sal)
From emp
Where sal in(select min(sal) from emp
Where sal>(select min(sal) from emp));
A SQL Join statement is used to combine data or rows from two or more tables
based on a common field between them.
Different types of Joins are:
1. INNER JOIN
2. LEFT JOIN
3. RIGHT JOIN
4. FULL JOIN
5. SELF JOIN
6. CARTISION JOIN
7. EQUI JOIN
Outer Joins
Note: We can also write
JOIN instead of INNER
JOIN. JOIN is same as
INNER JOIN.
The simplest Join is INNER JOIN.
1. INNER JOIN: The INNER JOIN keyword selects all rows from both the tables as
long as the condition satisfies. This keyword will create the result-set by
combining all rows from both the tables where the condition satisfies i.e. value of
the common field will be same.
Syntax,
SELECT table1.column1,table1.column2,table2.column1,…
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;
table1: First table.
table2: Second table
matching_column: Column common to both the tables.
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1 LEFT JOIN table2
ON table1.matching_column = table2.matching_column;
table1: First table.
table2: Second table
matching_column: Column common to both the tables.
2. LEFT JOIN: This join returns all the rows of the table on the left side of the join
and matching rows for the table on the right side of join. The rows for which
there is no matching row on right side, the result-set will contain null.
LEFT JOIN is also known as LEFT OUTER JOIN.
Syntax,
Note: We can also use
LEFT OUTER JOIN instead
of LEFT JOIN, both are
same.
Syntax,
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;
table1: First table.
table2: Second table.
matching_column: Column common to both the tables.
3. RIGHT JOIN: RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows
of the table on the right side of the join and matching rows for the table on
the left side of join. The rows for which there is no matching row on left
side, the result-set will contain null.
 RIGHT JOIN is also known as RIGHT OUTER JOIN.
Note: We can also use
RIGHT OUTER JOIN instead
of RIGHT JOIN, both are
same.
4. FULL JOIN: FULL JOIN creates the result-set by combining result of both LEFT
JOIN and RIGHT JOIN. The result-set will contain all the rows from both the
tables. The rows for which there is no matching, the result-set will
contain NULL values.
Syntax,
SELECT table1.column1,table1.column2,table2.column1,..
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;
table1: First table.
table2: Second table
matching_column: Column common to both the tables.
Q. WAQTD all the details of the employees from both the tables.
SELECT *
From emp
inner join dept
On emp.deptno= dept.deptno
Q. WAQTD employee name,sal,deptno,dept name for all employees.
1. WAQTD employee name and his department name for all the employees.
2. WAQTD name of the emp along with his location for all the employees.
3. WAQTD name of employee and his department name if the employee work as
salesman.
4. WAQTD name and Dname of all the employees working for accounting dept.
5. WAQTD salary and Dname for all the employee.
6. WAQTD Dname and annual salary for emp who earn more than 2450.
90
7. WAQTD Dname and hiredate of all employees who were hired during 81.
8. WAQTD all the details of employee and his department if he works in chicago or new york
9. WAQTD name and Dname for the employees if the name of emp’s , job and his Dname starts with
same char ‘s’.
10. WAQTD name and Dname and the location for emp’s if emp’s location is dallas and employees has to
working as manager.
11. WAQTD Dname and commission for all the employees who earn commission.
12. WAQTD Dname and salary and sal with 25% hike if the employee salary is less than 2500 and works as
clerk in new york.
13. WAQTD Ename and Dname for all the employees if they are working as manager or clerk in accounting
or research dept with sal more than joins.
14. WAQTD Dname and avg sal for each dept .
15. WAQTD employee name and department name if the employee gets max salary.
16. WAQTD name of the employee and department name if employees names and department name first
character is ‘A’ or’ S’ and employee should be earning more than ‘Smith’ and also he has to be hired
before the last employee and he may or might be reporting to king or jones.
17. WAQTD employee name and department name if employee is working in same location as his
manager 90
91
5. SELF JOIN: As the name signifies, in SELF JOIN a table is joined to itself.
That is, each row of the table is joined with itself and all other rows
depending on some conditions. In other words we can say that it is a join
between two copies of the same table.
Syntax,
SELECT table 1.coulmn1 , table2.column2
FROM table 1,
JOIN table 2,
ON some_condition;
Table 1: first table
Table 2: second table
some_condition: Condition for selecting the rows.
CONTACT: 7760200900 HR: 7022889639
92
Example,
Q. WAQTD the employee names along with their manager names.
SELECT emp.ename,man.ename mname
From emp
join emp man
where emp.mgr= man.empno;
Q. WAQTD all the details of employees where sal greater than his manager
salary.
SELECT *
From emp
join emp man
on emp.mgr=man.empno
where emp.sal> man.sal;
CONTACT: 7760200900 HR: 7022889639
1. WAQTD employees name, his manager name and employee salary and his manager
salary
2. WAQTD the employees name, his manager name, manager’s manager name, mgr’s mgr’s
mgr’s name.
3. WAQTD name of the employee and his managers name if employee is working as Clerk
4. WAQTD name of the employee and managers salary if employee and manager both earn
more than 2300
5. WAQTD employee name and managers hiredate if emp was hired before 1982
6. WAQTD employee name and manager comm if employee works as salesman and
manager works in dept 30.
7. WAQTD employee name and manager name and their salaries if employee earns more
than manager.
8. WAQTD employee name and hiredate , manager name and hiredate if manager was hired
before employee.
9. WAQTD employee and manager name if both are working in same job.
10. WAQTD employee name and manager name if manager is working as actual manager.
CONTACT: 7760200900 HR: 7022889639
93
 CASE 1:TO FIND MANAGER NAME
Example:
WAQTD name of SMITH's manager .
SELECT ENAME
FROM EMP
WHERE EMPNO = ( SELECT MGR
FROM EMP
WHERE ENAME ='SMITH') ;
WAQTD Location of Adams's manager's manager .
SELECT LOC
FROM DEPT
WHERE DEPTNO = ( SELECT DEPTNO
FROM EMP
WHERE EID = ( SELECT MGR
FROM EMP
WHERE EID = ( SELECT MGR
FROM EMP
WHERE ENAME ='ADAMS' ) ) ) ;
 CASE 2:TO FIND EMPLOYEE NAME
Ex:
WAQTD Name and salary given to the employees reporting
To James .
SELECT ENAME , SAL
FROM EMP
WHERE MGR = ( SELECT EID
FROM EMP
WHERE ENAME ='JAMES' ) ;
WAQTD dname of the employee reporting to President .
SELECT DNAME
FROM DEPT
WHERE DEPTNO = ( SELECT DEPTNO
FROM EMP
WHERE MGR = ( SELECT EID
FROM EMP
WHERE JOB ='PRESIDENT' ) ) ;
1.WAQTD smiths reporting manager's name
2.WAQTD Adams manager's manager name
3.WAQTD dname of Jones manager
4.WAQTD miller's manager's salary
5.WAQTD loc of smith's manager's manager.
6.WAQTD name of the employees reporting to Blake
7.WAQTD number of employees reporting to king
8.WAQTD details of the employees reporting to Jones
9.WAQTD enames of the employees reporting to Blake's
manager
10.WAQTD number of employees reporting to ford's manager
 "A query written inside another query such that the outer query and the
inner query are Dependent on each other , this is known as Co-Related
Sub-Query".
Outer Query
Inner Query
o/p (partially)
i/p
o/p
i/p
Result
Inter-
dependent
 Let us consider two queries inner and outer query respectively ,
1.Outer query executes first but partially
2.The partially executed output is given as an input to the inner Query
3.The inner query executes completely and generates an output
4.The output of inner query is fed as an input to the Outer query and Outer Query
produces the result .
5.Therefore, we can state that the outer query and the inner query both are
INTERDEPENDENT ( dependent on each other ) .
NOTE:
 In co-related sub query a Join condition is a must , And must be written only in the
Inner Query.
 Co-Related sub query works with the principles of both SUB QUERY & JOINS .
SUB QUERY CO-RELATED SUBQUERY
Inner query executes first Outer query executes first
Outer query is dependent on inner query Both are interdependent
Join condition not mandatory Join condition is mandatory and must be written
in inner query
Outer query executes Once Outer query executesTwice .
• Pseudo column is an imaginary column, behaves like a table column. But it is not actually
stored in the table.
• We can select these columns but we can’t manipulate(Insert, Update , Delete)
their values Types of
1. Rownum
2. Rowid
1. ROWNUM:
•Rownum is a serial number that is assigned to the result table.
• Rownum is assigned at the time of execution.
• Rownum is always starts with 1.
• Rownum is dynamic.
Syntax,
SELECT Rownum from table_name;
2. ROWID:
• For each row in the database, the Rowid returns the address of the row
• By using Rowid we can fetch the records
• Rowid is a 18 digit address of the records in the memory
• Rowid is generated at the time of inserting the record
• Rowid is unique and cannot be deleted
• Rowid is static(cannot be changed)
• It also be used to delete the duplicate records .
• They are the fastest way to access a single row.
• They can show you how the rows in a table are stored.
• If you delete a row, then Oracle may reassign its Rowid to a new row inserted later.
Syntax,
SELECT Rowid from table_name;
Example,
Q. SELECT Rowid from emp;
Q. SELECT ename From emp
Where Rowid=Rowid;
• Group by Clause is used to group the records(based on the certain attributes).
• Group by clause executes ‘Row by Row’.
• For group by class we can pass colm_name as argument.
• After the execution of group by clause we get result in groups.
• Any clause executes after group by clause will execute group by group.
• We can pass colm_name which is used in group by clause with MRF() in
select Clause
• We can use group by clause in a query even without using where clause.
Syntax,
SELECT colm_name/exp
From table_name
Where <Condition>
Group by colm_name/exp;
Note:
 Multiple arguments
can be passed to
group by class
Order of execution:
1. From
2. Where Clause( if used )
3. Group by Clause
4. Select
Nature Of Execution:
1. From
2. Where( row by row )
3. Group by ( row by row )
4. Select( group by group)
1. WAQTD average salary given to each department except for department 30
SELECT avg(sal),deptno
From emp
Where deptno !=30
Group by deptno;
2. WAQTD number of emp working in each department except president .
SELECT count(*)
From emp
where job != ‘PRESIDENT’
group by deptno;
3. WAQTD total salary needed to pay to all the employee in each job .
4. WAQTD no of employees working as manager in each dept
5. WAQTD avg salary needed to pay all the employees in each dept
excluding the employees in deptno 20.
6. WAQTD no of employees having character A in their names each job.
7. WAQTD no of employees and avg salary needed to pay the
employees whose sal is greater than 2000 in each dept.
8. WAQTD total salary needed to pay and no of salesman in each job.
9. WAQTD no of employees with their maximum salary in each job.
10. WAQTD maximum salaries given to an employee working in each dept.
11. WAQTD no of times the salaries have been repeated in employee table.
12. WAQTD no of employees hired on the same day into the same dept.
13. WAQTD no of employees getting the same salary in same department.
• Having clause is used to filter the groups.
• It will execute group by group
• Since having clause executes after group by clause we can write MRF( ) in it
as a condition.
• IN having clause we can use the exp used in group by clause
Syntax,
SELECT colm_name/exp
From emp
Where< condition >
Group by colm_name/exp
Having < group filter condition >;
Order of execution:
1. From
2. Where Clause( if used )
3. Group by Clause
4. Select
Nature Of Execution:
1. From
2. Where( row by row )
3. Group by ( row by row )
4. Having clause(group by group)
5. Select( group by group)
1. WAQTD at least 4 employees working in each dept except president.
SELECT count(*),deptno
From emp
Where job!='PRESIDENT'
Group by deptno
Having count(*) >=4;
2. WAQTD total salary needed to pay all the employee in each job if the total
salary of each job exceeds 3450
select sum(sal),job
from emp
group by job
having sum(sal )>3450;
3. WAQTD no of employee working as manager in each dept if their average salary is less
than 2300.
4. WAQTD avg salary needed to pay all the employees in each dept excluding the emp of
dept no 20.If there are at least 3 employees working in each dept.
5. WAQTD no of employees having character A in their names in each job if count of
employees is equal to 2.
6. WAQTD no of employees if more than 3 and avg salary needed to pay the employees
whose salary is greater than 2000 in each dept.
7. WAQTD deptno in which there are at least 4 salesman in each dept.
8. WAQTD no of emp if more than 2 with their maximum salaries in each job.
9. WAQTD maximum salary given to an employee working in each dept if max salary
is >1999.
10. WAQTD the salaries which are repeated or duplicate.
11. WAQTD the hiredate which appear more than one in the employee table.
12. WAQTD the hiredate and deptno if employees hired on the same day into the same dept.
13. WAQTD the salary and deptno if employees getting the same salary in the same dept.
• Order by clause is used to order the returned output into ascending or descending.
• By default Order by clause is in ascending order.
• order by clause should be written as the last clause in the query.
• order by clause executes after select clause.
• In order by clause we can write multiple column names.
• First priority is given to that column name which written 1st in the query.
Syntax,
5.
1.
2.
3.
4.
6.
SELECT colm_name/ exp
From emp
Where< condition >
Group by colm_name/exp
Having < group filter condition >;
Order by colm_name asc/desc
• SQL Data type is an attribute that specifies the type of data of any object.
• Every table has a column, which has a column name , every column stores the
data which has a data type.
• We have to assign every column with the data type while declaring a
column with column name.
Types of Data types:
1. Char
2. Varchar
3. Number
4. Date
5. LOB:
1.CLOB: character LOB
2.BLOB: Binary LOB
1. CHAR data type:
• If a column is assigned with char data type it can store following values.
• The maximum no of characters that should be stored in a column can be
specified using size.
• In char we can store a character string with the size from 1 to 2000 bytes
0 to 9
a to b
A to B
Special char
• Size(default) of the data type is 1
• Char is a fixed length memory allocation.
• We can specify the size for the data type.
Eg, char(2) , char(10)
Note:
 A column can have
maximum of one data type
 Each an every column should
be assigned with data types
2. VARCHAR data types:
• If a column is assigned with varchar data type it can store following values.
0
a
A
to 9
to b
to B
Special char
• BY assigning varchar we can store 1 to 2000 bytes
• By assigning varchar2 we can store 1 to 4000 bytes in a column.(prefer this)
• Varchar is dynamic/variable length memory allocation.
• It wont allocate the memory for null values.
4. DATE data type:
• If a column is assigned with date data type, then it can store only Dates.
• There is no size for date data types.
• In Oracle, Date follows a default format
i.e.
DD-MON-YY & DD-MON-YYYY
3. NUMBER data type:
• If a column assigned with number data type, then it can store only numbers.
• The column can store only positive values
• Number data type takes two arguments (precision , Scale), Precision is the
mandatory argument and scale is optional argument.
• If we want to store the decimal values then we need scale argument.
• Scale should be less than precision
Eg, Number 1234.56
This no is having precision of 6 and scale of 2
Note:
 Precision is the no of digits in a no.
 Scale is the no of decimals in a no.
DML is used to manipulate the records of the table.
CONTACT: 7760200900 HR: 7022889639 94
1. INSERT: Insert is used to add/insert records into the table.
Syntax,
Insert into table_name values(v1,v2,v3,…………);
Insert into table_name(colm1,colm2,colm3,…….) values(v1,v2,v3,……..);
Insert into table_name values(&colm1,&colm2,&colm3,…………);
The above syntax is used to insert multiple records @ a time
Example,
insert into emp values(1264,Basya,painter,……..);
insert into emp(empno, ename, job…..) values(1264,Disha,Actress…..);
Note:
 DML commands are
not permanent.
 Primary key is must
and it should be
unique.
95
2. UPDATE: Update is used to update the existing records of the table with new data.
Syntax,
Update table_name Set
colm_name=Value Where
condition;
Update table_name
Set colm_name= Vlaue,colm_name= Value,…….. Where
condition;
The above syntax is used to update multiple values @ a time.
Example,
Update emp
Set ename=‘BASYA’
Where ename=‘SMITH’;
96
3. DELETE: Delete command is used to delete or remove records from the table.
Syntax,
DELETE from table_name
Where condition;
Example,
Delete from emp
Where ename=‘ALLEN’;
TCL: Any activity performed on the data base is a transaction. So to control the transactions
performed on the data base we use TCL commands.
1. COMMIT: Commit is used to complete the transaction.
BY using commit we can make DML changes permanent.
2. ROLLBACK: This command takes us to the previous transaction Rollback
vanishes all the transactions or DML changes.
If commit command passed after transaction then the changes are
permanent and rollback command wont work.
3. SAVEPOINT: Save point command is used to create multiple Save points. Consider many
transactions done to the table here there and in between we have created save points ,
save points like a, b, c if we roll back to save point b , then what ever changes happened
from save point b all the changes will be vanished . The changes before save point ‘b’ are
unchanged.
CONTACT: 7760200900 HR: 7022889639 97
4. DATA INTIGRITY: Checking the accuracy of the data is called data intigrity.
• Using data intigrity we can ensure that only valid data stored in the DB.
How to achieve data intigrity?
It can be achieved by assigning columns with the data types and constraints
CONSTRAINTS: Constraints are the rules of validation that are assigned on a column.
A column can be assigned with two or more constraints.
•Constraints are optional but they are highly recommended. Types
of Constraints:
1. Null
2. Not Null
3. Unique
4. Check
5. Primary key
6. Foreign key
CONTACT: 7760200900
HR: 7022889639 98
1. NULL:
• Empty cells in table is called null
• Null is neither space nor zero.
• Null doesn’t allocate any memory.
• If we perform any arithmetic operation with null than the result is null
Eg, Null+1= Null
2. NOT NULL:
• If a column is assigned with not null constraints then the cell value cannot be
empty @ any point of time. It can’t be store null values.
AB
BB
AC
BC
AB
BB
BC
AB
BA
BB
HR: 7022889639 99
3. UNIQUE:
• If a column is assigned with unique constraint it cannot store duplicate values
or It store only the distinct values.
AB
BA
BC
BB
AB
AB
BC
BB
CONTACT: 7760200900 HR: 7022889639 100
4. CHECK:
The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a single column it allows only certain values for
this column.
SQL CHECK on CREATE TABLE:
The following SQL creates a CHECK constraint on the "Age" column when the "Persons" table is
created. The CHECK constraint ensures that the age of a person must be 18, or older:
SQL:
CREATE TABLE Persons (
ID number NOT NULL,
Last Name varchar2(25) NOT NULL,
First Name varchar2(25),
Age number,
CHECK (Age>=18)
CONTACT: 7760200900 HR: 7022889639 101
5. PRIMARY KEY:
• If a column is declared as primary key then the records can be identified
uniquely.
• Primary key is a combination of unique and not null constraints.
• A table can have only one key.
• A table consisting of PK is called as parent table or master table.
CANDIDATE KEY:
• The columns which are assigned with unique and not null constraints and they
can qualify as a primary key.
ALTERNATE KEY:
• The columns which are eligible to become primary keys but not declared as PK.
CONTACT: 7760200900 HR: 7022889639 102
6. FOREIGN KEY:
• FK is used to establish the relationship between the tables.
• FK column can accept null and duplicate values.
• In order to declare a column as FK that column should be declared as PK in the
other table.
• A table consisting of foreign key is called as child table.
• FK is also called as referential integrity constraints.
• A table can have more than one FK.
1. CREATE:
• CREATE statement is used to create Objects in DB.
Syntax,
CREATE table table_name
(colm_name Data type(size) Constraints,
colm_name Data type(size) Constraints,……..);
To create duplicate tables:
Syntax,
CREATE table table_name as (SELECT * from reference table_name)
Note: DDL statements are
permanent.
CONTACT: 7760200900 HR: 7022889639 105
2. RENAME:
• Rename is used to rename the tables or columns.
Syntax,
Rename Old table_name to New table_name;
Example,
Rename emp to employee;
3. TRUNCATE:
• Truncate is used to delete or remove all the records from the table at one shot.
• Truncate makes table empty.
• Truncate will not remove table from DB instead it deletes all records permanently.
• Removed records can’t be restored.
Syntax,
Truncate table table_name;
Example,
Truncate table employee;
 Describe the table to get the table structure.
Eg, desc table
CONTACT: 7760200900 HR: 7022889639 106
4. DROP:
• DROP statement is used to delete or remove table from DB or column from
table
Syntax,
DROP table table_name;
Example,
DROP table employees;
• The whole table is deleted from the table and gets stored in recyclebin.
•To restore the table from bin we use a comment called flashback.
FLASHBACK:
Syntax,
Flashback table table_name to before drop;
What is recycle bin?
Recyclebin is a table containing info about dropped objects or tables.
Syntax,
Select * from recyclebin;
• To remove the table permanently without storing in recyclebin, we use a
command called purge
Syntax,
DROP table table_name PURGE; PURGE
table table_name;
• To delete all records from recyclebin; PURGE
Recyclebin;
• If you want to see dropped data from DB.
Show Recyclebin; HR: 7022889639 107
5. ALTER: ALTER statement is used to modify the table with respect to
columns.
Example,
•Adding a Column. Syntax,
ALTER table table_name add colm_name datatype Constraint; Note: while adding
column to the table with not null constraint the table should be empty otherwise we
will get an error.
• Rename a Column.
Syntax,
ALTER table table_name rename column old colm_name to New colm_name;
• Drop a Column.
Syntax,
ALTER table table_name Drop column colm_name;
108
MODIFY:
• Modify is used to change the datatype of a column.
•Modify a Column.
Syntax,
109
ALTER table table_name modify colm_name datatype;
• To unlock the user.
Syntax,
ALTER User user_name Identified by passward account unlock;
Note: The column should
be empty to change the
datatype
By using DCL statements we can control user access.
There are two DCL statements.
1. GRANT
2. REVOKE
1. GRANT: GRANT statement is used to connect or provide permission from
one user to another.
2. REVOKE: REVOKE is used to take back the permissions from the user.
110
1. Normalisation:
2. ERD’s:
3. Set Operators:
4. Analytical Functions:
5. Indexes:
6. Views:
7. Stored procedures:
8. Triggers:
1
 " It is the process of reducing a large table into smaller tables
in order to remove redundancies and anomalies by identifying
their functional dependencies is known as Normalization . “
(Or)
 "The process of decomposing a large table into smaller table
is known as Normalization ."
(Or)
 "Reducing a table to its Normal Form is known as
Normalization ."
What is Normal Form?
 A table without redundancies and anomalies are said to be in
Normal Form .
Levels of Normal From .
1.First Normal Form ( 1NF )
2.Second Normal Form ( 2NF )
3.Third Normal Form ( 3NF )
4.Boyce -Codd Normal Form ( BCNF )
 Note : If anyTable / entity is reduced to 3NF , then the table is
said to be normalized.
1)Union
2)Union All
3)Intersection
4)Minus
UNION: The union operator could to be used to find the result set or
combination of two or more table without returning any duplicate rows.
Note:
• The columns must have same datatypes.
• The columns in each table must be in the same order (but they need not
have to in the same length).
• Each table used within union must have the same no of columns.
• It provides the unique values by default.
 Syntax:
Select col_name
From table_name1
[where <filter-condn>]
Union
Select col_name
From table_name2
[where<filter-condn>];
ORDER OF EXECUTION
FROM
[WHERE](if used)
SELECT
UNION ALL:
The union all operator could to be used to find the result set or
combination of two/more table including returning any
duplicate rows
NOTE
• The columns must have same datatypes.
• The columns in each table must be in the same order(but they
need not have to in the same length)
• Each table used within union must have the same no of
columns.
 Syntax:
Select col_name
From table_name1
[where <filter-condn>]
Union All
Select col_name
From table_name2
[where<filter-condn>];
ORDER OF EXECUTION
FROM
[WHERE](if used)
SELECT
INTERSECT:
Intersect operator is used to combine two select statements,
it returns only common value[equal value] present in the table
[col_name]
NOTE
• The columns must have same datatypes.
 Syntax:
Select col_name
From table_name1
[where <filter-condn>]
INTERSECT
Select col_name
From table_name2
[where<filter-condn>];
ORDER OF EXECUTION
FROM
[WHERE](if used)
SELECT
MINUS:
Minus operator is used to compare to select statements if
returns only the row that are present in the first stmt but are
not in second stmt [distinct value],minus elements are the
duplicate rows.
 Syntax:
Select col_name
From table_name1
[where <filter-condn>]
MINUS
Select col_name
From table_name2
[where<filter-condn>];
ORDER OF EXECUTION
FROM
[WHERE](if used)
SELECT
SQL Create Index Statement:
To increase the execution speed .The create index statement is used to create indexes
in tables , indexes are used to retrieve data from the database more quickly than
otherwise. The user cannot see the indexes, they are just used to speed up
searches/queries.
NOTE:
 Updating a table with indexes takes more time than updating a table without (because
the indexes also need on update). So only create indexes on columns that will be
frequently searched against.
 Create Index Syntax
Creates an index on a table. Duplicate values are allowed:
Create Index index_name
On tablename(col_name1,col_name2…..);
Set auto trace on explain
 Create Unique Index Syntax
Creates a unique index on a table, Duplicate values are not allowed.
Create Unique index index_name
On table_name(col1,col2….);
NOTE:
The syntax for creating indexes varies among different database. Therefore check the syntax
for creating indexes in your database
 Create Index example
The SQL stmt below creates an index named ‘idx_lastname’ on the ‘lastname’ column
in the ‘persons’
Table:
Create Index 2
On emp(ename);
* If you want to create an index on a combination of columns, you can list the column
names within the parenthesis, separated by commas
Create Index 2
On emp(ename,job);
 In SQL view is a virtual table based on the result set of an sql
statement.
 Syntax:
Create view view_name
As
Select col_name
From table_name
Where<condition>;
Syntax 2
Drop view view_name
 NOTE:
To give permission to create view!!
Login as system
Connect
User: system
Pwd:Oracle1234(tiger)
Grant create view to Scott;(giving the permission)
Revoke create view from Scott;(tacking back permission)

More Related Content

Similar to SQL Basics and Fundamentals (20)

Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)
 
Procedures andcursors
Procedures andcursorsProcedures andcursors
Procedures andcursors
 
Les01
Les01Les01
Les01
 
lab14444444444444444444444444444444444444444
lab14444444444444444444444444444444444444444lab14444444444444444444444444444444444444444
lab14444444444444444444444444444444444444444
 
Oracle
OracleOracle
Oracle
 
Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standards
 
Chinabankppt
ChinabankpptChinabankppt
Chinabankppt
 
Dbms
DbmsDbms
Dbms
 
IDUG 2015 NA Data Movement Utilities final
IDUG 2015 NA Data Movement Utilities finalIDUG 2015 NA Data Movement Utilities final
IDUG 2015 NA Data Movement Utilities final
 
Mssql
MssqlMssql
Mssql
 
SQL- Introduction to MySQL
SQL- Introduction to MySQLSQL- Introduction to MySQL
SQL- Introduction to MySQL
 
SQL
SQLSQL
SQL
 
Oracle SQL, PL/SQL best practices
Oracle SQL, PL/SQL best practicesOracle SQL, PL/SQL best practices
Oracle SQL, PL/SQL best practices
 
122 sql for-beginners
122 sql for-beginners122 sql for-beginners
122 sql for-beginners
 
SQL for interview
SQL for interviewSQL for interview
SQL for interview
 
PostgreSQL Database Slides
PostgreSQL Database SlidesPostgreSQL Database Slides
PostgreSQL Database Slides
 
0808.pdf
0808.pdf0808.pdf
0808.pdf
 
0808.pdf
0808.pdf0808.pdf
0808.pdf
 
Introduction to mysql part 3
Introduction to mysql part 3Introduction to mysql part 3
Introduction to mysql part 3
 
01 basic orders
01   basic orders01   basic orders
01 basic orders
 

Recently uploaded

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 

Recently uploaded (20)

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 

SQL Basics and Fundamentals

  • 2.  Basics on Database  What is SQL  Features of SQL  History of SQL  SQL sub Languages  Data types & Constraints  SQL Operators 2  SQL Functions  SQL Clauses  Sub-Queries  Nested & Correlated Queries  Normalisation
  • 3. 3 Employee Salary Emp_Id Dept_no • It is a raw fact which describes the attributes of an entity Name Ram 15000 Mail 10 Entity Attributes Raw Fact
  • 4. • Data can be valid/Invalid depending upon the scenario on which the Data is being provided. • The collection of Data becomes information. • We will store only valid Data in the Database. • Simply just storing the Data is not important , how fast we can retrieve it when it is required to be used is also important 4
  • 5. • Database is medium to store the Data in an organised and systematic manner. • Every Database should have these following functionalities i. Insert the Data ii. Retrieve the Data iii. Modify the Data iv. Delete the Data • The DB user should be able to do all the above operations 5
  • 6. • DBMS is a software(set of programs) which is used to create,manage and manipulate the DB • The Data stored in the form of files(with different extensions) so we can’t establish the relationship between the Data. • It provides the security to the DB. • It provides authorization to the user • To communicate with the DBMS we use a language called Query language 6
  • 7. 1. SQL 2. My SQL 3. Mongo DB 4. SQL Server 5. Postgres 6. DB2 • A DBMS software may have any of the following models to store the data i. Relational Model ii. Network Model iii. Object Model iv. File/Document Model 7
  • 8. • A DBMS is a software which store the Data in a systematic manner by using relational Model such a DBMS is known as RDBMS. • According to the relational model the data must be stored in the form of Tables. •A Table is a logical structure consists of Rows and Columns and Cells. Here,  Rows are referred as Records/Tuple.  Columns are referred Attributes/Fields.  Table is referred as Object/Relation. 8
  • 9. • SQL – Structured Query Language • It is defined as, SQL is a query language which is used to communicate with DBMS • Communicate in the sense we can create,manage and manipulate DB by using Queries 9
  • 10. • IBM developed the 1st relational model based DBMS called System-R in 1970. • To interact with that they developed the language called SEQUEL. • Later it is assigned with ANSI standards and then its named as SQL • The current Owner of SQL is Oracle. • We are using Oracle 10g ,current version is 19c and the first version is 1i • The Father of SQL is Raymond Boyce. • Co-father is E.F Codd. 10
  • 11. • SQL is used to access the Data from RDBMS. • SQL can execute Queries against the DB. • SQL used to describe the Data in the DB and manipulate it when needed. • SQL is used to create and drop DB and Table. • SQL allows users to set permissions on tables, procedures and views. 11
  • 12. I. Clear Screen[ Cl Scr] : Which is used to clear the screen. II. SET lines: To adjust the no of characters to be in a line. III. SET pages: To adjust the no of lines to be in a page. IV. Connect user: To connect one user to another. V. Show user: To show the current user. VI. Desc: To describe the particular table. VII. Show recycle bin VIII. Desc recycle bin 12
  • 13. There are 5 types in it 1. Data Definition Language i. Create ii. Alter iii. Rename iv. Drop v. Truncate 2. Data Manipulation Language i. Insert ii. Update iii. Delete 13
  • 14. 3. Transaction Control Language i. Commit ii. Save point iii. Rollback 4. Data Control Language i. Grant ii. Revoke 5. Data Query Language i. Select 14
  • 15. DQL is used retrieve the data • SELECT statement is used to simply retrieve the Data from the DB. 15 Syntax, SELECT Col_name /Exp FROM Table_name; Example, SELECT * or FROM emp; SELECT ename FROM emp; Note: The SQL statements are case insensitive but the Table Data is Case sensitive; Note: * represents All the details
  • 16. 1. Display all the tables present in existing user Q . SELECT * From Tab; 2. Write a query to display all the employee’s manager number Q. SELECT mgr From emp; 3. WAQTD all the employees empno and commission Q. SELECT empno,comm From emp; 16
  • 17. • This statement is used to return only distinct(different) values. • Inside a table a column may often contains duplicate values and sometimes you only want to list the different(distinct) values then we will go for Distinct Statement. • It can accepts any no of arguments. Syntax, SELECT Distinct colm_name from emp; Example, 1 Q. Q. SELECT distinct ename from emp; SELECT distinct ename, job,deptno from emp;
  • 18. 1. Arithmetic Operator [+, - , * , /] 2. Concatination Operator [||] 3. Comparison Operators [ = , != or <>] 4. Relational Operators [ > , < , >= , <= ] 5. Logical Operators: AND , OR , NOT 6. Special Operators: IN , NOT IN , Like , Not Like , Between , Not Between , Is , Is Not 7. Sub-Query Operators: ALL , ANY , EXISTS , NOT EXISTS 8. Set Operators: UNION , UNION ALL , INTERSECT , MINUS. 17
  • 19. • Aliasing is the alternate name given to the column. • Aliasing is for user convenience(optional) Syntax, SELECT Col_name/Exp as alias_name From Table_name 18 Example, WAQTD salary as annual_sal from employee table SELECT Sal as annual_sal From emp; Q. Note:  we can’t use alias names in where clause  We can use in order by clause Note:  By giving space we can alias the column
  • 20. 19 • These operators are used to perform arithmetic Operations such as Addition, Substitution, Division and Multiplication. QUERIES: 1. WAQTD the total salary of the employee from the emp table SELECT sal+comm or From emp; SELECT sal+comm as total_sal From emp; 2. WAQTD all the employee’s annual salary from employee table SELECT sal*12 or From emp; SELECT sal*12 as annual_sal From emp; 3. WAQTD half yearly salary of all the employees from employee table SELECT sal*6 From emp;
  • 21. 4. WAQTD all the employee’s sal with 20% hike in the salary SELECT (sal+(sal*20/100)) From emp; 5. WAQTD employee’s total annual salary from emp table SELECT (sal*12)+comm as “annual salary” From emp; 6. WAQTD quarterly salary of employees from emp table 20 Note:  We can’t perform arithmetic operations for null values  WE can use ‘_’ or “ “ for multiple strings in select statement
  • 22. • Where clause is used to filter the records or This clause is used to display the records based on the condition 21 Syntax, SELECT col_name/Exp From table_name Where <Condition>; Example, WAQTD all the details of the employee who are working in dept 20 Q. SELECT * From emp Where deptno=20;
  • 23. • Concatenation operator is used to join the two or more strings by using 22 pipe operator. • We will get the result in sentences. QUERIES: 1. WAQTD Mr Smith your salary is 2000Rs SELECT ‘Mr ’||ename||’ your salary is ‘||sal||’ Rs’ From emp; 2. WAQTD Mr Scott your promoted from designation to Manager SELECT ‘Mr ’||ename||’ your promoted from ‘||job ||’ to ‘||’ Manager’ From emp; Note:  ||  Pipe Operator Note:  If want single output then we will use the DUAL table DUAL is a dummy table present in the DB. It is used for the purpose of calculation without using User table
  • 24. Comparison Operators are used when we have to return single record or output. • We have = , != or <> Example, 1 Q WAQTD names of the employees who are working as Salesman. SELECT ename from emp Where Job = ‘SALESMAN’; Q WAQTD employee no of employees who are not working under manager 7389. SELECT empno from emp Where mgr != 7389; OR Where mgr <> 7389;
  • 25. Relational Operators are used when we have to return Greater than , >= , less than , <= conditions in a single output. Example, 1 Q. WAQTD the names of employees who are getting salary more than 3000. SELECT ename from emp Where sal > 3000; Q WAQTD details of the employees who are working behind the dept 30 SELECT * from emp Where deptno <30;
  • 26. Example In the following expression multiplication has a higher precedence than addition, so Oracle first multiplies 2 by 3 and then adds the result to 1. 1+2*3 You can use parentheses in an expression to override operator precedence. Oracle evaluates expressions inside parentheses before evaluating those outside. 1 Operator Operation ( ) Parentheses *, / multiplication, division +, -, || addition, subtraction, concatenation =, !=, <, >, <=, >=, IS NULL, LIKE, BETWEEN, IN comparison NOT exponentiation, logical negation AND conjunction OR disjunction
  • 27. 1. OR, A B R 0 0 0 0 1 1 1 0 1 1 1 1 • OR Operator will return the records based on both the 1st condition. • If the 1st condition is false then only it will check the 2nd condition. • If the 1st condition is true then it won’t check the 2nd condition directly it will return the output. • If any one condition satisfies or If any one of the condition is true then it will display the output. Note:  0 = False  1 = True Syntax, SELECT col_name/exp From emp where (col_name/exp or col_name/exp); A B 23 A+B
  • 28. 2. AND, A B R 0 0 0 0 1 0 1 0 0 1 1 1 • AND Operator will return the records based on both the conditions. • If the 1st condition is true then also it will check the 2nd condition. • If both the conditions satisfies or If both the conditions are true then only it will display the output. Syntax, SELECT col_name/exp From emp where (col_name/exp and col_name/exp); A B A.B 24
  • 29. 1. WAQTD all the details of an employee whose mgr number is 7839 or 7566 SELECT * From emp Where mgr =7839 or mgr =7566; 2. WAQTD names of all the manager hired after April 81 SELECT ename From emp Where job=‘MANAGER’ and hiredate> ’30-APR-81’; 3. WAQTD name of the clerk if he works in dept 10 or 20 or 30 SELECT ename From emp Where deptno=10 or deptno=20 or deptno=30; 4. WAQTD all the details of the employees who is working as manager or clerk in dept 10/30 SELECT * From emp Where (job=‘MANAGER’ or Job=‘CLERK’) and (deptno=10 or deptno=30); 25
  • 30. 5. WAQTD details of the employees working as analyst hired after 1985 getting salary > 2500 but less than 4000. 6. WAQTD all the employee details who is working under dept 30. 7. WAQTD all the employee name whose manager number is 7698. 8. Display emp name and emp number who is getting salary 1600 and 1500. 9. Write AQTD all emp details who is getting salary > 1250 and < than 1600. 10. Display manager number for all emp working in dept number 10. 26
  • 31. 11. WAQTD all employees whose salary is 1600. 12. WAQTD empno,job of all the employees whose mgr no is 7698. 13. WAQTD all the employees who does not belongs to dept 20. 14. WAQTD all employees who are working in dept 20 or job is manager. 15. WAQTD all the employees whose mgr no is 7839 or job is select. 16. Display all the employees whose comm is<=100 and job is salesman. 17. WAQTD all the employees whose mgr is 7698 and joined from 20-FEB-81. 18. WAQTD the employees who doesn’t belongs to dept 20 and getting some comm. 19. WAQTD the employees working in dept 10 or 20 and job is manager or salesman. 20. WAQTD the employees whose mgr is either 7698 or 7839 or job is manager or joined from 20-SEP-81. 27
  • 32. 1. IN Operator : In operator is a multi-valued operator which can accept single value at LHS and multiple values at RHS . Example; To select a manager working in either of deptno 10 or 20 or 30 • Instead of using comparison operator we can use IN operator here, SELECT * From emp Where job=‘MANAGER’ and deptno IN(10,20,30); • IN operator works similar to OR operator. • IN operator is generally preferred when we have multiple conditions with respect to LHS 28
  • 33. 2. NOT IN Operator : It is an operator which accept multiple values or single values in RHS to filter the records with respect to LHS Syntax, 29 WHERE col_name NOT IN(V1, V2, V3); Example, 1. WAQTD the names of the employees who are not working in dept 20 and dept 10 SELECT ename From emp Where deptno not in(10,20); 2. WAQTD names of the employees except smith from table emp SELECT ename From emp Where ename not in(‘SMITH’);
  • 34. 3. Between Operator is used whenever we have range of values (Lower range and Higher range) • Between Operator works including the ranges. • Interchange of lower and higher range is not possible Syntax, Where colm_name/exp between(L_range and U_range); 30 Example, WAQTD name,deptno of employees whose salary is in the range of 800 and 3000 SELECT ename,deptno From emp Where Sal between 800 and 3000;
  • 35. 4. Not between Operator is used whenever we have a range of values and this operator works excluding the ranges Syntax, Where colm_name/exp not between(L_range and H_range); 31 Example, WAQTD name,deptno of employees whose salary is in the range of 800 and 3000 SELECT ename,deptno From emp Where Sal between 800 and 3000;
  • 36. 5. IS Operator is used to check whether the values present at the LHS is null or not. • This Operator is only used to check the null values. Syntax, Where Colm_name/exp is null; 32 Example, WAQTD the details of employees who are not getting any commission from table emp SELECT * From emp Where comm Is null;
  • 37. 6. IS NOT Operator is used to verify the value present in the LHS is not null Syntax, Where Colm_name/exp Is not null; 33 Example, WAQTD the name of the employees who are getting some commission SELECT ename From emp Where comm is not null;
  • 38. 7. LIKE Operator is used to perform pattern matching or Wild card searching. Syntax, Where colm_name/exp Like ‘Pattern’; 34 • If we want to specify multiple pattern then we should specify like operator multiple times • The pattern is case sensitive and it should be in the form of regular expression • Regular expression is noting but combination of ordinary characters and meta characters ( % , _ ) • Meta characters are also called Wildcards • Percentile(%) can take any no of memory • Underscore(_) can take exactly one value
  • 39. Example, • Name starting with S  ‘ S% ’ • Name ending with S  ‘%S’ • S having anywhere in the name  ‘%S%’ • Name starts with J ends with S  ‘J%S’ • Name has A in the second space  ‘ _A%’ • Name has A in the second last space  ‘%A_’ • A name has 4 characters  ‘ ’ Note: Not like Operator works opposite to the Like Operator Syntax, Where colm_name/exp not like ‘Pattern’; 35 Note: Like operator is also called as wild card operator
  • 40. 1. WAQTD Name of the employee if his name consists of character A and ends with S SELECT ename From emp Where ename like ‘ %A%S ’; 2. WAQTD name and salary of an emp who gets 3 digits salary SELECT ename and sal From emp Where Sal like ‘ ’; 3. WAQTD total salary needed to pay employees hired in FEB SELECT sal+comm From emp Where hiredate like ‘%FEB%’; 4. WAQTD the employees who joined company in the year 1987 SELECT * From emp 36
  • 41. • Functions are defined as the set of instructions or block of codes which are used to perform particular task • Functions consists of 3 major components 1. Function name 2. No of arguments 3. Return type • There are two types of functions such as 1. Single row Functions : SRF can take one input ,process and generates results for the single input. If we pass n no of inputs for a SRF we will get n no of outputs. 2. Multi row Functions : MRF will aggregate or combine all the inputs and generates single output If we pass n no of inputs we will get a single output 37
  • 42. • SRF can take one input ,process and generates results for the single input. • If we pass n no of inputs for a SRF we will get n no of outputs. • SRF can take one or more arguments as input. • We can use any number of SRF( ) in Select Clause.  SRF mainly have 5 types functions in it 1. Case Manipulation Functions 2. Character Manipulation Functions 3. General Functions 4. Number Functions 5. Date Functions 38
  • 43. Case Manipulation function will takes a string value as an argument and returns a string There are 3 types of functions in it i. UPPER( ) ii. LOWER( ) iii. INITCAP( ) 1. UPPER( ) : It takes string as an argument and converts it into upper case Eg, SELECT Upper(‘smith’) from dual; 2. LOWER( ) : It takes string as an argument and converts it into lower case Eg, SELECT Lower(‘SMITH’) from dual; 3. INITCAP( ) : It takes string as an argument and converts the initial alphabets into Upper case Eg, SELECT Initcap(‘smith’) from dual; 39
  • 44. 1. Concat( ) 2. Length( ) 3. Substr( ) 4. Instr( ) 5. Replace( ) 1. CONCAT( ): • This function add two or more strings/expressions together. • It takes exactly two parameters as an argument. 41 Syntax, SELECT Concat( Exp1,Exp2 ) from table_name; Example, SELECT Concat( Ename, ‘is a clerk’) from emp; Parameters Description Exp1 , Exp2 Required, The expression to add together
  • 45. 2. LENGTH( ): • This functions returns the length of a string(in a Bytes). • It takes exactly one parameter as an argument. 42 Parameter Description Exp1 Required, the string to count the length for Syntax, SELECT Length(exp1) from table_name; Example, Q. Q. SELECT sal,length( sal) from emp; SELECT sal,length(sal) from emp Where length(sal)=3;
  • 46. Parameter Description Exp 1 Required, The string to extract from Exp 2 Required, The string position can be both +ve or -ve Exp 3 Optional, The no of characters to extract Syntax, SELECT substr(exp1,exp2,exp3) from table_name; Example, Q. Q. SELECT substr(‘Jspiders’,2,7) from dual; SELECT substr(‘Jspiders’,-2,7) from dual; 3. SUBSTR( ): • This function extracts a substring from a string(sorting at any position) • It takes 3 parameters as an arguments(1 optional pmtr) Note: Positions of String (-1, -2 -3 ,-4,-5, -6, -7,-8) (J , S , P , I , D , E , R , S) ( 1 , 2 ,3 , 4 ,5 , 6 , 7 , 8) Note: The optional string can’t be -ve 43
  • 47. 4. INSTR( ): • It returns the position of the first occurrence of a string in another string • It takes exactly 2 values as an arguments. 44 Parameter Description Exp1 Required, The string that will be searched Exp2 Required, The string to search in string1 Note:  It returns ‘0’ if string is not found Note:  Exp2 is Case sensitive Syntax, SELECT instr(exp1,exp2) from dual; Example, Q. Q. Q. SELECT instr(‘Jspiders’ , ’s’) from dual; SELECT instr(‘Jspiders’ , ‘S’) from dual; SELECT instr(‘Jspiders’ , ‘sp’) from dual
  • 48. 5. REPLACE( ): • It replaces all the occurrence of the substring within a sting with new string. • It takes maximum of 3 parameters as arguments. 45 Parameters Description Exp1 Required, The original string Exp2 Required, The substring to be replaced Exp3 Required, The new replacement substring Note:  Exp 2 is Case sensitive Syntax, SELECT Replace(exp1,exp2,exp3) from dual; Example, SELECT Replace(‘SALESMAN’, ‘SALES’, ‘SUPER’) from dual;
  • 49. 1. MOD( ) 2. POWER( ) 3. SQRT( ) 4. ROUND( ) 5. TRUNC( ) 1. MOD( ): • This function is used to obtain the modulus of the input(%) • It will always returns the reminder values of a no divided by another no. • It takes exactly 2 numbers as an argument. Syntax, SELECT mod(no1,no2) from table_name; Example, 46 Q. Q. SELECT mod(20,3) from dual; SELECT mod(2,4) from dual;
  • 50. 2. POWER( ): • It returns the value of a no is raised to the power of another value. • It takes exactly 2 values as an argument. Syntax, SELECT power(a , b) from table_name; 47 Example, SELECT power(2,4) from dual; Parameter Description No 1 Required, A number(Base) No 2 Required, A number(Exponent)
  • 51. 3. SQTR( ): • SQRT functions returns the square root of the number or char. • It accepts exactly one value as an argument. Syntax, SELECT sqrt( no ) from table_name; 48 Parameter Description No1 Required, A no to calculate the square root of, must be > 0 Example, SELECT sqrt(64) from dual;
  • 52. 4. ROUND( ): • Round function will rounds a number to specified no of decimal places. • It will accept either 1 or 2 values as an argument. Syntax, SELECT round(no1,no2) from table_name; 49 Example, Q. Q. SELECT round(23.333) from dual; SELECT round(23.333,1) from dual; Parameter Description No Required, The no to be rounded Decimals Optional, No of decimal places to round the number Note:  Rounds to the nearest whole no
  • 53. 5. TRUNC( ): • It truncates the no to specified decimal places. • It will accept either 1 or 2 values as an argument. Syntax, SELECT trunc( no1 , no2 ) from table_name; 50 Example, Q. Q. Q. SELECT trunc (23.777) from dual; SELECT trunc (23.44) from dual; SELECT trunc (23.45454,2) from dual; Parameter Description No Required, The no to be truncated Decimal Optional, The no of decimal places to be truncated
  • 54. 1. NVL( ) 2. NVL2( ) 1. NVL( ): • NVL accepts 2 parameters as arguments. If exp1 evaluates null, then nvl( ) returns exp2.If exp1 is not null then it will return exp1. 51 Syntax, SELECT nvl (exp1 , exp2) from table_name; Example, Q. Q. Q. SELECT nvl (null , 2) from dual; SELECT nvl (2 , 2) from dual; SELECT nvl( comm , 0) from emp; Note: Expressions are of same or different data types
  • 55. 2. NVL2( ): • It accepts 3 parameters as arguments. If exp1 is null nvl( ) returns exp3, if exp 1 is not null it will return exp2. Syntax, SELECT nvl2 (exp1 , exp2 , exp3) from table_name; Example, 52 Q. Q. SELECT nvl2 (null , 1, 2) from dual; SELECT nvl2( comm , 40, 0) from emp;
  • 56. • MRF( ) will aggregate or combine all the inputs and generates single output. • If we pass n no of inputs we will get a single output. • MRF( ) will ignore the null values. • We cannot write MRF( ) in where clause and group clause • In select Clause we cant use any other column name or expression with MRF( ). •We can use any no of MRF( ) in Select Clause. Types of MRF( ) functions: 53 1. MAX( ) 2. MIN( ) 3. COUNT( ) 4. SUM( ) 5. AVG( ) Note: MRF( ) accepts only single value as an argument, which is colm_name/exp
  • 57. 1. MAX( ): • This function used to obtain the maximum value from a column. Syntax, SELECT max(Colm_name/exp) from table_name; Example, Q. WAQTD the maximum salary of employee from table emp SELECT Max(sal) from emp; 2. MIN( ): • This function used to obtain the minimum value from a column. Syntax, SELECT min( colm_name/exp) from table_name; Example, Q. WAQTD the min(sal) from emp; 54
  • 58. 3. SUM( ): • This function is used to obtain the summation of all the values present in a column. Syntax, SELECT sum(Colm_name/exp) from table_name; Example, Q. WAQTD total salary needed to pay employees hired in FEB SELECT sum(sal) From emp where hiredate like ‘%FEB%’; 55
  • 59. 56 4. AVG( ): • It used to obtain the average of all the values present in a column. Syntax, SELECT avg(Colm_name/exp) from table_name; Example, Q. WAQTD average salary needed to pay all the employees SELECT avg(sal) from emp; 5. COUNT( ): • This function is used to count the no of records present in the table. Syntax, SELECT */colm_name/exp from table name; Example, Q. WAQTD the no of employees getting salary less than 2000 in dept no 10 SELECT * From emp where sal<2000 and deptno=10;
  • 60. 1. WAQTD total salary needed to pay employees working as Clark. SELECT sum(sal) From emp Where ename =‘CLARK’ 2. WAQTD no of employees having A as there first character. SELECT count(*) From emp Where ename like ‘A%’; 3. WAQTD no of employees working as Clerk or Manager. SELECT count(*) From emp Where job= ‘CLARK’ or job= ‘MANAGER’; 4. WAQTD no of employees reporting to 7839 mgr. SELECT count(*)
  • 61. 5. WAQTD no of employees earning commission in deptno 20 from emp SELECT count(*) From emp Where comm is not null and deptno=20 6. WAQTD avg salary,total salary,no of employees and maximum salary of the employees who are working as president. 7. WAQTD the no of employees who are having A in their names. 8. WAQTD the no of employees and total salary needed to pay the employees who have two consecutive Ls in their name 9. WAQTD no of departments present in employee table
  • 62. • A Query written inside another query known as sub query. Working principle: Outer Query Result Inner Query O/p I/p
  • 63. • The inner query executes first. • The output of the inner query is given as input to the outer query. • Taking the input the outer query executes completely generating a result. • Therefore we can say that the outer query is dependent on inner query. A. CASE 1 Whenever we have unknown values we go for sub-query. Example, Q. WAQTD name of the employees who are earning more than smith. SELECT ename From emp Where sal > (SELECT sal From emp Where ename=‘SMITH’;) Note: The datatype on the conditions must be exactly same , irrespective of columns Mgr = Number(4) Empno =Number(4)
  • 64. In above query salary of smith is unknown, therefore we wrote a sub-query to find the unknown. Example, Q. WAQTD all the details of employees having same designation as Ward SELECT * From emp Where job in(select job from emp Where ename=‘WARD’; Q. WAQTD name and salary of the employees earning less than jones SELECT sal,ename From emp Where sal<(select sal from emp where ename=‘JONES’;)
  • 65. B. CASE 2 Whenever the data to be selected belongs to two different tables. Example, Q WAQTD loc of the employees who are getting salary greater than 3000 SELECT loc From dept Where deptno in (select deptno from emp Where sal>3000;) Q. WAQTD dept name of jones SELECT dname From dept Where deptno in (select deptno From emp Where ename=‘JONES’;)
  • 66. 1. wAQTD name of the employees who are working in the same dept as Turner. 2. WAQTD name and sal of the employees earning less than Jones. 3. WAQTD all the details of the employees working in the same designation as James. 4. WAQTD no of the employees working for King. 5. WAQTD name and hiredate of employees who are getting sal more than Smith but less than Clark. 6. WAQTD no of employees who are hired after Martin and getting salary less than King. 7. WAQTD name and job of the employee who earn comm and get salary less than Scott. 8. WAQTD dept name Adams. 9. WAQTD location in which Smith works. 10. WAQTD name and dept of the employees who works in accounting dept. 11. WAQTD name and deptno of the employees who earn more than Ward and work in Research. 12. WAQTD no of employees working in Boston. 13. WAQTD name and salary of the employees who are working as Clerk in Chicago. 14. WAQTD all the details of the employees who are earning less than King and working in Smith’s dept. 15. WAQTD all the details of the employees who are working as manager in new york. 16. WAQTD name of the employees working the same job as Scott , getting salary more than Adams and working in dept in which Martin works.
  • 67. 1. Single Row Sub-Query. 2. Multi Row Sub-Query. 1. Single Row Sub-Query: • If the sub-query returns exactly one record then it is referred as SRSQ. • If it returns one record, we can use normal operators , such as = , != or <> , >= , <= , < , >. Example, Q. WAQTD names of employees who are getting comm more than James. SELECT ename From emp Where comm > (select comm from emp Where ename= ‘JAMES’);
  • 68. 2. Multi Row Sub-Query: • If the sub-query returns more than one record then it is called MRSQ. • When it returns more than 1 records we can’t use normal operators instead we use special operators or sub-query operators such as ALL , ANY. Q. WAQTD the name of employee whose manager works in new york. SELECT ename From emp Where mgr in(select empno from emp Where deptno in (select deptno from emp Where loc= ‘NEWYORK’));
  • 69. • When we write more than one sub-query , then it is called nested sub-query. • We can nest up to 225 sub-queries at the max. Example, Q. WAQTD 2nd minimum salary. SELECT min(sal) From emp Where sal in(select min(sal) from emp Where sal>(select min(sal) from emp));
  • 70. A SQL Join statement is used to combine data or rows from two or more tables based on a common field between them. Different types of Joins are: 1. INNER JOIN 2. LEFT JOIN 3. RIGHT JOIN 4. FULL JOIN 5. SELF JOIN 6. CARTISION JOIN 7. EQUI JOIN Outer Joins
  • 71. Note: We can also write JOIN instead of INNER JOIN. JOIN is same as INNER JOIN. The simplest Join is INNER JOIN. 1. INNER JOIN: The INNER JOIN keyword selects all rows from both the tables as long as the condition satisfies. This keyword will create the result-set by combining all rows from both the tables where the condition satisfies i.e. value of the common field will be same. Syntax, SELECT table1.column1,table1.column2,table2.column1,… FROM table1 INNER JOIN table2 ON table1.matching_column = table2.matching_column; table1: First table. table2: Second table matching_column: Column common to both the tables.
  • 72. SELECT table1.column1,table1.column2,table2.column1,.... FROM table1 LEFT JOIN table2 ON table1.matching_column = table2.matching_column; table1: First table. table2: Second table matching_column: Column common to both the tables. 2. LEFT JOIN: This join returns all the rows of the table on the left side of the join and matching rows for the table on the right side of join. The rows for which there is no matching row on right side, the result-set will contain null. LEFT JOIN is also known as LEFT OUTER JOIN. Syntax, Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are same.
  • 73. Syntax, SELECT table1.column1,table1.column2,table2.column1,.... FROM table1 RIGHT JOIN table2 ON table1.matching_column = table2.matching_column; table1: First table. table2: Second table. matching_column: Column common to both the tables. 3. RIGHT JOIN: RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of the table on the right side of the join and matching rows for the table on the left side of join. The rows for which there is no matching row on left side, the result-set will contain null.  RIGHT JOIN is also known as RIGHT OUTER JOIN. Note: We can also use RIGHT OUTER JOIN instead of RIGHT JOIN, both are same.
  • 74. 4. FULL JOIN: FULL JOIN creates the result-set by combining result of both LEFT JOIN and RIGHT JOIN. The result-set will contain all the rows from both the tables. The rows for which there is no matching, the result-set will contain NULL values. Syntax, SELECT table1.column1,table1.column2,table2.column1,.. FROM table1 FULL JOIN table2 ON table1.matching_column = table2.matching_column; table1: First table. table2: Second table matching_column: Column common to both the tables.
  • 75. Q. WAQTD all the details of the employees from both the tables. SELECT * From emp inner join dept On emp.deptno= dept.deptno Q. WAQTD employee name,sal,deptno,dept name for all employees. 1. WAQTD employee name and his department name for all the employees. 2. WAQTD name of the emp along with his location for all the employees. 3. WAQTD name of employee and his department name if the employee work as salesman. 4. WAQTD name and Dname of all the employees working for accounting dept. 5. WAQTD salary and Dname for all the employee. 6. WAQTD Dname and annual salary for emp who earn more than 2450. 90
  • 76. 7. WAQTD Dname and hiredate of all employees who were hired during 81. 8. WAQTD all the details of employee and his department if he works in chicago or new york 9. WAQTD name and Dname for the employees if the name of emp’s , job and his Dname starts with same char ‘s’. 10. WAQTD name and Dname and the location for emp’s if emp’s location is dallas and employees has to working as manager. 11. WAQTD Dname and commission for all the employees who earn commission. 12. WAQTD Dname and salary and sal with 25% hike if the employee salary is less than 2500 and works as clerk in new york. 13. WAQTD Ename and Dname for all the employees if they are working as manager or clerk in accounting or research dept with sal more than joins. 14. WAQTD Dname and avg sal for each dept . 15. WAQTD employee name and department name if the employee gets max salary. 16. WAQTD name of the employee and department name if employees names and department name first character is ‘A’ or’ S’ and employee should be earning more than ‘Smith’ and also he has to be hired before the last employee and he may or might be reporting to king or jones. 17. WAQTD employee name and department name if employee is working in same location as his manager 90
  • 77. 91 5. SELF JOIN: As the name signifies, in SELF JOIN a table is joined to itself. That is, each row of the table is joined with itself and all other rows depending on some conditions. In other words we can say that it is a join between two copies of the same table. Syntax, SELECT table 1.coulmn1 , table2.column2 FROM table 1, JOIN table 2, ON some_condition; Table 1: first table Table 2: second table some_condition: Condition for selecting the rows. CONTACT: 7760200900 HR: 7022889639
  • 78. 92 Example, Q. WAQTD the employee names along with their manager names. SELECT emp.ename,man.ename mname From emp join emp man where emp.mgr= man.empno; Q. WAQTD all the details of employees where sal greater than his manager salary. SELECT * From emp join emp man on emp.mgr=man.empno where emp.sal> man.sal; CONTACT: 7760200900 HR: 7022889639
  • 79. 1. WAQTD employees name, his manager name and employee salary and his manager salary 2. WAQTD the employees name, his manager name, manager’s manager name, mgr’s mgr’s mgr’s name. 3. WAQTD name of the employee and his managers name if employee is working as Clerk 4. WAQTD name of the employee and managers salary if employee and manager both earn more than 2300 5. WAQTD employee name and managers hiredate if emp was hired before 1982 6. WAQTD employee name and manager comm if employee works as salesman and manager works in dept 30. 7. WAQTD employee name and manager name and their salaries if employee earns more than manager. 8. WAQTD employee name and hiredate , manager name and hiredate if manager was hired before employee. 9. WAQTD employee and manager name if both are working in same job. 10. WAQTD employee name and manager name if manager is working as actual manager. CONTACT: 7760200900 HR: 7022889639 93
  • 80.  CASE 1:TO FIND MANAGER NAME Example: WAQTD name of SMITH's manager . SELECT ENAME FROM EMP WHERE EMPNO = ( SELECT MGR FROM EMP WHERE ENAME ='SMITH') ; WAQTD Location of Adams's manager's manager . SELECT LOC FROM DEPT WHERE DEPTNO = ( SELECT DEPTNO FROM EMP WHERE EID = ( SELECT MGR FROM EMP WHERE EID = ( SELECT MGR FROM EMP WHERE ENAME ='ADAMS' ) ) ) ;
  • 81.  CASE 2:TO FIND EMPLOYEE NAME Ex: WAQTD Name and salary given to the employees reporting To James . SELECT ENAME , SAL FROM EMP WHERE MGR = ( SELECT EID FROM EMP WHERE ENAME ='JAMES' ) ; WAQTD dname of the employee reporting to President . SELECT DNAME FROM DEPT WHERE DEPTNO = ( SELECT DEPTNO FROM EMP WHERE MGR = ( SELECT EID FROM EMP WHERE JOB ='PRESIDENT' ) ) ;
  • 82. 1.WAQTD smiths reporting manager's name 2.WAQTD Adams manager's manager name 3.WAQTD dname of Jones manager 4.WAQTD miller's manager's salary 5.WAQTD loc of smith's manager's manager. 6.WAQTD name of the employees reporting to Blake 7.WAQTD number of employees reporting to king 8.WAQTD details of the employees reporting to Jones 9.WAQTD enames of the employees reporting to Blake's manager 10.WAQTD number of employees reporting to ford's manager
  • 83.  "A query written inside another query such that the outer query and the inner query are Dependent on each other , this is known as Co-Related Sub-Query". Outer Query Inner Query o/p (partially) i/p o/p i/p Result Inter- dependent
  • 84.  Let us consider two queries inner and outer query respectively , 1.Outer query executes first but partially 2.The partially executed output is given as an input to the inner Query 3.The inner query executes completely and generates an output 4.The output of inner query is fed as an input to the Outer query and Outer Query produces the result . 5.Therefore, we can state that the outer query and the inner query both are INTERDEPENDENT ( dependent on each other ) . NOTE:  In co-related sub query a Join condition is a must , And must be written only in the Inner Query.  Co-Related sub query works with the principles of both SUB QUERY & JOINS .
  • 85. SUB QUERY CO-RELATED SUBQUERY Inner query executes first Outer query executes first Outer query is dependent on inner query Both are interdependent Join condition not mandatory Join condition is mandatory and must be written in inner query Outer query executes Once Outer query executesTwice .
  • 86. • Pseudo column is an imaginary column, behaves like a table column. But it is not actually stored in the table. • We can select these columns but we can’t manipulate(Insert, Update , Delete) their values Types of 1. Rownum 2. Rowid 1. ROWNUM: •Rownum is a serial number that is assigned to the result table. • Rownum is assigned at the time of execution. • Rownum is always starts with 1. • Rownum is dynamic. Syntax, SELECT Rownum from table_name;
  • 87. 2. ROWID: • For each row in the database, the Rowid returns the address of the row • By using Rowid we can fetch the records • Rowid is a 18 digit address of the records in the memory • Rowid is generated at the time of inserting the record • Rowid is unique and cannot be deleted • Rowid is static(cannot be changed) • It also be used to delete the duplicate records . • They are the fastest way to access a single row. • They can show you how the rows in a table are stored. • If you delete a row, then Oracle may reassign its Rowid to a new row inserted later.
  • 88. Syntax, SELECT Rowid from table_name; Example, Q. SELECT Rowid from emp; Q. SELECT ename From emp Where Rowid=Rowid;
  • 89. • Group by Clause is used to group the records(based on the certain attributes). • Group by clause executes ‘Row by Row’. • For group by class we can pass colm_name as argument. • After the execution of group by clause we get result in groups. • Any clause executes after group by clause will execute group by group. • We can pass colm_name which is used in group by clause with MRF() in select Clause • We can use group by clause in a query even without using where clause. Syntax, SELECT colm_name/exp From table_name Where <Condition> Group by colm_name/exp; Note:  Multiple arguments can be passed to group by class
  • 90. Order of execution: 1. From 2. Where Clause( if used ) 3. Group by Clause 4. Select Nature Of Execution: 1. From 2. Where( row by row ) 3. Group by ( row by row ) 4. Select( group by group)
  • 91. 1. WAQTD average salary given to each department except for department 30 SELECT avg(sal),deptno From emp Where deptno !=30 Group by deptno; 2. WAQTD number of emp working in each department except president . SELECT count(*) From emp where job != ‘PRESIDENT’ group by deptno;
  • 92. 3. WAQTD total salary needed to pay to all the employee in each job . 4. WAQTD no of employees working as manager in each dept 5. WAQTD avg salary needed to pay all the employees in each dept excluding the employees in deptno 20. 6. WAQTD no of employees having character A in their names each job. 7. WAQTD no of employees and avg salary needed to pay the employees whose sal is greater than 2000 in each dept. 8. WAQTD total salary needed to pay and no of salesman in each job. 9. WAQTD no of employees with their maximum salary in each job. 10. WAQTD maximum salaries given to an employee working in each dept. 11. WAQTD no of times the salaries have been repeated in employee table. 12. WAQTD no of employees hired on the same day into the same dept. 13. WAQTD no of employees getting the same salary in same department.
  • 93. • Having clause is used to filter the groups. • It will execute group by group • Since having clause executes after group by clause we can write MRF( ) in it as a condition. • IN having clause we can use the exp used in group by clause Syntax, SELECT colm_name/exp From emp Where< condition > Group by colm_name/exp Having < group filter condition >;
  • 94. Order of execution: 1. From 2. Where Clause( if used ) 3. Group by Clause 4. Select Nature Of Execution: 1. From 2. Where( row by row ) 3. Group by ( row by row ) 4. Having clause(group by group) 5. Select( group by group)
  • 95. 1. WAQTD at least 4 employees working in each dept except president. SELECT count(*),deptno From emp Where job!='PRESIDENT' Group by deptno Having count(*) >=4; 2. WAQTD total salary needed to pay all the employee in each job if the total salary of each job exceeds 3450 select sum(sal),job from emp group by job having sum(sal )>3450;
  • 96. 3. WAQTD no of employee working as manager in each dept if their average salary is less than 2300. 4. WAQTD avg salary needed to pay all the employees in each dept excluding the emp of dept no 20.If there are at least 3 employees working in each dept. 5. WAQTD no of employees having character A in their names in each job if count of employees is equal to 2. 6. WAQTD no of employees if more than 3 and avg salary needed to pay the employees whose salary is greater than 2000 in each dept. 7. WAQTD deptno in which there are at least 4 salesman in each dept. 8. WAQTD no of emp if more than 2 with their maximum salaries in each job. 9. WAQTD maximum salary given to an employee working in each dept if max salary is >1999. 10. WAQTD the salaries which are repeated or duplicate. 11. WAQTD the hiredate which appear more than one in the employee table. 12. WAQTD the hiredate and deptno if employees hired on the same day into the same dept. 13. WAQTD the salary and deptno if employees getting the same salary in the same dept.
  • 97. • Order by clause is used to order the returned output into ascending or descending. • By default Order by clause is in ascending order. • order by clause should be written as the last clause in the query. • order by clause executes after select clause. • In order by clause we can write multiple column names. • First priority is given to that column name which written 1st in the query. Syntax, 5. 1. 2. 3. 4. 6. SELECT colm_name/ exp From emp Where< condition > Group by colm_name/exp Having < group filter condition >; Order by colm_name asc/desc
  • 98. • SQL Data type is an attribute that specifies the type of data of any object. • Every table has a column, which has a column name , every column stores the data which has a data type. • We have to assign every column with the data type while declaring a column with column name. Types of Data types: 1. Char 2. Varchar 3. Number 4. Date 5. LOB: 1.CLOB: character LOB 2.BLOB: Binary LOB
  • 99. 1. CHAR data type: • If a column is assigned with char data type it can store following values. • The maximum no of characters that should be stored in a column can be specified using size. • In char we can store a character string with the size from 1 to 2000 bytes 0 to 9 a to b A to B Special char • Size(default) of the data type is 1 • Char is a fixed length memory allocation. • We can specify the size for the data type. Eg, char(2) , char(10) Note:  A column can have maximum of one data type  Each an every column should be assigned with data types
  • 100. 2. VARCHAR data types: • If a column is assigned with varchar data type it can store following values. 0 a A to 9 to b to B Special char • BY assigning varchar we can store 1 to 2000 bytes • By assigning varchar2 we can store 1 to 4000 bytes in a column.(prefer this) • Varchar is dynamic/variable length memory allocation. • It wont allocate the memory for null values.
  • 101. 4. DATE data type: • If a column is assigned with date data type, then it can store only Dates. • There is no size for date data types. • In Oracle, Date follows a default format i.e. DD-MON-YY & DD-MON-YYYY
  • 102. 3. NUMBER data type: • If a column assigned with number data type, then it can store only numbers. • The column can store only positive values • Number data type takes two arguments (precision , Scale), Precision is the mandatory argument and scale is optional argument. • If we want to store the decimal values then we need scale argument. • Scale should be less than precision Eg, Number 1234.56 This no is having precision of 6 and scale of 2 Note:  Precision is the no of digits in a no.  Scale is the no of decimals in a no.
  • 103. DML is used to manipulate the records of the table. CONTACT: 7760200900 HR: 7022889639 94 1. INSERT: Insert is used to add/insert records into the table. Syntax, Insert into table_name values(v1,v2,v3,…………); Insert into table_name(colm1,colm2,colm3,…….) values(v1,v2,v3,……..); Insert into table_name values(&colm1,&colm2,&colm3,…………); The above syntax is used to insert multiple records @ a time Example, insert into emp values(1264,Basya,painter,……..); insert into emp(empno, ename, job…..) values(1264,Disha,Actress…..); Note:  DML commands are not permanent.  Primary key is must and it should be unique.
  • 104. 95 2. UPDATE: Update is used to update the existing records of the table with new data. Syntax, Update table_name Set colm_name=Value Where condition; Update table_name Set colm_name= Vlaue,colm_name= Value,…….. Where condition; The above syntax is used to update multiple values @ a time. Example, Update emp Set ename=‘BASYA’ Where ename=‘SMITH’;
  • 105. 96 3. DELETE: Delete command is used to delete or remove records from the table. Syntax, DELETE from table_name Where condition; Example, Delete from emp Where ename=‘ALLEN’;
  • 106. TCL: Any activity performed on the data base is a transaction. So to control the transactions performed on the data base we use TCL commands. 1. COMMIT: Commit is used to complete the transaction. BY using commit we can make DML changes permanent. 2. ROLLBACK: This command takes us to the previous transaction Rollback vanishes all the transactions or DML changes. If commit command passed after transaction then the changes are permanent and rollback command wont work. 3. SAVEPOINT: Save point command is used to create multiple Save points. Consider many transactions done to the table here there and in between we have created save points , save points like a, b, c if we roll back to save point b , then what ever changes happened from save point b all the changes will be vanished . The changes before save point ‘b’ are unchanged. CONTACT: 7760200900 HR: 7022889639 97
  • 107. 4. DATA INTIGRITY: Checking the accuracy of the data is called data intigrity. • Using data intigrity we can ensure that only valid data stored in the DB. How to achieve data intigrity? It can be achieved by assigning columns with the data types and constraints CONSTRAINTS: Constraints are the rules of validation that are assigned on a column. A column can be assigned with two or more constraints. •Constraints are optional but they are highly recommended. Types of Constraints: 1. Null 2. Not Null 3. Unique 4. Check 5. Primary key 6. Foreign key CONTACT: 7760200900 HR: 7022889639 98
  • 108. 1. NULL: • Empty cells in table is called null • Null is neither space nor zero. • Null doesn’t allocate any memory. • If we perform any arithmetic operation with null than the result is null Eg, Null+1= Null 2. NOT NULL: • If a column is assigned with not null constraints then the cell value cannot be empty @ any point of time. It can’t be store null values. AB BB AC BC AB BB BC AB BA BB HR: 7022889639 99
  • 109. 3. UNIQUE: • If a column is assigned with unique constraint it cannot store duplicate values or It store only the distinct values. AB BA BC BB AB AB BC BB CONTACT: 7760200900 HR: 7022889639 100
  • 110. 4. CHECK: The CHECK constraint is used to limit the value range that can be placed in a column. If you define a CHECK constraint on a single column it allows only certain values for this column. SQL CHECK on CREATE TABLE: The following SQL creates a CHECK constraint on the "Age" column when the "Persons" table is created. The CHECK constraint ensures that the age of a person must be 18, or older: SQL: CREATE TABLE Persons ( ID number NOT NULL, Last Name varchar2(25) NOT NULL, First Name varchar2(25), Age number, CHECK (Age>=18) CONTACT: 7760200900 HR: 7022889639 101
  • 111. 5. PRIMARY KEY: • If a column is declared as primary key then the records can be identified uniquely. • Primary key is a combination of unique and not null constraints. • A table can have only one key. • A table consisting of PK is called as parent table or master table. CANDIDATE KEY: • The columns which are assigned with unique and not null constraints and they can qualify as a primary key. ALTERNATE KEY: • The columns which are eligible to become primary keys but not declared as PK. CONTACT: 7760200900 HR: 7022889639 102
  • 112. 6. FOREIGN KEY: • FK is used to establish the relationship between the tables. • FK column can accept null and duplicate values. • In order to declare a column as FK that column should be declared as PK in the other table. • A table consisting of foreign key is called as child table. • FK is also called as referential integrity constraints. • A table can have more than one FK.
  • 113. 1. CREATE: • CREATE statement is used to create Objects in DB. Syntax, CREATE table table_name (colm_name Data type(size) Constraints, colm_name Data type(size) Constraints,……..); To create duplicate tables: Syntax, CREATE table table_name as (SELECT * from reference table_name) Note: DDL statements are permanent.
  • 114. CONTACT: 7760200900 HR: 7022889639 105 2. RENAME: • Rename is used to rename the tables or columns. Syntax, Rename Old table_name to New table_name; Example, Rename emp to employee; 3. TRUNCATE: • Truncate is used to delete or remove all the records from the table at one shot. • Truncate makes table empty. • Truncate will not remove table from DB instead it deletes all records permanently. • Removed records can’t be restored.
  • 115. Syntax, Truncate table table_name; Example, Truncate table employee;  Describe the table to get the table structure. Eg, desc table
  • 116. CONTACT: 7760200900 HR: 7022889639 106 4. DROP: • DROP statement is used to delete or remove table from DB or column from table Syntax, DROP table table_name; Example, DROP table employees; • The whole table is deleted from the table and gets stored in recyclebin. •To restore the table from bin we use a comment called flashback. FLASHBACK: Syntax, Flashback table table_name to before drop;
  • 117. What is recycle bin? Recyclebin is a table containing info about dropped objects or tables. Syntax, Select * from recyclebin; • To remove the table permanently without storing in recyclebin, we use a command called purge Syntax, DROP table table_name PURGE; PURGE table table_name; • To delete all records from recyclebin; PURGE Recyclebin; • If you want to see dropped data from DB. Show Recyclebin; HR: 7022889639 107
  • 118. 5. ALTER: ALTER statement is used to modify the table with respect to columns. Example, •Adding a Column. Syntax, ALTER table table_name add colm_name datatype Constraint; Note: while adding column to the table with not null constraint the table should be empty otherwise we will get an error. • Rename a Column. Syntax, ALTER table table_name rename column old colm_name to New colm_name; • Drop a Column. Syntax, ALTER table table_name Drop column colm_name; 108
  • 119. MODIFY: • Modify is used to change the datatype of a column. •Modify a Column. Syntax, 109 ALTER table table_name modify colm_name datatype; • To unlock the user. Syntax, ALTER User user_name Identified by passward account unlock; Note: The column should be empty to change the datatype
  • 120. By using DCL statements we can control user access. There are two DCL statements. 1. GRANT 2. REVOKE 1. GRANT: GRANT statement is used to connect or provide permission from one user to another. 2. REVOKE: REVOKE is used to take back the permissions from the user. 110
  • 121. 1. Normalisation: 2. ERD’s: 3. Set Operators: 4. Analytical Functions: 5. Indexes: 6. Views: 7. Stored procedures: 8. Triggers: 1
  • 122.  " It is the process of reducing a large table into smaller tables in order to remove redundancies and anomalies by identifying their functional dependencies is known as Normalization . “ (Or)  "The process of decomposing a large table into smaller table is known as Normalization ." (Or)  "Reducing a table to its Normal Form is known as Normalization ."
  • 123. What is Normal Form?  A table without redundancies and anomalies are said to be in Normal Form . Levels of Normal From . 1.First Normal Form ( 1NF ) 2.Second Normal Form ( 2NF ) 3.Third Normal Form ( 3NF ) 4.Boyce -Codd Normal Form ( BCNF )  Note : If anyTable / entity is reduced to 3NF , then the table is said to be normalized.
  • 124.
  • 125. 1)Union 2)Union All 3)Intersection 4)Minus UNION: The union operator could to be used to find the result set or combination of two or more table without returning any duplicate rows. Note: • The columns must have same datatypes. • The columns in each table must be in the same order (but they need not have to in the same length). • Each table used within union must have the same no of columns. • It provides the unique values by default.
  • 126.  Syntax: Select col_name From table_name1 [where <filter-condn>] Union Select col_name From table_name2 [where<filter-condn>]; ORDER OF EXECUTION FROM [WHERE](if used) SELECT
  • 127. UNION ALL: The union all operator could to be used to find the result set or combination of two/more table including returning any duplicate rows NOTE • The columns must have same datatypes. • The columns in each table must be in the same order(but they need not have to in the same length) • Each table used within union must have the same no of columns.
  • 128.  Syntax: Select col_name From table_name1 [where <filter-condn>] Union All Select col_name From table_name2 [where<filter-condn>]; ORDER OF EXECUTION FROM [WHERE](if used) SELECT
  • 129. INTERSECT: Intersect operator is used to combine two select statements, it returns only common value[equal value] present in the table [col_name] NOTE • The columns must have same datatypes.
  • 130.  Syntax: Select col_name From table_name1 [where <filter-condn>] INTERSECT Select col_name From table_name2 [where<filter-condn>]; ORDER OF EXECUTION FROM [WHERE](if used) SELECT
  • 131. MINUS: Minus operator is used to compare to select statements if returns only the row that are present in the first stmt but are not in second stmt [distinct value],minus elements are the duplicate rows.
  • 132.  Syntax: Select col_name From table_name1 [where <filter-condn>] MINUS Select col_name From table_name2 [where<filter-condn>]; ORDER OF EXECUTION FROM [WHERE](if used) SELECT
  • 133. SQL Create Index Statement: To increase the execution speed .The create index statement is used to create indexes in tables , indexes are used to retrieve data from the database more quickly than otherwise. The user cannot see the indexes, they are just used to speed up searches/queries. NOTE:  Updating a table with indexes takes more time than updating a table without (because the indexes also need on update). So only create indexes on columns that will be frequently searched against.
  • 134.  Create Index Syntax Creates an index on a table. Duplicate values are allowed: Create Index index_name On tablename(col_name1,col_name2…..); Set auto trace on explain  Create Unique Index Syntax Creates a unique index on a table, Duplicate values are not allowed. Create Unique index index_name On table_name(col1,col2….); NOTE: The syntax for creating indexes varies among different database. Therefore check the syntax for creating indexes in your database
  • 135.  Create Index example The SQL stmt below creates an index named ‘idx_lastname’ on the ‘lastname’ column in the ‘persons’ Table: Create Index 2 On emp(ename); * If you want to create an index on a combination of columns, you can list the column names within the parenthesis, separated by commas Create Index 2 On emp(ename,job);
  • 136.  In SQL view is a virtual table based on the result set of an sql statement.  Syntax: Create view view_name As Select col_name From table_name Where<condition>; Syntax 2 Drop view view_name
  • 137.  NOTE: To give permission to create view!! Login as system Connect User: system Pwd:Oracle1234(tiger) Grant create view to Scott;(giving the permission) Revoke create view from Scott;(tacking back permission)