SQL Notes 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 101

SQL

(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.

2. SCHEMA: The collection of a tables in a database is known as schema.

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)

5. DBMS ( DATABASE MANAGEMENT SYSTEM):


➢ DBMS is a software which is used to store data and manage the data.
➢ A combination of database and management services is called as DBMS.
➢ Management services like inserting or adding new data, modifying or
updating older data with newer data, deleting unwanted data, fetching or
retrieving data.
➢ DBMS will allow for single users.
➢ DBMS is preferred for small scale organization.
➢ DBMS will not support normalization.
➢ In DBMS software, Data will be stored in a form of files with a different
extension so it is not possible to establish a relationship between the files or
data.
➢ DBMS software are FoxPro, FoxBASE, and dbase.

Page 3
SQL (STRUCTURED QUERY LANGUAGE)

6. RDBMS ( RELATIONAL DATABASE MANAGEMENT SYSTEM):


➢ RDBMS is an advanced version of DBMS.
➢ RDBMS is a software which is used to store data and manage the data.
➢ If any DBMS software as to be qualified as RDBMS software then it should
support E.F Codd principles / rules :
1. Each and every cell in a table should consist of single value.
2. If we are having huge volume of data then we should store it in different
tables and establish a relationship between the tables.
➢ RDBMS will allow for multiple users.
➢ RDBMS is preferred for large organization.
➢ RDBMS will support normalization.
➢ RDBMS software is having enhanced security, good performance and we
can store huge volume of data compare to DBMS.
➢ In RDBMS software, Data will be stored in the form of tables so we can
establish a relationship between the tables.
➢ RDBMS software are
1. Oracle → 2i (internet)………9i, 10g (grid computing)……….11g,
12c……….18c, 19c (cloud computing) (paid & Licensed version –Feb
2019).
2. MySQL 3. Mongo dB 4. Db2 5. Teradata
6. Sybase 7. Sql server.

DATA INTEGRITY: The process of restricting of storing wrong / invalid data in


database (tables) is called as data integrity.
Or
The process of checking correctness and accuracy of data in a database is called
as data integrity.
➢ Data integrity process will avoid of storing invalid data in database.

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)

➢ The default size is 0.


➢ The allocated memory block which are not utilized will consider as null and
we can utilize in future.
➢ Syntax : varchar (size)

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)

4). Primary key 5). Foreign key


1). Not null:
➢ Not null is a constraint given to column.
➢ If any column is assigned with not null constraint then that column will not
accept null values, i.e. it is a compulsorily or mandatory to enter the same
data.
➢ Which column or attribute will assign constraint as not null.
➢ If a column or attribute is a mandatory or compulsorily for a table or entity
for those column will assign a constraint as not null.

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)

➢ If a column or attribute is a mandatory and that column should not accept


duplicates values , i.e. a combination of not null and unique constraints,
those column are eligible to become primary key.
Characteristics of primary key:
➢ Primary key is a combination of not null and unique constraints.
➢ If any column is assigned with a constraint as primary key then that column
will not accept both null value and duplicate values.
➢ In a table only one column is assigned as primary key constraint but more
than one column can eligible to become a primary key.
➢ Primary key is not a mandatory but it is highly recommended.
➢ If a table is consist of primary key then the table is a strong entity or strong
table.
➢ If a table is not consist of primary key then the table is a weak entity or
weak table.
➢ The column which are eligible to become a primary key is called candidate
key.
➢ The column which are eligible to become a primary key but not chosen as a
primary key is called alternative key.
pk
empno ename Job Sal mob Dob
Not null Not null Not null * Not null Not null
Unique * * * unique *

5). Foreign key:


➢ Foreign key is a referential integrity constraint a column which belongs to
another table is called as foreign key.
➢ Why we will use foreign key.
➢ To establish a relationship between the tables we will use foreign keys.
“relationship is known for works for”.
Characteristics of foreign key:
➢ If a column is consist of foreign key is called as child / slave table.
➢ A foreign key which actually belongs to the table is called as parent /
master table.

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:

SELECT * / [distinct] / C.N’s / Expression --- 2

Page 9
SQL (STRUCTURED QUERY LANGUAGE)

FROM table _name; ----- 1


Characteristics of from clause:
➢ In from clause we will specify table name.
➢ In from clause we will specify multiple table name.
➢ From clause is used to select complete table for query execution.
Characteristics of select clause:
➢ Select statement is used to fetching or retrieving or accessing a data from a
specific table by selecting all columns or specified number of columns.
➢ Select statement will execute row by row or record by record.
➢ Select statement is responsible to prepare an output or result set. ✓ Select
statement will prepare output in a form of tables.
2). Selections:
➢ Fetching or retrieving or accessing a data from a specific table by selecting
all columns or specified number of columns and specified number of rows
is called as selection.
➢ In selection we can restrict columns and we can restrict rows.
Syntax:

SELECT * / [distinct] / C.N’s / Expression ---- 3


FROM table _name ----- 1
WHERE <Conditions>; ----2
Characteristics of where clause:
➢ Where clause is used to filter the record.
➢ Where clause will select the record and reject the record.
➢ Where clause will execute row by row or record by record.
➢ If the specified condition is true Where clause it will retain the record else it
will reject the record.
➢ In Where clause we will specify condition.
Syntax:
LHS value Relational operator RHS value
(C.N’s / Exp) (>,<,<=,>=,==,!=,< >) (numbers, date, characters)

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:

• Create table dept( Deptno number(5) primary key,


Dname varchar(20) not null, Loc varchar(20) );
• Crete table emp(
Empno number(4) primary key, Ename varchar(20) not null, Job number(4) , Mgr
number(4), Hiredate date, Sal number(7,2), comm number(7,2), deptno
number(5), constraint deptno_fk foreign key(deptno) references dept(deptno));
2). Alter: Alter statement is used to modify the table structure .

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 ;

3. Data Manipulation Language (DML):


1. INSERT 2. UPDATE 3. DELETE
1).Insert: Insert statement is used to add a record in a table.
Syntax: Insert into tablename values(v1,v2,v3..); or
Insert into tablename (col1,col2,.) values(v1,v2);
Example: Insert into table emp values(1,’virat’,’cricketer’,’india’,31);
2).Update: update statement is used to modify the records present in a table.
Syntax: Update tablename

Set col1=val1,col2=val2…
Where <condn>;
Example: update table emp

Set ename=’virat Kohli’


Where empno=1;
3).Delete: delete statement is used to delete the records present in a table.
Syntax: Delete from tablename
Where <condn>;

Page 13
SQL (STRUCTURED QUERY LANGUAGE)

Example: delete table emp


Where empno=1;

4. Data Control Language (DCL):


1.GRANT 2. REVOKE
1).Grant: It is used to give permissions to the user.
Syntax: Grant sql statements on tablename to username;
Example: -- login as Scott user
- Select * from regions;
- Table or view does not exit.
-- login as hr user
- Select * from emp;
- Table or view does not exit.
-- Grant select on regions to Scott; - grant succeeded.
-- login as Scott user

- select * from hr. regions;


2).Revoke: It is used to get back the permissions from the user.
Syntax: Revoke sql statements on tablename from username;
Example: -- login as hr user

- Revoke select on regions from Scott; - revoke succeeded.


-- login as Scott user
- select * from hr. regions;
- Table or view does not exit.
5. Transaction Control Language (TCL):

Page 14
SQL (STRUCTURED QUERY LANGUAGE)

1. ROLLBACK 2. COMMIT 3. SAVEPOINT


1). Rollback: rollback statement is used to undo the DML changes .
Syntax: Rollback;
Example: select * from emp;
Emp | Ename
10 | virat Kohli
20 | Rakesh
--- Rollback; rollback completed.
--- no rows selected.
2). Commit: Commit statement is used to save the DML changes
Syntax: Commit;
Example: select * from emp;
Emp | Ename
10 | virat Kohli
20 | Rakesh
--- commit; → commit completed.
3). Savepoint: Save point statement is used to mark the position in db.
Which helps the rollback statement to roll back to the particular position.
Syntax: Savepoint savepointname;
Syntax: Rollback to savepoint_name;
Example: select * from emp;
Emp | Ename
10 | virat Kohli
20 | Rakesh

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.

Syntax: upper (‘string’ /C.N)


Example: select upper (ename) from dual;
--- VIRAT KOHLI
2). Lower function(): lower function will convert given string into lower case.

Syntax: lower (‘string’ /C.N)


Example: select lower (ename) from dual;
--- virat Kohli
3). Initcap function(): Initcap function will convert given string into Initcap case (
initial letter capital) .

Syntax: Initcap (‘string’ /C.N)


Example: select Initcap (ename) from dual;
--- Virat Kohli
EXPRESSIONS
Expressions is a combination of operands and operators.

Page 17
SQL (STRUCTURED QUERY LANGUAGE)

An Expression is a statement will generate or result set.

Operators:

1). Arithmetic operator ( +,-, *, / )

2). Logical operator (AND , OR , NOT)

3). Relational operator (<,>,<=,>=,==,!=,< >)


Operands: operands are classified into two types
1). Immediate or direct value
Example: 10 – 20
2). Variable or identifiers
Example: int a=10,b=20 c=a*b;
LITERALS: literals are the Immediate or direct value which is given to any of the
sql statements.
1). Number literals: It is the Immediate or direct value which is of type number
given to any of the sql statements.

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.

Syntax: Select Distinct C.N’s / Expression ---- 2


From tablename ; ------ 1
Example: WQD Sal of all the employees.
Select Distinct Sal
From emp;
ORDER BY CLAUSE: Order by clause is used to sort a record in ascending order
or descending order.
➢ Order by clause is used to display output or result set in ascending order or
descending order.
➢ Order by clause should be the last statement in the query.
➢ Whenever we want to display output in ascending order we will use a
keyword called asc and it is not compulsorily ,because by default order by
clause it will display the output in ascending order.
➢ Whenever we want to display output in descending order it is a
compulsorily to use a keyword called desc.
Syntax: Select Distinct C.N’s / Expression ---- 2
From tablename ; ------ 1
Order by [asc] / desc; --- 3

Page 19
SQL (STRUCTURED QUERY LANGUAGE)

Example: WQD Sal in asc / desc order of all the employees.


Select Sal
From emp
Order by Sal [asc] / desc;
Specifying Multiple Conditions In Where Clause:
Whenever we want to use Specifying Multiple Conditions in a single
Where Clause we should use operators
Operators: 1). Arithmetic operator ( +,-, *, / )
2). Relational operator (<,>,<=,>=,==,!=,< >)
3). Concatenation operator (||)
4). Logical operator (AND , OR , NOT)
5). Special operator ( In, Between, Like , Is)
Concatenation operator ( || ): ( pipeline operator )
Concatenation or combining or merging more than 2 strings we will use
Concatenation operator.

Syntax: ‘String1’ / C.N1 | | ‘String2’ / C.N2……….

Example: Select ‘Royal’ | | ‘Challengers’ | |’ Bangalore’ from dual;


Output : Royal challengers Bangalore
Logical operator (AND , OR , NOT)
1). AND OPERATOR: When the given conditions are mandatory to execute we
will use AND operator.

Syntax: Where cond1 AND cond2 AND cond3 ……….


Truth table: Cond1 | Cond2 | output
True | True | True
True | False | False
False | True | False

Page 20
SQL (STRUCTURED QUERY LANGUAGE)

False | False | False


2). OR OPERATOR: When either of the conditions are mandatory to execute we
will use OR operator.

Syntax: Where cond1 OR cond2 OR cond3 ……….


Truth table: Cond1 | Cond2 | output
True | True | True
True | False | True
False | True | True
False | False | False
2). NOT OPERATOR: NOT operator is used to exclude the record.

Syntax: Where NOT cond1 cond2 cond3 ……….


Truth table: Input | output
True | False |
True | True |
Example: WQD employee details only the employees who are earnings
Sal in a range 1000 to 5000 and empno should be in a range 7100 to 7600 and he
should be working as salesman, analyst, president and except deptno 30.
Select *
From emp
Where (Sal >=1000 and Sal<=5000) and (empno>=7100 and empno<=7600)
and (lower(job) = ‘salesman’,’analyst’,’president’) and deptno< >30;
Special operator ( In, Between, Like , Is):
1). IN OPERATOR:
➢ In is a multi-valid operator.
➢ In operator will accept single value in LHS side and multi value in RHS side.
➢ In operator it will perform =(equal to) comparison.

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)

➢ Null is not representing either 0 or space , it is representing as nothing (no


data).
➢ Null will not consume any memory allocation.
➢ Whenever we are performing any arithmetic operation the result will be
Null.
➢ Is operator it will return true when LHS value is null value.
➢ Is operator it will return false when LHS value is not a null value.

4). LIKE OPERATOR:


➢ Like operator is used for pattern matching or wild card search.
➢ Pattern or wild card - it is a combination of ordinary characters and special
characters or meta characters.
➢ Ordinary Characters – ordinary characters which don’t have special
significance (there is no special meaning).
➢ Special characters or meta characters – special characters which has some
special significant ( there is a meaning).
➢ Special characters or meta characters has classified into 2 types
1).Percentile ( % ) – It is a special characters it will accept the characters (
alphabets, numbers, special characters except (%, _ ) at any no of time ( min – 0 ,
max -- infinity occurrences ).
2).Underscore ( - ) -- It is a special characters it will accept the characters (
alphabets, numbers, special characters except (%, _ ) at only one time ( min – 1 ,
max --1 occurrences ).

Syntax: LHS Like ‘pattern / wild card’;


Combination Of Special Operator And Not Operator

1). LHS Value NOT IN (value1,value2,value3….);


NOT IN Operator it will return true when LHS value is NOT equal to any of the
RHS value.
2). LHS Value NOT BETWEEN lower limit and upper limit;

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.

4). LHS NOT Like ‘pattern / wild card’;


NOT LIKE Operator it will return true when LHS value is NOT equal to any of
the RHS value.
FUNCTIONS:
Functions are block or set of statements it will execute whenever it is called or
invoke is called as functions.
Functions are classified as 2 types
1. user defined functions
2. built in functions or pre- defined functions
1. User defined functions: It is a functions which are developed or defined by
users based on customers requirement is called as user defined functions.
➢ All user defined functions can be change or modify when requirement
change.
➢ Sql will not support User defined functions we should use plsql, c, c++,java,
python etc. programming language.

2. Built in functions or pre- defined functions: It is a functions which is defined


when software is install is called as built in functions or pre- defined functions.
➢ All pre- defined functions cannot be change or modify .
➢ In sql we will use pre- defined functions .
➢ pre- defined functions are classified into 2 types
a. single row functions
b. multi row functions

Page 24
SQL (STRUCTURED QUERY LANGUAGE)

A. SINGLE ROW FUNCTIONS


➢ Single row functions are the functions which can accept n records as input
and it provides n records as output.
➢ In single row functions for every individual input there is a separate 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.
➢ In single row functions the no of output is directly proportional to no of
input.

B. MULTI ROW FUNCTIONS / AGGREGATE / GROUP


➢ Multi row functions will accept n records as input and it will create a group
or clusters and it will provides single row as output.
➢ By default, all multi row functions will create single row.
➢ In multi row functions the no of output is directly proportional to no of
groups or clusters.
➢ Multi row functions is classified as 5 types:
a. count ( ) b. max ( ) c. min ( )
d. sum ( ) e. avg ( )
A. COUNT ( ): It is a function used to count the no of records given to it.
Syntax: count(argument) Argument → * / C.N/ Exp
B. MAX ( ): Max ( ) function is used to obtain maximum value present in column
or expression.
Syntax: MAX(argument) Argument → * / C.N/ Exp
C. MIN ( ): Min ( ) function is used to obtain minimum value present in column or
expression.
Syntax: MIN(argument) Argument → * / C.N/ Exp
D. SUM ( ): This function used to obtain the summation of all the values present
in C.N / EXP.

Page 25
SQL (STRUCTURED QUERY LANGUAGE)

Syntax: SUM(argument) Argument → * / C.N/ Exp


E. AVG ( ): This function used to obtain the average of all the values present in
C.N / EXP.
Syntax: AVG(argument) Argument → * / C.N/ Exp

GROUP BY CLAUSE: Group by Clause is used to create a group present in table


based on references. Or group by clause will group the record present in table
based on their references.
➢ To obtain multiple record as an output from multi row function we will go
for group by clause.
➢ References - C.N / Exp in group by clause is called as references.
➢ Group by expression -- combination of C.N and multi row function in select
statement is called as Group by expression.
➢ Based on references in group by clause is classified into 2 cases or 2 types
➢ Whenever we are specifying single C.N or single references in group by
clause it will create main groups.
➢ Whenever we are specifying multiple C.N or multiple references in group
by clause it will create sub group inside main groups and it is also known as
sub grouping.
➢ When we go for group by clause.
➢ To write combination of C.N and MRF in single select statement we will use
group by clause.
➢ To create multiple groups and to obtain multiple row functions we will go
group by clause.
Syntax: Select group by Expression ---- 4
From tablename ---- 1
Where <condition> ----- 2
group by References ; ---- 3
RULES OF GROUP BY CLAUSE:

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.

3. we can’t write Multi row functions in where conditions.


4. whenever we are writing where clause followed by group by clause where
clause will execute based on their retain record, group by based on group the
record.
5. If any clause is executing after group by clause it will execute group by group
not row by row.

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.

RULES OF 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)

2. If you want to consider column condition in Having clause column name


should be present in group by clause.
QUERY : A query is a set of statement with a multiple conditions to interact with
database is called as query. Or Starting from select statement followed by
multiple conditions and terminating with semicolon ( ; ) is called as query.
SUB QUERY: A query inside another query is called as sub query or A query inside
another query is called as sub query.
sub query can be written in 2 clause

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.

TYPES OF SUB QUERY


A. Single row sub query. B. Multi row sub 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)

Case 1: To Determine Unknown Values.


Case 2: Linking multiple tables (by using primary key and foreign key).
Case 3: Mapping values, present in a same table but in different rows. (Nth max
and Nth min).
Drawback:

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

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
A. CARTESIAN JOINS / CROSS JOINS:
➢ Cartesian joins refer cross product of multiple table.
➢ Cartesian joins is working on a principle of cross product.
➢ Cross product means a value from one table with all the values present in
another table is called as cross product.
➢ In cartesian joins we will Not specify any joining condition.
➢ In cartesian joins it will result both valid and invalid (not using joining
condition).

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

Syntax of Inner join:

Oracle Syntax: Select * / C.N ---- 3


From tablename1, tablename2, … --- 1
Where < Joining condition > and < condition > ; ----2

Page 31
SQL (STRUCTURED QUERY LANGUAGE)

ANSI Syntax: Select * / C.N ---- 3


From table1 [inner] join table2, … ; ---- 1
On <joining condition> where <condition> ; ----2
Example: WQD ename, Dname of all employee
Select ename, dname
From emp, dept
Where emp.deptno=dept. deptno;

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)

D. NON - EQUI JOINS:


➢ Joining multi table without specifying ‘=’ operator in joining condition is
called non-equi joins.
➢ In non-equi joins joining condition except to operator other all relational
operator(> , < ,>= , <= ,!=) specify.
➢ When to go for non-equi Joins.
1. when there is no relational (no common C.N between the tables).
2. when there is relevant data ( C.N can be different but data type ,size should
be similar).
Example: WQD ename, Sal, grade, hisal, losal only the employees is more than
losal
Select ename, Sal, grade, hisal, losal
From emp , Salgrade
Where Sal> losal;
E. OUTER JOINS :
➢ Joining multi table by utilizing common column between the table is called
Outer join.
➢ Outer join is a combination of inner query and invalid records.
➢ Outer join will result both valid and invalid records.
➢ Valid records from all tables and invalid records from specified tables.

1. LEFT OUTER JOINS / LEFT JOINS:


➢ Left Outer join is a combination of inner joins and invalid records from left
table or
➢ Valid records from all tables and a record from left table which does not
have any matching pairs in right table is called as left outer joins.
Oracle Syntax: Select * / C.N ---- 3
From table1, table2, … --- 1
Where table1.C.N= table2.C.N ( + ); ------ 2

Page 33
SQL (STRUCTURED QUERY LANGUAGE)

ANSI Syntax: Select * / C.N ---- 3


From table1 left [outer] join table2, … ; ---- 1
On table1.C.N= table2.C.N where <condition> ; ----2

2. RIGHT OUTER JOINS / RIGHT JOINS:


➢ Right Outer join is a combination of inner joins and invalid records from
right table or
➢ Valid records from all tables and a record from right table which does not
have any matching pairs in right table is called as right outer joins.
Oracle Syntax: Select * / C.N ---- 3
From table1, table2, … --- 1
Where table1.C.N ( + )= table2.C.N; ------ 2
ANSI Syntax: Select * / C.N ---- 3
From table1 right[outer] join table2, … ; ---- 1
On table1.C.N= table2.C.N where <condition> ; ----2
3.FULL OUTER JOINS / OUTER JOINS
Full Outer join is a combination of left outer joins and right outer joins.
Oracle Syntax: Select * / C.N ---- 3

From table1, table2, … --- 1


Where table1.C.N = table2.C.N; ------ 2
union Select * / C.N ---- 3
From table1, table2, … --- 1
Where table1.C.N = table2.C.N; ------ 2

ANSI Syntax: Select * / C.N ---- 3


From table1 full[outer] join table2, … ; ---- 1
On table1.C.N= table2.C.N where <condition> ; ----2

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)

Outer query | Inner query ( joining cond )


|
Max { where N | where table1.C.N <= table2.C.N
N-1 | where table1.C.N < table2.C.N
Min { where N | where table1.C.N <= table2.C.N
N-1 | where table1.C.N < table2.C.N
Example: WQD 3rd Max salary
Select Sal
From emp a
Where 3 = (select count (distinct Sal)
From emp
where a.Sal<=b.Sal);
PSEUDO COLUMNS OR FALSE COLUMN:
➢ Pseudo column or false column which are not actually present in a table
but it will reflect in output whenever we are specifying pseudo columns in
select statements.
➢ Oracle RDBMS will support pseudo column is classified as 2 types
1). Row id 2). Row number
➢ In each and every database all tables will consists of row id and row
number ( pseudo columns)

Page 36
SQL (STRUCTURED QUERY LANGUAGE)

1). Row id:


➢ Row id is a unique and permanent value given to each and every record
present in a table.
➢ Row id represents physical address of each and every record.(physical
address means database name, table name , column name).
➢ Row id is a 18 bit alphanumeric value.
➢ Row id will be automatically generated by insert statements.
➢ Row id is a static value.
2). Row number:
➢ Row num is a unique and temporary value given to each and every record
present in a table.
➢ Row num represents total number of records selected by select
statements.
➢ Row num is a sequential integer value given to each and every record
present in a table.
➢ Row num is automatically generated by select statements.
➢ Row id is a dynamic value.
➢ Top employee details / beginning details
➢ N-1 → > , N → > =
➢ Bottom employee details / last details
➢ N-1 → > , N → > =
Example: WQD top 3rd employee details.
Select *
From emp a
Where 3 = (select count (distinct rowid)
from emp b
where a.rowid>=b.rowid);

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)

Syntax: Select * / C.N


From table_name
Where <condition>
INTERSECT Select * / C.N
From table_name
Where <condition>;
Example:
Select Sal
From emp
Where deptno=20
Intersect Select Sal
From emp
Where lower(job) IN(‘clerk’, ‘analyst’);
4. MINUS Operator: This operator it will give the output a value which is not
present in another table.
A={10,x,20,y,30} B={30,40,50,x} ,,A minus B ={ 10,20,y} ,,B minus A ={ 40,50}
Syntax: Select * / C.N
From table_name
Where <condition>
MINUS Select * / C.N
From table_name
Where <condition>;
Example:
Select Sal
From emp

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)

Arg4→nth occurrence of ch or ss.(arg3 and arg4 is optional)


5.Replace: it is used to replace the old ch’s with new characters
Syntax : Replace(C .N /’String’,’old ch’,[’new ch’])
Arg3 is optional.
2.Number functions
1.Mod function: it is used to obtain the modules of a given number.
Syntax : MOD(m,n) modules mean remainder
Example: Select mod( 10,2) from dual;
----- 5 -----
2.Round function : it is used to round of the given number.
Syntax : Round(arg1)
Example: Select round(77.96) from dual;
----- 78 ----
3.trunc function: it is used to round of the given number always to the lowest.
Syntax : Trunc(arg1)
Example: Select round(77.96) from dual;
----- 77 ----
3.GENERAL FUNCTIONS
1.NVL function: it is used to handle null values
Syntax : NVL(arg1,arg2)
Arg1 is always a column name. Arg2 is always value
If arg1 is null value nvl function will return the value present in arg2
If arg1 is not a null value nvl function will return arg1 itself
Example: Select NVL(null, 10) from dual;

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)

→ Select ename, Sal, case deptno


When 20 then Sal+(Sal*0.5),
When 10 then Sal+(Sal*0.75),
Else Sal+(Sal*0.25)
End ‘new_salary’
from emp;
→ Select ename, Sal,
Decode ( Deptno, 20 , Sal+(Sal*0.5),
10 , Sal+(Sal*0.75), Sal+(Sal*0.25) as ‘new_salary’
from emp;
→ Select ename, Sal, case Sal
When Sal>2700 then ‘luxury’,
When Sal<= 2700 then ‘economy’,
End ‘status of employee’
from emp;
→ Select ename, Sal, case Sal
When Sal between 100 and 1000 then ‘poor’,
When Sal between 1001 and 2500 then ‘average’,
When Sal between 2501 and 3000 then ‘well paid’,
Else ‘richest person’
End ‘emp salary’ from emp;
4.Date functions
1.sysdate: it is used to obtain the system date where database is present.
Syntax : Sysdate;

Page 48
SQL (STRUCTURED QUERY LANGUAGE)

2.Months_between: it is used to obtain the no of months between two dates.


Syntax : Months_between(Date,Date)
3.last_day: it is used to obtain the last day of the given month in the form of date
Syntax : Last_day(Date)
4.extract :it is used to extract the components of date
Syntax : Extract(Day/month/year from date)
5.Conversion function
→ Converting a value from one type to another type is called conversion.
→ two types –
→Implicit : Converting a value from one time to another time is called implicit
conversion.
Example : select 10 + ‘10’ from dual;
→Explicit : Converting a value from one time to another time explicitly by usiung
conversion function is called explicit conversion.
To number converts characters value into number value
Example : select 10 + to_number (‘10’) from dual;
➔ select 10 + ASCII (‘A’) from dual; --- 75
➔ select 10 + ASCII (‘D’) from dual; --- 78
1.to_char()
It is used to convert the date format to character format.
Syntax : To_char(date, ‘Format models’)
The format models are
DD, d, day, dy mm, mon, month, yy, year, yyyy
➔ select to-char (sysdate ,’year’ month day dd’) from dual;
➔ twenty twenty January Sunday 06

Page 49
SQL (STRUCTURED QUERY LANGUAGE)

Various Syntax in SQL


➔ SELECT Statement
SELECT * / C.N’s / Exp
FROM table_name;

➔ 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 ;

➔ LEFT OUTER JOIN


SELECT * / C.N
FROM table1, table2….
Where table1.CN=table2.CN ( +) ;

➔ RIGHT OUTER JOIN


SELECT * / C.N
FROM table1, table2….
Where table1.CN (+ )=table2.CN ;

➔ FULL OUTER JOIN


SELECT * / C.N
FROM table1, table2….
Where table1.CN=table2.CN ( +) ;
UNION
SELECT * / C.N
FROM table1, table2….

Page 52
SQL (STRUCTURED QUERY LANGUAGE)

Where table1.CN (+) =table2.CN ;

➔ 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)

Purge table table_name;

➔ 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

Name Null? Type


-------------------------------- -------- ----------------------
EMPNO NOT NULL NUMBER(5)
ENAME VARCHAR2(0 CHAR)
JOB VARCHAR2( CHAR)
MGR NUMBER(4)
HIREDATE DATE
SAL NUMBER(7,2)
COMM NUMBER(7,2)
DEPTNO NUMBER(4)

Department table

Name Null? Type


-------------------------------- -------- ----------------------
DEPTNO NOT NULL NUMBER(24)
DNAME VARCHAR2(20 CHAR)
LOC VARCHAR2(20 CHAR)

Sal grade table

Name Null? Type


-------------------------------- -------- ----------------------
GRADE NOT NULL NUMBER
LOSAL NUMBER
HISAL NUMBER

Page 55
SQL (STRUCTURED QUERY LANGUAGE)

Questions on sql basics


1. Write a Query to display name of the employee.
Select ename
From emp;
2. Write a Query to display ename and salary of all employee.
Select ename , Sal
From emp;
3. Write a Query to display department name and its location for all the
department.
Select dname, loc
From dept;
4. Write a Query to display name, salary, commission and date of joining of every
employee.
Select ename, Sal , comm, hiredate
From emp;
5. Write a Query to display employee name, his designation and his manager’s
employee number.
Select ename, job, mgr
From emp;
6. Write a Query to display employee name and his department number.
Select ename, deptno
From emp;
7. Write a Query to display all the details of each and every employee of the
company.
Select *
From emp;
8. Write a Query to display all the details of department present in company.

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)

Where Sal * 12 > 10000;


15. Write a Query to display all the details of employee if the department number
is 20.
Select *
From emp
Where deptno=20;
16. Write a Query to display all the details of the employee if designation is
Manager.
Select *
From emp
Where lower(job) = ‘manager’;
17.Write a Query to display all the details of employee only if they were hired
after the year 1995.
Select *
From emp
Where hiredate>’01-jan-1995’ ;
18. Write a Query to display all the details of employee only if his designation is
clerk.
Select *
From emp
Where lower(job) = ‘clerk’
19. Write a Query to display depart name, depart number for all the department
which is located in BOSTON.
Select dname ,deptno
From dept
Where lower(loc) = ‘Boston’

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)

14. Write A Query To Display Number Of Employees Having Commission In Dept


30?
Select Deptno, Count(*)
From Emp
Where Comm Is Not Null
Group By Deptno
Having Deptno=30;

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;

19. Display Department Wise, Number Of Manager.


Select Deptno, Count(*)
From Emp
Where 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)

Having count (*));


2. list the department names which has employees.
Select dname
From dept
Where deptno In (Select deptno
From emp
Group by deptno
Having count (*) > 0);
3. display the employees whose location is having at least one ‘o’ in it.
Select *
From emp
Where deptno In (Select deptno
From dept
Where lower(loc) like ‘%o’);
4. list the department names that are having at least 1 employee in it.
Select dname
From dept
Where deptno In (Select deptno
From emp
Group by deptno
Having count(*)>=1);
5. list the department names that are having at least 4 employees in it
Select dname
From dept

Page 68
SQL (STRUCTURED QUERY LANGUAGE)

Where deptno In (Select deptno


From emp
Group by deptno
Having count(*)>=4);
6. display the department names which are having at least 2 clerks in it
Select dname
From dept
Where deptno In (Select deptno
From emp
Where lower(job)= ‘clerk’
Group by deptno
Having count(*)>=2);
7. query to display the employee names who is having maximum salary in dept
name "accounting".
Select ename, max(Sal)
From emp
Where deptno In (Select deptno
From dept
Where lower(dname)= ‘accounting’);
8. query to display all the employees in 'operations and accounting' dept. list the
employees who has salary greater than miller
Select *
From emp
Where Sal = (Select Sal
From emp

Page 69
SQL (STRUCTURED QUERY LANGUAGE)

Where lower(ename)= ‘ miller’) and deptno In (Select deptno


From dept
Where lower(dname) In (’Accounting’, ‘operations’));
9. select all the employees who are working for Chicago.
Select *
From emp
Where deptno In (Select deptno
From dept
Where lower(loc)= (’Chicago’));
10. query to display employee names who is having minimum salary in
department research
Select ename, min(Sal)
From emp
Where deptno In (Select deptno
From dept
Where lower(dname) = (’research’));
11. list the department names that are having at least 3 employes in it.
Select dname
From dept
Where deptno In (Select deptno
From emp
Group by deptno
Having count(*)>=3);
12. list employees from research and accounting department having atleast two
reporting

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)

Where hiredate < ( select max(hiredate)


From emp
Where hiredate < ( select max(hiredate)
From emp ));
4. display the 2nd minimum hiredate
Select min(hiredate)
From emp
Where hiredate > ( select min(hiredate)
From emp ));
5. display the 3rd maximum comm
Select max(comm)
From emp
Where comm < ( select max(comm)
From emp
Where comm < ( select max(comm)
From emp ));
6. display the 2nd minimum comm
Select min(comm)
From emp
Where comm > ( select min(comm)
From emp ));
7. display dname, those who are earning 3rd maximum comm
Select dname
From dept

Page 72
SQL (STRUCTURED QUERY LANGUAGE)

Where comm = (Select max(comm)


From emp
Where comm < ( select max(comm)
From emp
Where comm < ( select max(comm)
From emp )));
8. display ename, job those who are earning 3rd maximum Sal
Select ename , job
From emp
Where Sal = (Select max(Sal)
From emp
Where Sal < ( select max(Sal)
From emp
Where Sal < ( select max(Sal)
From emp )));
9. select ename, dname of employee who earns 2nd max salary and works for
location Dallas.
Select ename, max(Sal)
From emp
Where Sal = (Select max(Sal)
From emp
Where deptno In (Select deptno
From dept
Where lower(loc)=’Dallas’));

Page 73
SQL (STRUCTURED QUERY LANGUAGE)

2 : Mapping values into same table but in different rows


1. display Scott manager’s manager’s department name
Select ename as mgr_name
From emp
Where empno = (Select mgr
From emp
Where empno = (Select mgr
From emp
Where lower(ename)= ‘ Scott’));
2. list all the deptname and loc of all the salesman manager-manager's
Select dname , loc
From dept
Where deptno In (Select deptno
From emp
Where empno = (Select mgr
From emp
Where empno = (Select mgr
From emp
Where lower(job)= ‘ Salesman’));
3. display location of all the employees who reporting to Blake
Select loc
From dept
Where deptno In (Select deptno
From emp

Page 74
SQL (STRUCTURED QUERY LANGUAGE)

Where mgr = (Select empno


From emp
Where lower(ename)= ‘ Blake’));
4. list all the employees who are reporting to jones manager
Select *
From emp
Where mgr = (Select empno
From emp
Where lower(ename)= ‘ jones’);
5. display martin's manager's manager's department location.
Select loc
From dept
Where deptno In (Select deptno
From emp
Where mgr = (Select empno
From emp
Where lower(ename)= ‘ martin’));
6. write a query to find smith's manager's manager hiredate.
Select hiredate as mgr_hiredate
From emp
Where empno = (Select mgr
From emp
Where empno = (Select mgr
From emp

Page 75
SQL (STRUCTURED QUERY LANGUAGE)

Where lower(ename)= ‘ smith’));


JOINS QUESTIONS:
INNER JOINS:
1. List ename, job, annual Sal, deptno, dname who earn 30000 per year and who
are not clerks
Select ename, job, Sal*12 as annsal , deptno, dname
From emp , dept
Where emp.deptno = dept. deptno and Sal *12 =30000 and lower(job)!=’clerks’;
2. Display Dept name of the employee who earn min salary and have no reporting
manager.
Select dname, min(Sal)
From emp , dept
Where emp.deptno = dept. deptno and mgr is null;
3.Display employee name and department name for each employee
Select ename, dname
From emp , dept
Where emp.deptno = dept. deptno;
4. Display location name of the employee who earn commission.
Select loc
From emp , dept
Where emp.deptno = dept. deptno and comm is not null;
5. Display Dept name, loc of all the employees who are reporting to Smith.
Select deptname, loc, mgr
From emp , dept
Where emp.deptno = dept. deptno and lower(ename)=’smith’;

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)

Select city, country_id


From Countries C, Locations L
Where L.country_id = C.country_id ;
12. Display all Regions and their respective Countries and Cities.
Select city, C.* , R.*
From Countries C, Locations L, Regions R
Where L.country_id = C.country_id and R.region_id = C.region_id;
13. Display all Regions, Countries and Cities which are not belongs to Europe.
Select city, C.* , R.*
From Countries C, Locations L, Regions R
Where L.country_id = C.country_id and R.region_id = C.region_id and
lower(city) <> ‘Europe’;
14. Display the region name of India.
Select C.* , R.*
From Countries C, Regions R
Where R.region_id = C.region_id and lower(region_name)=’India’;
15. Display all the Countries along with their Cities and also the countries doesn't
have Cities.
Select city, C.*
From Countries C, Locations L
Where L.country_id = C.country_id and cities is null ;

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)

SQL Interview Questions


1. What is sql.
2. What are tables in sql.
3. What are the different statements in sql.
4. What is distinct clause and why it is used.
5. What are the different clauses used in sql.
6. What are constraints and why we use.
7. What are joins, explain types with example.
8. How many aggregate functions are available in sql and name them.
9. What is view in sql.
10.How we can update the view.
11.Explain the working of sql privileges.
12.What is the difference between sql and plsql.
13.What is the use of nvl function
14.What is the Cartesian product of a table.
15.What do you mean by subquery.
16.How many row comparison operators are used while working with sub
query.
17.Difference between delete and truncate.
18.Difference between drop and truncate.
19.What is normalization explain.
20.What is the syntax to add a record to a table.
21.What is the syntax to add a column to a table.
22.Define delete statement in sql.
23.Define commit.
24.What is primary key and foreign key.
25.Is it possible to have more than one foreign key in a table.

Page 80
SQL (STRUCTURED QUERY LANGUAGE)

26.Can u rename a column in the output of sql query.


27.What do you mean by Rowid.
28.Define union, minus, a union all and intersect.
29.What is difference between unique key and primary key.
30.How can you avoid duplicate records in result set.
31.Explain the difference between rename and alias.
32.Difference between where and having clause.
33.List the special operators.
34.Which command is used to get back the privileges offered by the grant
command.
35.Which operator tests column for the absence of data.
36.What are the special characters or wildcards used for pattern matching.
37.Difference between substr and Instr.
38.Which is the fastest way accessing a row or record in a table.
39.What is schema.(collection of database objects of a user.
40.What are self joins and why we go self joins.
41.What does rollback and savepoint do.
42.What is a null.
43.Difference between union and union all.
44.Which are the different statements in DDL.
45.What is the difference between unique and distinct.
46.What is rownum .
47.What is the main role of primary key in a table.
48.Difference between char and varchar2.
49.What is difference between null,0 and space.
50.Is where clause should appear always before the group by clause? yes or
no.
51.Describe conversion functions.
52.Which statement is used to drop a column in a table.
53.What is case function.
54.What is composite primary key.

Page 81
SQL (STRUCTURED QUERY LANGUAGE)

1) Does SQL support programming?

• 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.

2) What are the different types of database management systems?

There are four types of database:

o Hierarchical databases (DBMS)


o Relational databases (RDBMS)
o Network databases (IDMS)
o Object-oriented databases+

RDBMS is one of the most often used databases due to its easy accessibility and supports regarding complex
queries.

3) What is the primary use of Normalization?

• 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.

4) What are the disadvantages of not performing Database Normalization?

The major disadvantages are:

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.

5) What is an inconsistent dependency?

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.

6) What is Denormalization in a Database?

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.

7) What is the difference between SQL, MySQL and SQL Server?

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.

8) What is the difference between SQL and PL/SQL?

No. SQL PLSQL

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.

9) Is it possible to sort a column using a column alias?

o Yes. You can use the column alias in the ORDER BY instead of WHERE clause for sorting.

10) What is the SQL query to display the current date?

1. There is a built-in function in SQL called GetDate() which is used to return the current timestamp.

11) Which are the most commonly used SQL joins?

Most commonly used SQL joins are INNER JOIN and LEFT OUTER JOIN and RIGHT OUTER JOIN.

12) What are the different types of joins in SQL?

Joins are used to merge two tables or retrieve data from tables. It depends on the relationship between tables.

Following are the most commonly used joins in SQL:

Inner Join: inner joins are of three type:

1. Theta join
2. Natural join
3. Equijoin

Outer Join: outer joins are of three type:

1. right outer join


2. Left outer join
3. Full outer join

13) What is the difference between BETWEEN and IN condition operators?

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.

14) What is a constraint? Tell me about its various levels.

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 :

1. column level constraint


2. table level constraint

15) What is the difference between DELETE and TRUNCATE statement in SQL?

The main differences between SQL DELETE and TRUNCATE statements are given below:

No. DELETE TRUNCATE

1) DELETE is a DML command. TRUNCATE is a DDL command.

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.

16) What is ACID property in a database?

ACID property is used to ensure that the data transactions are processed reliably in a database system.

A single logical operation of a data is called transaction.

ACID is an acronym for Atomicity, Consistency, Isolation, Durability.

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.

18) What is the usage of SQL functions?

Functions are the measured values and cannot create permanent environment changes to SQL server. SQL
functions are used for the following purpose:

o To perform calculations on data


o To modify individual data items
o To manipulate the output
o To format dates and numbers
o To convert data types

19) Which function is used to return remainder in a division operator in SQL?

The MOD function returns the remainder in a division operation.

20) What is the usage of the DISTINCT keyword?

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?

No. DROP TRUNCATE

1) DROP is used to delete the table TRUNCATE is used to delete all the records present in a
permanently. table permanently.

2) Table structure will not retain. Table structure will retain.

3) Flashback concept is supported. Flashback concept is not supported.

4) Purge will support. Purge will not support.

22) What is the difference between WHERE CLAUSE and HAVING CLAUSE statement in SQL?

No. WHERE HAVING

1) It is a independent clause. It is a dependent clause.

2) It will execute row by row or record It will group by group.


by record.

3) We can’t write MRF. We can write MRF.

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

You might also like