SQL Notes 1
SQL Notes 1
SQL Notes 1
(SRUCTURED QUERY
LANGUAGE)
CONTENTS
1. SQL
2. HISTORY OF SQL
3. USERS OF SQL
4. BACKEND VALIDATION
5. IMPORTANCE OF SQL
6. BASIC TERMINOLOGY
a). DATABASE b). SCHEMA c). ENTITY
d). DATA e). DBMS f). RDBMS
7. DATA INTEGRITY
8. DATA TYPES
1). Char 2). Varchar 3). Number 4). Date
9. CONSTRAINTS
1). Not null 2). Unique 3). Check 4). Primary key 5). Foreign key
10. SQL STATEMENTS/LANGUAGES
1). DQL 2). DDL 3). DML 4). DCL 5). TCL
11. Data Query language (DQL)
1). Projections 2). Selections 3). Joins
12. Data Definition language (DDL)
1).CREATE 2). ALTER 3). RENAME 4). DROP 5). TRUNCATE
13. Data Manipulation Language (DML)
1). INSERT 2). UPDATE 3). DELETE
14. Data Control Language (DCL)
1).GRANT 2). REVOKE
15. Transaction Control Language (TCL)
1). ROLLBACK 2). COMMIT 3). SAVEPOINT
16. CASE MANIPULATION FUNCTION
1). Upper function() 2). Lower function() 3). Initcap function()
17. EXPRESSIONS , OPERATORS
18. LITERALS
1). Number literals 2). Character literals 3). Date literals
19. ALIAS NAME
20. DISTINCT CLAUSE
21. ORDER BY CLAUSE
22. CONCATENATION OPERATOR
23. Logical operator (AND , OR , NOT)
24. Special operator ( In, Between, Like , Is)
25. Combination Of Special Operator And Not Operator
26. FUNCTIONS
27. MULTI ROW FUNCTIONS
a. count ( ) b. max ( ) c. min ( ) d. sum ( ) e. avg ( )
28. GROUP BY CLAUSE
29. HAVING CLAUSE
30. QUERY
31. SUB QUERY
32. JOINS
a). Cartesian Joins / Cross Joins
b). Inner Joins / Equi Joins
c). Non - Equi Joins
d). Outer Joins ------- 1. left Outer Joins / left Joins
2. Right Outer Joins / Right Joins
3. Full Outer Joins / Outer Joins
e). Self Joins
33. CO-RELATED SUB QUERY
34. PSEUDO COLUMNS OR FALSE COLUMN
1). Row id 2). Row number
35. VIEWS
1). Simple view 2). Complex view
36. ESCAPE CHARACTERS
37. ANY and ALL operations
38. SET OPERATOR
1). UNION Operator 2). UNION ALL Operator
3). Intersect Operator 4). MINUS Operator
39. NORMALIZATION
1). 1NF 2). 2NF 3). 3NF 4). 4NF 5). 5NF 6). 6NF
BCNF ( Boyce Codd Normal Form) → 3.5 NF
40. SINGLE ROW FUNCTIONS
41. 1).character single row functions 2).number functions
42. 3).general functions 4).Date functions. 5).conversion function
43. Various Syntax in SQL
44. Questions on SQL Query
45. INTERVIEW QUESTIONS ON SQL
SQL (STRUCTURED QUERY LANGUAGE)
SQL
SQL is a structured query language which is used to interact with the database.
HISTORY OF SQL:
➢ SQL was introduced by Raymond Boyce in the year 1970 and also a father
of sql.
➢ E.F Codd (Edger Frank Codd) is known as co-founder of Sql.
➢ SQL was introduced by a company called IBM, but current owner of sql is
Oracle.
➢ Initially sql was known as SEQEL (Simple English Query Executable
Language).
➢ It was acquired by ANSI (American National Standard Institute) and they
renamed SEQEL to SQL in the year 1979.
USERS OF SQL:
1. Database developer: This person use sql to create a database and tables for
s/w or application.
2. Database Tester: This person use sql to perform a backend validation.
3. Database administrator: This person use sql to maintain a successful
environment in the database.
BACKEND VALIDATION:
The process of ensuring a data entered in frontend as successfully stored in
backend (database) is called as backend validation.
IMPORTANCE OF SQL:
1. Create database
2. Create tables
3. Inserting data
4. Deleting data
5. Updating data / modifying data
6. Retrieving data / accessing data / modifying data
7. Create views
8. Create stored procedure or triggers or index
Page 1
SQL (STRUCTURED QUERY LANGUAGE)
BASIC TERMINOLOGY:
1. DATABASE:
➢ Database is a centralized place which is used to store data.
➢ Database should allow user to interact with database.
➢ Database should allow user to insert a new data.
➢ Database should allow user to modify a new data or update older data with
newer data.
➢ Database should allow user to delete unwanted data.
➢ Database should allow user to fetch or retrieve data.
➢ In database data will be stored in a form of tables.
➢ Rows is also known as tuples or records.
➢ Columns is also known as attributes or fields or identifiers.
➢ Table is also known as object or entity.
➢ The intersection of rows and columns is called as cells.
Page 2
SQL (STRUCTURED QUERY LANGUAGE)
3. ENTITY: An Entity is a real world object. Each and Every entity is having its
own attributes and properties which describes about them is called as
Entity.
➢ Generally, an Entity is a combination of rows and columns.
Example: Student → Entity
• Sid , Sname , Dob , Gender, Address , Age
4. Data: Data is a row or record which describes all attributes or columns
of an entity of tables is known as data.
➢ Generally, Data is also defined as
➢ Data is a collection of information.
➢ Data is piece of information.
➢ Data is a raw fact.
Example: Student → table
Row /record: +sid+ sname+-age-+---loc---+-----Sal----+
Data: | 1 | Ramesh | 32 |Bengaluru | 2000.00 |
(Column / attribute)
Page 3
SQL (STRUCTURED QUERY LANGUAGE)
Page 4
SQL (STRUCTURED QUERY LANGUAGE)
➢ Data integrity process will ensures that we are storing valid data in
database.
➢ Data integrity process will be achieved by data types and constraints.
➢ The process of Data integrity will be achieved by data types and constraints
for each and every column present in the database.
DATA TYPES: Data types which describes what type of data should be accept or
store in a column in a database or tables.
➢ Assigning data types for each and every column is mandatory or
compulsorily.
➢ For each and every column we assign maximum only one data type.
➢ In oracle RDBMS N no of data types are available among those four are the
preferred and important data types are:
1). Char 2). Varchar 3). Number 4). Date
1). Char:
➢ If a column is assign with a data type char then it will accept only
characters. i.e.: alphabets (A-Z ,a-z) , numbers (0-9) and special characters
($-#).
➢ Fixed length memory allocation.
➢ It will accept up to 2000 characters.
➢ The default size is 1.
➢ The allocated memory block which are not utilized will consider as space
and we can’t utilize in future.
➢ Syntax : char (size)
2). Varchar:
➢ If a column is assign with a data type varchar then it will accept only
characters. i.e.: alphabets (A-Z ,a-z) , numbers (0-9) and special characters
($-#).
➢ variable length memory allocation.
➢ It will accept up to 4000 characters.
Page 5
SQL (STRUCTURED QUERY LANGUAGE)
3). Number:
➢ If a column is assign with a data type as number it will accept only number
or digit (0-9).
➢ Syntax: Number (precision, Scale)
➢ Case 1: Number (precision) : maximum no of digits can be accept or stored.
➢ Eid Number(5)
➢ 12345
➢ 98765
➢ Case 2: Number (precision, scale) : maximum no of digits can be accept or
stored including decimal and it represents decimal value.
➢ Eid → Number(4,2)
➢ 12.45
➢ 98.65
➢ Note: -9999 to 9999 (it will accept -ve no but usually we will not enter).
4). Date:
➢ If a column is assign with a data type as date it will accept only date format.
➢ The date format in oracle RDBMS
➢ DD-MON-YYYY OR DD-MON-YY
➢ Syntax: Date
➢ Example: 15-Aug-47 or 15-Aug-1947
CONSTRAINTS:
➢ Constraint is a set of rules or set of validation done to the column to restrict
of storing wrong data is called as constraints.
➢ There are 5 types of constraints are available in sql:
1). Not null 2). Unique 3). Check
Page 6
SQL (STRUCTURED QUERY LANGUAGE)
2). Unique:
➢ Unique is a constraint given to column.
➢ If any column is assigned with unique constraint then that column will not
accept duplicates values, i.e. it will not accept the values which is already
present or exists.
➢ Which column or attribute will assign constraint as Unique.
➢ If a column or attribute should consist or accept only distinct values for
those column will assign a constraint as unique.
3). Check / (Domain):
➢ Check is an additional validation done to the column to restrict of storing
wrong data.
➢ Syntax: check (condition)
➢ Ex: Mob -- number(10)
Check (length(mob)==10)
Sal – number(5,2)
Check (Sal>0)
4).Primary key:
➢ Primary key is a constraint given to column.
➢ If any column is assigned with a constraint as primary key it will represent
or identify a row or record uniquely.
➢ Which column or attribute can eligible to become primary key.
Page 7
SQL (STRUCTURED QUERY LANGUAGE)
Page 8
SQL (STRUCTURED QUERY LANGUAGE)
➢ Foreign key column will accept null values and duplicates values but it will
not accept the values which is not present in parent table column.
➢ In a table more than one foreign key can consist.
➢ If a column as to be consider as foreign key then first of all that column
should be primary in its parent table.
p.k f.k
empno ename Job Sal mob Dob Deptno
Not null Not null Not null * Not null Not null Not null
Unique * * * unique * *
p.k
Deptno dname Loc
Not null Not null Not null
Unique * *
SQL STATEMENTS/LANGUAGES
We have 5 different languages in SQL
1. DQL 2. DDL 3. DML 4. DCL 5. TCL
1. Data Query language (DQL):
➢ DQL is used to fetch / retrieve / accessing a data present in a database.
➢ DQL language consist of select statement.
• Select : select statement is used to fetch or retrieve or accessing a data
from a specific table in a database.
• Select statement is classified into 3 types
1). Projections 2). Selections 3). Joins
1). Projections:
➢ Projections is a process of fetching or retrieving or accessing a data from a
specific table by selecting all columns or specified number of columns is
called as projections.
➢ In projections we can restrict columns but we can’t restrict rows.
Syntax:
Page 9
SQL (STRUCTURED QUERY LANGUAGE)
Page 10
SQL (STRUCTURED QUERY LANGUAGE)
➢ If the specified condition is true or false Where clause will not stop
execution it will check the conditions for all the rows present in a table.
➢ Where clause will not execute multiple records at one shot, but Where
clause will execute multiple conditions for a single record at one shot.
2. Data Definition language (DDL):
1.CREATE 2. ALTER 3. RENAME 4. DROP 5. TRUNCATE
1).Create: It is used to create a table or an object.
Syntax:
Create table table name(
Colname1 datatype not null/null,
Colname2 datatype not null/null,
.
.
Constraint constraint_name Unique(colname),
Constraint constraint_name Primary key(colname),
Constraint constraint_name Check(condn),
Constraint constraint_name Foreign key(colname) References parent table
(colname)
);
Example:
Page 11
SQL (STRUCTURED QUERY LANGUAGE)
a. To add a column:
Syntax: Alter table tablename
Add column_name datatype constraint;
Example: Alter table emp
Add mob number(13) not null;
b. To drop a column:
Syntax: Alter table tablename
Drop Column Column_name;
Example: Alter table emp
Drop column mob;
c. To Rename a column:
Syntax: Alter table tablename
Rename column old Column_name to new Column_name;
Example: Alter table emp
Rename column mob to mobile;
3). Drop: Drop is used to delete the table permanently from a db
Syntax: Drop table tablename;
Example: Drop table emp;
From oracle 10g onwards we have a concept of recycle bin, then can get back the
table from recycle bin by using flashback statement.
Syntax: Flashback table tablename to before Drop;
Example: Flashback table emp to before Drop;
We can also delete the table from recycle bin by using purge statement
Syntax: Purge table tablename;
Example: Purge table emp;
Page 12
SQL (STRUCTURED QUERY LANGUAGE)
4).Truncate: Truncate statement is used to delete all the records from the table
permanently.
Syntax: Truncate table tablename;
Example: Truncate table emp;
5).Rename: rename statement is used to change the tablename permanently.
Syntax: Rename old tablename to new tablename;
Example: Rename table emp to employee ;
Set col1=val1,col2=val2…
Where <condn>;
Example: update table emp
Page 13
SQL (STRUCTURED QUERY LANGUAGE)
Page 14
SQL (STRUCTURED QUERY LANGUAGE)
Page 15
SQL (STRUCTURED QUERY LANGUAGE)
---- savepoint a;
→ savepoint created.
----update emp
Set ename=’Rakesh bj ‘
Where empno=20;
Emp | Ename
10 | virat Kohli
20 | Rakesh bj
---- savepoint b;
→ savepoint created.
---- delete from emp
Where empno=20;
---- select * from emp;
Emp | Ename
10 | virat Kohli
---- savepoint c;
→ savepoint created.
----rollback to c;
---- select * from emp;
Emp | Ename
10 | virat Kohli
-----rollback to b;
---- select * from emp;
Emp | Ename
Page 16
SQL (STRUCTURED QUERY LANGUAGE)
10 | virat Kohli
20 | Rakesh bj
-----rollback to a;
---- select * from emp;
Emp | Ename
10 | virat Kohli
20 | Rakesh
CASE MANIPULATION FUNCTION:
There are 3 case manipulation function:
1). Upper function(): upper function will convert given string into upper case.
Page 17
SQL (STRUCTURED QUERY LANGUAGE)
Operators:
Example: 10,25,50,100….
2). Character literals: It is the Immediate or direct value which is of type
character given to any of the sql statements. character literals should be
enclosed in (‘’) (single quotes).
Example: ‘virat Kohli’
3). Date literals: It is the Immediate or direct value which is of type Date given to
any of the sql statements.
Example: DD-MON-YY
15-AUG-47
ALIAS NAME: Alias name is alternative name or temporary name given to
column or expression present in result set.
Page 18
SQL (STRUCTURED QUERY LANGUAGE)
➢ Whenever we are giving alias name for column or expression , it will change
in a result set but not in original table.
Syntax: Select * / C.N’s / Expression [AS] Alias name -----2
From tablename ; --- 1
Example: WQD annsal of all the employees.
Select Sal *12 [as] annsal
From emp;
DISTINCT CLAUSE: Distinct Clause is used to eliminate duplicate values present in
result set or output.
➢ Distinct Clause will execute after select statement /clause.
Page 19
SQL (STRUCTURED QUERY LANGUAGE)
Page 20
SQL (STRUCTURED QUERY LANGUAGE)
Page 21
SQL (STRUCTURED QUERY LANGUAGE)
➢ In operator it will compare a single LHS value with all the values present in
RHS value.
➢ In operator it will return true when any one of the condition or comparison
is true.
➢ In operator it will return false when any one of the condition or
comparison is false.
➢ In operator it will working similar to OR operator.
Syntax: LHS Value IN (value1,value2,value3….); 2).
BETWEEN OPERATOR:
➢ When the values or input are in the form of range we
will use between operator.
Syntax: LHS Value BETWEEN lower limit and upper limit;
➢ ALWAYS lower limit should be less than upper limit i.e. lower limit < upper
limit.
➢ Between operator it works like inclusive range ( including lower limit and
upper limit ).
➢ Internally, between operator is represented as lower limit >= and upper
limit <=.
➢ Between operator it will return true when any one of the condition or
comparison is true.
➢ Between operator it will return false when any one of the condition or
comparison is false.
➢ Between operator it will working similar to AND operator.
3). IS OPERATOR:
➢ In Oracle RDBMS , one null is not equal to another null
➢ Null != Null
➢ To compare Null with Null we will use an operator called IS operator.
➢ It is a special operator which is used to compare null values.
➢ Syntax: LHS Value IS Null;
Characteristics of Null:
➢ Null is a reserve keyword in Oracle RDBMS.
Page 22
SQL (STRUCTURED QUERY LANGUAGE)
Page 23
SQL (STRUCTURED QUERY LANGUAGE)
NOT BETWEEN Operator it will retain true when LHS value is NOT within
lower limit and upper limit or not within the range.
3). LHS Value IS NOT Null;
NOT IS Operator it will return true when LHS value is NOT equal to any of the
RHS value.
Page 24
SQL (STRUCTURED QUERY LANGUAGE)
Page 25
SQL (STRUCTURED QUERY LANGUAGE)
1. whatever the C.N present in select clause same should be present in group by
clause.
Page 26
SQL (STRUCTURED QUERY LANGUAGE)
2. whatever the C.N present in group by clause may or may not be present in
select clause.
HAVING CLAUSE:
➢ Having clause is used to consider multi row functions as a conditions.
➢ Having clause will filter the record after grouping the data.
➢ Having clause is a dependent clause Because Having clause can’t be used
without group by clause.
Syntax: Select group by Expression ---- 4
From tablename ---- 1
Where <condition> ----- 2
group by References ---- 3
having Group by expression ; ---- 5
When we go for having clause.
➢ We can write C.N as condition in having clause but that column should be
present in group by clause.
➢ Whenever the condition w.r.t C.N it is better to use where clause.
➢ If any condition w.r.t Multi row functions it is better to go with Having
clause.
1. whatever the Multi row functions present in Having clause may or may not
be present in select clause.
Page 27
SQL (STRUCTURED QUERY LANGUAGE)
1. From clause
2. Where clause
Select * → outer query
From tablename
Where condition ( Select * → Inner query / outer query
From tablename
Where condition ( Select * → Inner query
From tablename
Where condition));
➢ The innermost query is called → Inner query.
➢ The outermost is called → Outer query.
➢ Generally, the combination of Inner query and Outer query is known as
sub query. Sub query is also known as nested sub query because in
oracle we can write up to 255 Inner query.
WORKING MECHANISM OF SUB QUERY:
➢ First compiler give control to Inner query .
➢ Inner query will execute based on conditions and it will prepare / generate
the output.
Page 28
SQL (STRUCTURED QUERY LANGUAGE)
➢ The output generated by Inner query will pass as an input to outer query.
➢ Outer query will execute based on condition and input taken from Inner
query and it will prepare / generate final output.
➢ Outer query is the responsible to prepare final output. Outer query is
dependent and inner query is a independent query.
➢ Outer query is completely dependent on inner query.
A. Single row sub query - If the inner query is returning exactly one row as
output then it is Single row sub query.
➢ Sigle row sub query is returning one row as output to compare we will use
IN operator.
B. Multi row sub query - If the inner query is returning more than one row as
output then it is multi row sub query.
➢ Multi row sub query is returning more than one row as output. We can’t
compare with the help of relational operator so we will use ANY,ALL and
IN operator.
When to go for sub query or what are the uses of sub query
➢ Whenever if you want to determine unknown values.
➢ To link multiple tables (by using primary key and foreign key).
➢ To map values, present in a same table but in different rows.
(Nth max and Nth min).
Page 29
SQL (STRUCTURED QUERY LANGUAGE)
1. We can link N no of tables but we can’t fetch data from all tables.
2. If you want to determine Nth max , Nth min we should write N-1 inner length
query will be increase and performance will be decrease.
JOINS:
➢ Joins is a special possibility of select statement.
➢ By using joins, we can fetch / retrieve data from multiple table
simultaneously.
➢ In oracle RDBMS joins is classified into 5 types
Page 30
SQL (STRUCTURED QUERY LANGUAGE)
➢ Cartesian join can apply for any kind of table (means we can cartesian join
if the table is having relationship or without relationship means pk and fk).
➢ Cartesian joins will result both valid and invalid compare to valid , invalid is
more hence it is not preferred type of joins.
Oracle Syntax: Select * / C.N ---- 2
From tablename1, tablename2, … ; ---- 1
ANSI Syntax: Select * / C.N ---- 2
From table1 cross join table2, … ; ---- 1
Example: WQD ename, Dname of all employee
Select ename, dname
From emp, dept;
B. INNER JOINS / EQUI JOINS:
➢ Joining multi table by utilizing common column between the table is called
Inner join. Or Joining multiple table by specifying joining condition is called
Inner join.
➢ In Inner join we specify joining condition.
➢ Inner join will result only valid result.
➢ We can apply Inner join only the table is having relationship (pk and fk are
in same column).
➢ Joining condition - Joining multi table by utilizing common column between
the table is called Joining condition.
Syntax of Joining condition:
Where table1 C.N= table2 C.N
Page 31
SQL (STRUCTURED QUERY LANGUAGE)
C. SELF JOINS:
➢ Joining same table to itself is called as self-Join.
➢ Except self-join other all type of joins we will specify multiple table names.
Where as in self-join same table but multiple copies.
➢ Based on self-join joining condition it has classified into two cases
➢ Case 1: Joining same table to itself by considering same column name.
Syntax: Select * / C.N ---- 3
From table1 A , table2 B, … --- 1
Where A.C.N1= B.C.N2; ------2
➢ Case 2: Joining same table to itself by considering different column name.
Syntax: Select * / C.N ---- 3
From table1 A , table2 B, … --- 1
Where A.C.N1= B.C.N2; ------ 2
Example: WQD ename, job, mgr_name, mgr_job of all employee
Select a.ename,a.job, b.ename mgr_name, b.job mgr_job
From emp a, emp b
Where a.mgr=b.empno;
Page 32
SQL (STRUCTURED QUERY LANGUAGE)
Page 33
SQL (STRUCTURED QUERY LANGUAGE)
Page 34
SQL (STRUCTURED QUERY LANGUAGE)
Example: WQD ename, Dname only the employees are not working for any of
the dept and the dept no employees are working
Select ename, Dname
From emp, dept
Where emp.deptno=dept.deptno ( + )
Union
Select ename, Dname
From emp, dept
Where emp.deptno ( + ) =dept.deptno ;
CO-RELATED SUB QUERY:
➢Co-Related Sub Query is a advanced version of sub queries.
➢Co-Related Sub Query is working on a principle of sub query and joins.
➢In Co-Related Sub Query inner query and outer query will be present.
➢In Co-Related Sub Query inner query and outer query inter related / co-
related each other.
➢ In Co-Related Sub Query inner query and outer query inter dependent on
each other because of specifying joining conditions in inner query.
➢ In Co-Related Sub Query inner query and outer query inter dependent on
outer query output and outer query is dependent on inner query inner
query output both are independent each other.
WORKING MECHANISM OF CO-RELATED SUB QUERY:
➢ First compiler give control to Outer query .outer query will execute for the
first time partially.(except select and where clause , only from clause will
execute).
➢ The output generated by Outer query will pass as an input to inner query.
➢ Inner query will execute for the first time completely(including select ,
from , where).
➢ The output generated by inner query will pass as an input to outer query.
➢ Outer query will execute for the 2nd time completely (including select and
where clause ) and outer query will prepare final output.
Page 35
SQL (STRUCTURED QUERY LANGUAGE)
Page 36
SQL (STRUCTURED QUERY LANGUAGE)
Page 37
SQL (STRUCTURED QUERY LANGUAGE)
VIEWS:
➢ View is like a table created by selecting only specified number of column is
called as views.
➢ Views are created by original table.
➢ A view which is created on a table is called as target table.
➢ A view are classified into 2 types
1). Simple view 2). Complex view
1). Simple view:
➢ A view which is created by single table or single target table is called as
simple view.
Syntax:
Create view view name
As
Select C.N
From tablename;
Example:
Create view demo _ regions
As
Select region _ name
From regions; → view created.
2). Complex view:
➢ A view which is created by More than one table or target table is called as
complex view.
Syntax:
Create view view name
As
Page 38
SQL (STRUCTURED QUERY LANGUAGE)
Select C.N
From table1, table2
Where <condition> ;
Example:
Create view demo _ countries
As
Select region _ name, country_ name, country_id
From regions, countries
Where region. region_id = countries . region_id ;
→ Grant select on demo_ countries to Scott; → view
created.
ESCAPE CHARACTERS:
✓ The process of converting special characters into ordinary characters is called
as escape characters.
Example: WQD ename , which consist of – as a character
Select sname
From escn
Where lower ( sname) like ‘%!_%’
Escape ‘!’;
Sname
Virat _kohli
Rakesh %bj
-------------------
Select sname
Page 39
SQL (STRUCTURED QUERY LANGUAGE)
From escn
Where lower ( sname) like ‘%_____%’
Escape ‘!’;
--------------------
ANY and ALL operations
ANY OPERATOR
➢ It is a multi- valued operations it will accept single LHS value and multiple
RHS value.
Syntax : LHS VALUE RELATIONAL OPERATOR ANY RHS VALUE
>ANY, < ANY,> = ANY,<= ANY = , != ANY
➢ ANY operator it will compare single LHS value with all the value present in
RHS side.
➢ ANY operator it will return true if any one of comparison is true.
➢ ANY operator it will return false if all the comparison are false.
Example : WQD employee details only if the emp Sal should be more than any of
the Blake Sal.
Select *
From emp
Where Sal > ANY (Select Sal
From emp
Where lower(ename)=’Blake’);
All OPERATOR
➢ It is a multi- valued operations it will accept single LHS value and multiple
RHS value.
Syntax : LHS VALUE RELATIONAL OPERATOR ANY RHS VALUE
>All, < All,> = All,<= All = , != All
Page 40
SQL (STRUCTURED QUERY LANGUAGE)
➢ ALL operator it will compare single LHS value with all the value present in
RHS side.
➢ ALL operator it will return true if any one of comparison is true.
➢ ALL operator it will return false if all the comparison are false.
Example : WQD employee details only if the emp Sal should be more than the
Blake Sal.
Select *
From emp
Where Sal > ALL (Select Sal
From emp
Where lower(ename)=’Blake’);
➢ When to go for ANY and ALL operator
➢ Whenever we want to compare single RHS value with >,<,<=,>= relational
operator with multiple RHS value than it is better to go for ANY operator or
ALL operator.
SET OPERATOR :
Set operator will work with multiple query , output and it will give single output.
1. UNION Operator: This operator will combine multiple query output into a
single output without duplicate.
A={10,x,20,y,30} B={30,40,50,x} ,, A union B ={ 10,x,20,y,30,40,50}
Syntax: Select * / C.N
From table_name
Where <condition>
Union Select * / C.N
From table_name
Where <condition>;
Example:
Page 41
SQL (STRUCTURED QUERY LANGUAGE)
Select Sal
From emp
Where deptno=20
Union Select Sal
From emp
Where lower(job) IN(‘clerk’, ‘analyst’);
2. UNION ALL Operator: This operator will combine multiple query output
into a single output with duplicate.
A={10,x,20,y,30} B={30,40,50,x} ,, A union ALL B ={ 10,x,20,y,30,40,50}
Syntax: Select * / C.N
From table_name
Where <condition>
Union ALL Select * / C.N
From table_name
Where <condition>;
Example:
Select Sal
From emp
Where deptno=20
Union ALL Select Sal
From emp
Where lower(job) IN(‘clerk’, ‘analyst’);
3. Intersect Operator: This operator will combine multiple query output into
a single output only the common values.
A={10,x,20,y,30} B={30,40,50,x} ,, A intersect B ={ x,30}
Page 42
SQL (STRUCTURED QUERY LANGUAGE)
Page 43
SQL (STRUCTURED QUERY LANGUAGE)
Where deptno=20
MINUS Select Sal
From emp
Where lower(job) IN(‘clerk’, ‘analyst’);
NORMALIZATION :
➢ Normalization is a database design technique or table design technique
which organize the data by avoiding redundancy and dependency is called as
normalization.
➢ Normalization is a process of splitting bigger table into smaller table and
establishing relationship is called as normalization .
➢ E. F CODD is the father of normalization.
➢ E. F CODD as prepared a normal theory with several normal forms.
Normal forms are:
1. 1NF 2. 2NF 3. 3NF 4. 4NF 5. 5NF 6. 6NF
BCNF ( Boyce Codd Normal Form) → 3.5 NF
1. 1NF
➢ Each and every cell in a table should consist of single value.
➢ Each and every record in a table should be unique each other.
2. 2NF
➢ First table should be in 1NF.
➢ In a table any one of the column should consider as PK.
➢ In a table functional dependency should not be present.
Functional dependency:
➢ All non pk column is depending on single pk column is called as functional
dependency.
Partial dependency:
➢ A non pk column is depending on another non pk column and inter it is
depending on pk is called as functional dependency.
Page 44
SQL (STRUCTURED QUERY LANGUAGE)
3. 3NF
➢ First table should be in 2NF.
➢ A table should not consist of transitive dependency .
SINGLE ROW FUNCTIONS :
➢ Single row functions are the functions which can accept n records as input
and it provides n records as output.
➢ Single row functions execute record by record
➢ It can be used in select clause and where clause
➢ Single row functions can be nested.
➢ We pass CN/exp/literals as an argument for single row functions.
Classification of SRF’s
1.character single row functions. 2.number functions
3.general functions. 4.Date functions. 5.conversion function.
1. CHARACTER SINGLE ROW FUNCTIONS
1.length: it is used to obtain the length of given string.
Syntax : Length( C.N /’string’)
2.concat: it is used to concatenate two strings
Syntax : Concat (arg1,arg2)
3.SUBSTR: substr function is used extract the ch or substring from a given string.
Syntax : SUBSTR( C.N /’String’,start_pos,[length])
Arg1→colname or a string
Arg2→start position(position can be negative or positive)
Arg3→length(optional)
4.INSTR: instr function is used to search the ch or a ss from the given string
Syntax : INSTR( C.N /’string’, ‘char ss’,[s_pos,occurrence])
Arg1→colname/string Arg2→ch or a ss Arg3→start position(-ve or +ve)
Page 45
SQL (STRUCTURED QUERY LANGUAGE)
Page 46
SQL (STRUCTURED QUERY LANGUAGE)
----- 10 ----
2.NVL2 function : it is also used to handle null values
Syntax : NVL2(arg1,arg2,arg3)
If arg1 is null value nvl2 function will return the value present inn arg3,if arg1 is
not a null it returns value present in arg2.
Example: Select SAL+ NVL2(comm, comm*0.1,0) from dual;
3. CASE function and DECODE function:
It is similar to if else statement
Syntax : Select C.N / Exp case
When cond1 then ‘result1’
When cond2 then ‘result2’
When cond3 then ‘result3’
……
Else ‘result’
End [as] Alias name
from tablename;
Syntax : Select C.N / Exp case
Decode ( expression , condition1, action
Condition2, action, other action)
from tablename;
Example : WQD ename, Sal , and calculate a new Sal in the following way
1. if the employee are working for 20 dept, new Sal should be increment of 50%.
2. if the employee are working for 10 dept, new Sal should be increment of 75%.
3. if the employee are working for any other dept, new Sal should be increment of
25%.
Page 47
SQL (STRUCTURED QUERY LANGUAGE)
Page 48
SQL (STRUCTURED QUERY LANGUAGE)
Page 49
SQL (STRUCTURED QUERY LANGUAGE)
➔ WHERE Clause
SELECT * / C.N’s / Exp
FROM table_name
WHERE < CONDITION >;
➔ DISTINCT Clause
SELECT DISTINCT * / C.N’s / Exp
FROM table_name;
➔ ALIAS NAME
SELECT C.N’s / Exp [ AS ] ALIAS NAME
FROM table_name;
➔ Order by clause
SELECT * / C.N’s / Exp
FROM table_name
WHERE < CONDITION >;
ORDER BY [ ASC] / DESC;
➔ AND/OR Clause
SELECT * / C.N’s / Exp
FROM table_name
WHERE CONDITION-1 {AND|OR} CONDITION-2;
Page 50
SQL (STRUCTURED QUERY LANGUAGE)
➔ IN Clause
SELECT * / C.N’s / Exp
FROM table_name
WHERE column_name IN (val-1, val-2,...val-N);
➔ BETWEEN Clause
SELECT * / C.N’s / Exp
FROM table_name
WHERE column_name BETWEEN (val-1, val-2,...val-N);
➔ LIKE Clause
SELECT * / C.N’s / Exp
FROM table_name
WHERE column_name LIKE { PATTERN };
➔ IS Clause
SELECT * / C.N’s / Exp
FROM table_name
WHERE column_name IS NULL;
➔ GROUP BY Clause
SELECT group by expression
FROM table_name
WHERE < CONDITION >
GROUP BY references;
➔ HAVING Clause
SELECT group by expression
FROM table_name
WHERE CONDITION
GROUP BY references
HAVING group by expression;
Page 51
SQL (STRUCTURED QUERY LANGUAGE)
➔ CARTESIAN JOIN
SELECT * / C.N
FROM table1, table2….;
➔ INNER JOIN
SELECT * / C.N
FROM table1, table2….
Where <joining condition> and <condition> ;
➔ SELF JOIN
CASE1 : SELECT * / C.N
FROM table1 A, table2 B….
Where A.CN1=B.CN1 ;
CASE2 : SELECT * / C.N
FROM table1 A, table2 B….
Where A.CN1=B.CN2 ;
Page 52
SQL (STRUCTURED QUERY LANGUAGE)
➔ Create table
Create table table name(
Colname1 datatype not null/null,
Colname2 datatype not null/null,
.
.
Constraint constraint_name Unique(colname),
Constraint constraint_name Primary key(colname),
Constraint constraint_name Check(condn),
Constraint constraint_name Foreign key(colname) References
parent table (colname)
);
➔ Alter table
1. To add a column:
Alter table tablename
Add column_name datatype constraint;
2. To drop a column:
Alter table tablename
Drop column column_name ;
3. To rename a column:
Alter table tablename
Rename column old column_name to new_column;
➔ RENAME TABLE
Rename old_tablename to new_tablename;
➔ DROP table
Drop table table_name;
Flashback table table_name to before drop;
Page 53
SQL (STRUCTURED QUERY LANGUAGE)
➔ TRUNCATE table
Truncate table table_name;
➔ INSERT
Insert into tablename values(v1,v2,v3…);
➔ UPDATE
Update tablename
Set col1=val1,col2=val2….
Where <condition >;
➔ Delete
Delete from table_name
Where <condition >;
➔ GRANT
GRANT SQL statements on table_name to username;
➔ REVOKE
REVOKE SQL statements on table_name from username;
➔ ROLLBACK
ROLLBACK;
➔ COMMIT
COMMIT;
➔ SAVEPOINT
SAVEPOINT SAVEPOINT NAME;
Page 54
SQL (STRUCTURED QUERY LANGUAGE)
Employee table
Department table
Page 55
SQL (STRUCTURED QUERY LANGUAGE)
Page 56
SQL (STRUCTURED QUERY LANGUAGE)
Select *
From dept;
9. Write a Query to display employee name, his employee number, his salary and
also his annual salary for every employee.
Select ename ,empno ,Sal ,Sal*12
From emp;
10.Write a Query to display employee name, his employee number and salary
with the hike of 30% for every employee
Select ename, empno, (Sal + 0.3)*12
From emp;
11. Write a Query to display name of the employee with annual salary with a
monthly bonus of 200 and provide suitable alias name.
Select ename, ( Sal +200) * 12 as annsal
From emp;
12. Write a Query to display name, salary along with annual salary of employee
with yearly bonus of 1000.
Select ename, ( Sal +1000) * 12 as annsal
From emp;
13. Write a Query to select all the salary of employee of the salary is greater than
1500.
Select Sal
From emp
Where Sal>1500;
14. Write a Query to display employee name, his hire date, his salary and annual
salary only if his annual salary greater than 10000.
Select ename, hiredate, Sal , ( Sal * 12 ) as annsal
From emp
Page 57
SQL (STRUCTURED QUERY LANGUAGE)
Page 58
SQL (STRUCTURED QUERY LANGUAGE)
20. Write a Query to display all the details of employee only if his designation is
clerk and if the department number is 20.
Select *
From emp
Where lower(job) = ‘clerk’ and deptno=20;
Questions on operators:
1. display all the employees whose name starts with p
Select *
From emp
Where lower(ename) like ‘p%’;
2. display all the analyst and clerks in department 10 and 20.
Select *
From emp
Where lower(job) IN (‘analyst’,’ clerks’) and deptno IN(10,20);
3. display all the employees who are having at least two AA’s in their job locations
descriptions and salary in the range 1200 to 2800 in dept 10,20,30.
Select *
From emp
Where lower(job) like ‘%AA%’ and Sal between 1200 to 2800 and deptno
IN(10,20,30);
4. display all the employees whose job does not belong to clerk and whose
department number Is 10,20.
Select *
From emp
Where lower(job) <> ‘clerk’ and deptno IN(10,20);
Page 59
SQL (STRUCTURED QUERY LANGUAGE)
5. list all the employees who is not having reporting manager in dept 20 and 30.
Select *
From emp
Where mgr IS NULL and deptno IN(20,30);
6. list all the employees who’s job is salesman and the salary ranges between
1500 and 3000
Select *
From emp
Where lower(job) = ‘salesman’ and Sal between 1500 to 3000;
Group by and having questions:
1. Display The Deptno Which Is Having The Maximum Salary And Maximum Salary
More Than 1500 Earned By The Employee And Job Description Not As A Clerk And
Sort By Descending Order
Select Deptno, Max(Sal)
From Emp
Where Job!='Clerk'
Group By Deptno
Having Max(Sal)>1500
Order By Deptno Desc;
2. List The Number Of Employee In Each Department, Except 30, Sorted High To
Low. Only Include Department With 3 Or More Employee.
Select Deptno, Count(*)
From Emp
Where Deptno!=30
Group By Deptno
Having Count(*)>=3
Order By Deptno Desc;
3. Display The Number Of Employees Who Has Annual Salary More Than 10000
Department-Wise
Select Deptno, Count(*)
Page 60
SQL (STRUCTURED QUERY LANGUAGE)
From Emp
Where Sal*12>10000
Group By Deptno;
4. Display The Max Salary For Each Of The Job Excluding All The Employee Whose
Having Commission.
Select Job ,Max(Sal)
From Emp
Where Comm Is Null
Group By Job;
5.Find The Total Salary Department Number Wise Where More Than Two
Employees Exits?
Select Deptno, Count(*),Sum(Sal)
From Emp
Group By Deptno
Having Count(*)>2;
6. Display Job Wise And Department Wise Least Salary Only If The Least Salary Is
Less Than 3000 In Department 10,30?
Select Deptno , Job ,Min(Sal)
From Emp
Where Deptno In (10,30)
Group By Deptno, Job
Having Min(Sal)<3000;
7. List All The Employees Except Those Who Are Working In Dept 30 And 20?
Select *
From Emp
Where Deptno Not In (20,30);
8. Display The Department Number Which Are Having More Than 200 As Their
Commission Along With Employees Whose Name Having 'A' Is One Of Character.
Select *
From Emp
Where lower(Ename) Like '%A%' And Comm>200;
Page 61
SQL (STRUCTURED QUERY LANGUAGE)
9. Display Department Number And Total Salary Whose Average Salary Is Greater
Than 500 For Each Department.
Select Deptno, Avg(Sal),Sum(Sal)
From Emp
Group By Deptno
Having Avg(Sal)>500;
10.Display Job Wise Salary Of The Employees B/W 2000 & 5000 Excluding Dept No
30 .
Select Job, Sal
From Emp
Where Sal Between 2000 And 5000
Group By Job, Sal
Having Deptno<>30;
11. Display Job Wise Employee Names Which Consist Of 5 Characters And Job
Designation Should Be Neither Salesman Nor Analyst
Select Ename, Job
From Emp
Where Ename Like '_____'
Group By Job, Ename
Having Job Not In ('Salesman’, ‘Analyst')
Order By Job;
12. Display The Department Number Along With The Number Of Employees And
Also Employee Name?
Select Ename, Deptno, Count(*)
From Emp
Group By Deptno, Ename
Order By Deptno;
13. Display Department Wise Maximum And Minimum Salary Of All Salesman.
Select Deptno ,Min(Sal),Max(Sal)
From Emp
Where Job='Salesman'
Group By Deptno;
Page 62
SQL (STRUCTURED QUERY LANGUAGE)
15. Display Number Of Employee, Total Salary Paid To Employee Work In Each
Department?
Select Deptno, Sum(Sal),Count(*)
From Emp
Group By Deptno;
16. Display Job Wise With A No Of Employees Whose Salary Is Greater Than 2000.
Select Job ,Count(*)
From Emp
Where Sal>2000
Group By Job;
17. Display Maximum Salary, Minimum Salary, Average Salary Of Each Department
Select Deptno, Max(Sal),Min(Sal), Avg(Sal)
From Emp
Group By Deptno;
18. Display Number Of Employees Department Wise Who Are Having Sal Greater
Than 2000 & Working As Manager.
Select Deptno, Count(*)
From Emp
Where Sal>2000 And Job ='Manager'
Group By Deptno;
Page 63
SQL (STRUCTURED QUERY LANGUAGE)
20. Display Minimum Salary For Each Of The Job Whose Name Starts Wit S
Select Job, Min(Sal)
From Emp
Where Ename Like 'S%'
Group By Job;
QUESTIONS ON SUBQUERIES
Case 1: To determine unknown values
1. display all the employees whose job is same as Scott.
Select *
From emp
Where job In (Select job
From emp
Where lower(ename)= ‘Scott’);
2. list employees whose job is same as Scott and their salary greater than smith’s
salary
Select *
From emp
Where job In (Select job
From emp
Where lower(ename)= ‘Scott’) and Sal In (Select Sal
From emp
Where lower(ename)= ‘smith’);
3. display all the employees whose job is same as Scott and Allen
Select *
From emp
Where job In (Select job
Page 64
SQL (STRUCTURED QUERY LANGUAGE)
From emp
Where lower(ename) in (‘Scott’, ‘Allen’);
4. write a query to display all the employee whose job not same as Allen and
salary is greater than martin
Select *
From emp
Where job In (Select job
From emp
Where lower(ename) <>(‘Allen’)) and Sal in ( Select Sal
From emp
Where lower(ename)= ‘ martin’);
5. display all the employees whose salary is greater than avg sal of department
20.
Select *
From emp
Where Sal In (Select Sal
From emp
Where deptno=20
Group by Sal
Having Sal>avg(Sal));
6. list all the employees whose job is same as jones and their salary lesser than
Scott
Select *
From emp
Where job In (Select job
Page 65
SQL (STRUCTURED QUERY LANGUAGE)
From emp
Where lower(ename)= ‘jones’) and Sal < (Select Sal
From emp
Where lower(ename)= ‘Scott’);
7. display who are all the employees reporting to Scott
Select *
From emp
Where mgr In (Select mgr
From emp
Where lower(ename)= ‘ Scott’);
8. display all the employees who are actual managers
Select *
From emp
Where mgr In (Select mgr
From emp);
9. display all the employees who are earning more than all the managers(job).
Select *
From emp
Where Sal In (Select Sal
From emp
Where lower(job)= ‘ managers’);
10. select empno, job and salary of all the analyst who are earning more than any
of the manager(job)
Select ename, job , Sal
Page 66
SQL (STRUCTURED QUERY LANGUAGE)
From emp
Where Sal In (Select Sal
From emp
Where lower(job)= ‘ managers’);
11. list the employees who has salary greater than Allen
Select *
From emp
Where Sal In (Select Sal
From emp
Where lower(ename)= ‘Allen’);
12. display the employee number and name of employee working as clerk and
earning highest salary among clerks
Select empno , ename
From emp
Where Sal In (Select Sal
From emp
Where lower(job)= ‘clerk’);
Case 2 : Linking Multiple table by utilizing PK and FK
1. list the department names that are having no employees at all.
Select dname
From dept
Where deptno In (Select deptno
From emp
Group by deptno
Page 67
SQL (STRUCTURED QUERY LANGUAGE)
Page 68
SQL (STRUCTURED QUERY LANGUAGE)
Page 69
SQL (STRUCTURED QUERY LANGUAGE)
Page 70
SQL (STRUCTURED QUERY LANGUAGE)
Select *
From emp
Where mgr is not null and deptno In (Select deptno
From dept
Where lower(dname) In (’research’, ‘accounting’));
Case 3 : Mapping values into same table but in different rows
1. N th max and N th min
1. display the 3rd maximum salary
Select max(Sal)
From emp
Where Sal < ( select max(Sal)
From emp
Where Sal < ( select max(Sal)
From emp ));
2. display the 3rd minimum salary
Select min(Sal)
From emp
Where Sal > ( select min(Sal)
From emp
Where Sal > ( select min(Sal)
From emp ));
3. display the 3rd maximum hiredate
Select max(hiredate)
From emp
Page 71
SQL (STRUCTURED QUERY LANGUAGE)
Page 72
SQL (STRUCTURED QUERY LANGUAGE)
Page 73
SQL (STRUCTURED QUERY LANGUAGE)
Page 74
SQL (STRUCTURED QUERY LANGUAGE)
Page 75
SQL (STRUCTURED QUERY LANGUAGE)
Page 76
SQL (STRUCTURED QUERY LANGUAGE)
6. list employees who are working in research Dept and they are manager.
Select dname, loc, mgr
From emp , dept
Where emp.deptno = dept. deptno and lower(ename)=’smith’
7. Display ename, dname of all the employees whose salary less than avg sal of
dept 30
Select ename, dname, Sal
From emp , dept
Where emp.deptno = dept. deptno and deptno=30
Group by Sal
Having Sal> avg(Sal);
8. Display ename dname and loc of all the employees who are working for Jones
Select ename, dname, loc
From emp , dept
Where emp.deptno = dept. deptno and lower(ename)=’jones’;
9. Display ename dname of all the employees whose name starts with S
Select ename, dname
From emp , dept
Where emp.deptno = dept. deptno and lower(ename) like ’s%’;
10. Display all Countries along with the Regions .
Select C.* , R.*
From Countries C, Regions R
Where R.region_id = C.region_id ;
11. Display all Cities and the Country it belongs.
Page 77
SQL (STRUCTURED QUERY LANGUAGE)
Page 78
SQL (STRUCTURED QUERY LANGUAGE)
Self-join:
1. WQD ename , hiredate, deptno, mgr name, Sal, deptno only emp Sal should be
in a range 100 to 5000 and mgr name should consist of e character
Select ename, hiredate , A.deptno , ename mgr_name, Sal, B.deptno
mgr_deptno
From emp A , emp B
Where A.mgr=B.empno and A.Sal between 100 to 5000 and lower(B.ename)
like ‘%a’;
2. WQD ename, mgr_ name , only the emp deptno is same as mgr_deptno.
Select A.ename, B.ename mgr_name
From emp A , emp B
Where A.deptno = B.deptno and A.mgr = B.empno;
Corelated sub query
1. WQD 3rd max salary
Select Sal
From emp A
Where 3 = ( select Count(Distinct Sal)
From emp B
Where A.Sal <= B.Sal);
2. WQD 4th min hiredate
Select hiredate
From emp A
Where 4 = ( select Count(Distinct hiredate)
From emp B
Where A.hiredate >= B.hiredate);
Page 79
SQL (STRUCTURED QUERY LANGUAGE)
Page 80
SQL (STRUCTURED QUERY LANGUAGE)
Page 81
SQL (STRUCTURED QUERY LANGUAGE)
• SQL refers to the Standard Query Language, which is not actually the programming language.
• SQL doesn't have a loop, Conditional statement, logical operations, it cannot be used for anything other
than data manipulation.
• It is used like commanding (Query) language to access databases. The primary purpose of SQL is to
retrieve, manipulate, update and perform complex operations like joins on the data present in the database.
RDBMS is one of the most often used databases due to its easy accessibility and supports regarding complex
queries.
• Normalization is mainly used to add, delete or modify a field that can be made in a single table.
• The primary use of Normalization is to remove redundancy and to remove the insert, delete and update
distractions.
• Normalization breaks the table into small partitions and then link them using different relationships so
that it will avoid the chances of redundancy.
o The occurrence of redundant terms in the database which causes the waste of the space in the disk.
o Due to redundant terms inconsistency may also occur id any change will be made in the data of one
table but not made in the same data of another table then inconsistency will take place, which will
lead to the maintenance problem and effects the ACID properties as well.
Page 82
SQL (STRUCTURED QUERY LANGUAGE)
o Inconsistent dependency refers to the difficulty of accessing particular data as the path to reach the data
may be missing or broken. Inconsistent dependency will leads users to search the data in the wrong table
which will afterward give the error as an output.
o Denormalization is used to access the data from higher or lower normal form of database. It also
processes redundancy into a table by incorporating data from the related tables. Denormalization adds
required redundant term into the tables so that we can avoid using complex joins and many other
complex operations. Denormalization doesn’t mean that normalization will not be done, but the
denormalization process takes place after the normalization process.
o SQL or Structured Query Language is a language which is used to communicate with a relational database.
It provides a way to manipulate and create databases. On the other hand, MySQL and Microsoft's SQL
Server both are relational database management systems that use SQL as their standard relational
database language.
o MySQL is available for free as it is open source whereas SQL server is not an open source software.
1) SQL or Structured Query Language is a PL/SQL is a dialect of SQL which is used to enhance the
language which is used to capabilities of SQL. It was developed by Oracle Corporation
communicate with a relational in the early 90's. It adds procedural features of
database. It provides a way to programming languages in SQL.
manipulate and create databases.
2) In SQL single query is being executed PL/SQL a whole block of code is executed at once.
at once.
3) SQL is like the source of data that we PL/SQL provides a platform where the SQL the SQL data
need to display. will be shown.
Page 83
SQL (STRUCTURED QUERY LANGUAGE)
4) SQL statement can be embedded in PL/SQL statement cannot be embedded in SQL as SQL do
PL/SQL. not support any programming language and keywords.
o Yes. You can use the column alias in the ORDER BY instead of WHERE clause for sorting.
1. There is a built-in function in SQL called GetDate() which is used to return the current timestamp.
Most commonly used SQL joins are INNER JOIN and LEFT OUTER JOIN and RIGHT OUTER JOIN.
Joins are used to merge two tables or retrieve data from tables. It depends on the relationship between tables.
1. Theta join
2. Natural join
3. Equijoin
The BETWEEN operator is used to display rows based on a range of values. The values can be numbers, text,
and dates as well. BETWEEN operator gives us the count of all the values occurs between a particular range.
Page 84
SQL (STRUCTURED QUERY LANGUAGE)
The IN condition operator is used to check for values contained in a specific set of values. IN operator is used
when we have more than one value to choose.
Constraints are the rules and regulations which are applied to the table column which enforces yours to store
valid data and prevents users to store irrelevant data. There are two levels :
15) What is the difference between DELETE and TRUNCATE statement in SQL?
The main differences between SQL DELETE and TRUNCATE statements are given below:
2) We can use WHERE clause in We cannot use WHERE clause with TRUNCATE
DELETE command.
3) DELETE statement is used to delete TRUNCATE statement is used to remove all the
a row from a table rows from a table.
4) DELETE is slower than TRUNCATE TRUNCATE statement is faster than DELETE statement.
statement.
5) You can rollback data after using It is not possible to rollback after using TRUNCATE
DELETE statement. statement.
ACID property is used to ensure that the data transactions are processed reliably in a database system.
Page 85
SQL (STRUCTURED QUERY LANGUAGE)
Atomicity: it requires that each transaction is all or nothing. It means if one part of the transaction fails, the
entire transaction fails and the database state is left unchanged.
Consistency: the consistency property ensure that the data must meet all validation rules. In simple words you
can say that your transaction never leaves your database without completing its state.
Isolation: this property ensure that the concurrent property of execution should not be met. The main goal of
providing isolation is concurrency control.
Durability: durability simply means that once a transaction has been committed, it will remain so, come what
may even power loss, crashes or errors.
17) What is the difference between NULL value, zero and blank space?
Ans: A NULL value is not the same as zero or a blank space. A NULL value is a value which is 'unavailable,
unassigned, unknown or not applicable.' On the other hand, zero is a number, and a blank space is treated as a
character.
The NULL value can be treated as unknown and missing value as well, but zero and blank spaces are different
from the NULL value.
Functions are the measured values and cannot create permanent environment changes to SQL server. SQL
functions are used for the following purpose:
The DISTINCT keyword is used to ensure that the fetched value is only a non-duplicate value. The DISTINCT
Page 86
SQL (STRUCTURED QUERY LANGUAGE)
keyword is used to SELECT DISTINCT, and it always fetches different (distinct) from the column of the table.
21) What is the difference between DROP and TRUNCATE statement in SQL?
1) DROP is used to delete the table TRUNCATE is used to delete all the records present in a
permanently. table permanently.
22) What is the difference between WHERE CLAUSE and HAVING CLAUSE statement in SQL?
4) In where clause we can write any We should write the C.N which is present in group by
of the C.N clause.
5) Where clause will filter the record It will filter the record after grouping.
before grouping.
6) We can write where clause without We can’t write having clause without writing / using group
writing / using group by clause. by clause.
Page 87
SQL (STRUCTURED QUERY LANGUAGE)
Page 88
SQL (STRUCTURED QUERY LANGUAGE)
Page 89
SQL (STRUCTURED QUERY LANGUAGE)
Page 90
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner