Vous êtes sur la page 1sur 180

ABOUT ME

G. PRAKASH CHAKRAVARTHY. M.Tech


Experience
Software: 6 years on Oracle database
- worked in Citibank, Japan for 3 years as senior consultant.
- worked in Polaris Software Lab Limited for 3 years as Project Lead.

Teaching: 4 years
- worked in NRI Institute of Technology as Associate Professor
- 4 years of experience in training students for GATE

Area of Specialization: Database (Oracle)


Certifications:
- Oracle Certified Associate
- Microsoft Certified Professional on Windows 2003 server

Subjects handled in GATE:-DBMS, CN, and OS


- Trained 200+ batches for GATE.
Introduction

DBMS Syllabus
SNO NAME OF THE TOPIC
1 E-R Model & Relational Model
2 SQL [Structured Query Language]  2 Marks
3 Relational Algebra & Tuple Calculus 1 (or)2 Marks
4 Normalization [Schema Refinement]  2 Marks
5 Transaction Management
6 Concurrency Control  2 Marks
7 File Organization & Indexing  1 (or)2 Marks

Weight age = 8 Marks


Introduction

Any Queries
You can reach me at :
Mail :- prakashchakrarvarthyg@yahoo.com
Mobile :- 91-9866474747
Introduction

DBMS Syllabus
SNO NAME OF THE TOPIC
1 E-R Model & Relational Model
2 SQL [Structured Query Language]
3 Relational Algebra & Tuple Calculus
4 Normalization [Schema Refinement]
5 Transaction Management
6 Concurrency Control
7 File Organization & Indexing
Structured Query Language [SQL]
1) UNDERSTANDING THE BASICS OF TABLE
2) PARENT TABLE (VS) CHILD TABLE
3) BASIC SELECT STATEMENT
4) OPERATORS IN SQL
5) NULL
6) SINGLE-ROW FUNCTIONS
7) MULTI-ROW FUNCTIONS [GROUP FUNCTIONS]
8) SET OPERATORS
9) PATTERN MATCHING
10) JOINS
11) NESTED SUB QUERIES
12) CORRELATED SUB QUERIES
13) DML STATEMENTS
14) DDL STATEMENTS
15) DCL STATEMENTS
16) TCL STATEMENTS
17) VIEWS
4 Types of GATE
Questions in SQL
Query Table Output
Table with ROWS are given

TYPE : 1 GATE 2011: 2 Marks

Database table by name Loan_Records is given below.


What is the output of the following SQL query?

SELECT Count(*)
FROM ( a) 3
(SELECT Borrower, Bank_Manager
FROM Loan_Records) AS S b) 9
NATURAL JOIN
(SELECT Bank_Manager,Loan_Amount c) 5
FROM Loan_Records) AS T
d) 6
);
Query Table Question for Query ?
Sample Rows to be Populated NO ROWS are given for the Table

TYPE : 2 GATE 2014 SET:3  2 Marks


Consider the following relational schema:
employee(empId, empName, empDept)
customer(custId, custName, salesRepId, rating)
salesRepId is a foreign key referring to empId of the employee relation. Assume that each
employee makes a sale to at least one customer. What does the following query return?
SELECT empName
FROM employee E
WHERE NOT EXITS (SELECT custId
FROM customer C
WHERE C.salesRepId = E.empId
AND C.rating <> ‘GOOD’);

a) Names of all the employees with at least one of their customers having a ‘GOOD’ rating.
b) Names of all the employees with at most one of their customers having a ‘GOOD’ rating.
c) Names of all the employees with none of their customers having a ‘GOOD’ rating.
d) Names of all the employees with all their customers having a ‘GOOD’ rating.
GATE Previous Questions
Consider the table employee(empId, name, department,salary) and the two queries
Q1 and Q2 below. GATE 2007 : 2 Marks
Assuming that department 5 has more than one employee, and we want to find the
employees who get higher salary than anyone in the department 5, which one of
the statements is TRUE for any arbitrary employee table?
Q1:- SELECT e.empId
FROM employee e
WHERE not exists (SELECT *
TYPE : 3
FROM employee s
WHERE s.department=5 and s.salary >= e.salary);
Q2:- SELECT e.empId
FROM employee e
WHERE e.salary>ANY ( SELECT distinct salary
FROM employee s
WHERE s.department=5);
a. Q1 is the correct query
b. Q2 is the correct query
Query:1 (Vs) Query:2
c. Both Q1 and Q2 produce the same answer
d. Neither Q1 nor Q2 is the correct query
GATE Previous Questions
GATE 2011 : 2 Marks
TYPE : 4
Consider a database table T containing two columns X and Y each of type integer.
After the creation of the table, one record (X=1, Y=1) is inserted in the table.

Let MX and MY denote the respective maximum values of X and Y among all records
in the table at any point in time. Using MX and MY, new records are inserted in the
table 128 times with X and Y values being MX+1, 2*MY+1 respectively.

It may be noted that each time after the insertion, values of MX and MY change.
What will be the output of the following SQL query after the steps mentioned above
are carried out?

a) 127
Cross Subject Question
SELECT Y FROM T WHERE X=7; b) 255
c) 129 Maths + DBMS
d) 257
Structured Query Language [SQL]
1) UNDERSTANDING THE BASICS OF TABLE
2) PARENT TABLE (VS) CHILD TABLE
3) BASIC SELECT STATEMENT
4) OPERATORS IN SQL
5) NULL
6) SINGLE-ROW FUNCTIONS
7) MULTI-ROW FUNCTIONS [GROUP FUNCTIONS]
8) SET OPERATORS
9) PATTERN MATCHING
10) JOINS
11) NESTED SUB QUERIES
12) CORRELATED SUB QUERIES
13) DML STATEMENTS
14) DDL STATEMENTS
15) DCL STATEMENTS
16) TCL STATEMENTS
17) VIEWS
Understanding the basics of TABLE
TABLE Definition Data
Definition

Set of Columns Values for those columns


Data

What Column consists of


?
1. Column Name Name of the Column [Max = 30 characters]
2. Column Data Type number, char, varchar, date, Boolean, e.t.c
3. Size of the Data Type Number(20), char(30)
4. Default Value
Avoids NULL values for the particular column
5. Constraints [5]
1. NOT NULL
2. UNIQUE
3. PRIMARY KEY Represents BUSINESS Rules
4. CHECK
5. FOREIGN KEY
EMPLOYEE CHECK (salary > 0) DEPARTMENT
NULL Value ? NO NO YES YES YES

Duplicates ? NO YES NO YES YES

PRIMARY KEY NOT NULL UNIQUE CHECK FOREIGN KEY Parent Column
Child Column

× × ×
×
× ×
UNIQUE Column  Accepts Multiple NULL Values Match the following
CHECK CONSTRAINT EMPLOYEE CONSTRAINTS
CHECK Column  Accepts Multiple NULL Values 1) empID 1) NOT NULL
2) empName 2) UNIQUE
CHECK  Won’t accept if condition fails [salary > 0] 3) PassportNo 3) PRIMARY KEY
4) Salary 4) FOREIGN KEY
FOREIGN KEY CONSTRAINT
5) deptId 5) CHECK
FOREIGN KEY Column  Accepts Multiple NULL Values
FOREIGN KEY Column  Won’t accept if values NOT in PARENT.
Will it accepts NULL Values ? NO
NOT NULL
Will it accepts DUPLICATE Values ? YES

Will it accepts NULL Values ? YES


UNIQUE
Will it accepts DUPLICATE Values ? NO

Will it accepts NULL Values ? NO


PRIMARY KEY
Will it accepts DUPLICATE Values ? NO

Will it accepts NULL Values ? YES


FOREIGN KEY
Will it accepts DUPLICATE Values ? YES

Will it accepts values not in PARENT Column ? NO

Will it accepts NULL Values ? YES


CHECK
Check salary > 3000 Will it accepts DUPLICATE Values ? YES
Will it accepts values if condition fails [salary = 2000] NO
Simple Primary Key Composite Primary Key

Primary Key = { eno } Primary Key = { eno + dno }

1 allowed 1 101 allowed

1 Not allowed 1 101 Not allowed

NULL Not allowed 1 102 allowed


KEY POINTS 2 101 allowed
 No of Columns in Key = only one column
 Primary Key = eno NULL 103 Not allowed
 eno  won’t take Duplicate values
 eno  won’t take NULL values 3 NULL Not allowed

KEY POINTS OF COMPOSITE PRIMARY KEY


1. Individual columns in a Composite Key [eno, dno] wont accept NULL values.
2. Combination of columns [eno+dno] must be Unique.
3. Individual columns alone [eno, dno] can have Duplicates.
GATE Previous Questions
GATE 2014 SET:2 1 Mark

Given an instance of the STUDENTS relation as shown below:

For (StudentName, StudentAge) to be a key for this instance, the value X should NOT be
equal to_____?

1
Given an instance of the STUDENTS relation as shown below:

Ans = 19

For (StudentName, StudentAge) to be a key for this instance, the value X should NOT be equal to_____?

Key  Composite Key = (StudentName, StudentAge)

X != 19

Key Points :-
1. Individual columns in a Composite Key [eno, dno] wont accept NULL values.
2. Combination of columns [eno+dno] must be Unique.
3. Individual columns alone [eno, dno] can have Duplicates.
Understanding the basics of TABLE

1 How many primary keys can be created on a single table


? Answer = 1

2 My requirement  3 columns shouldn’t take NULL & Duplicate values.


?
empid ename PAN CARD NO AADHAR CARD NO 1 column = primary key
2 columns = Unique + NOT NULL

All 3 columns should not take NULL values and DUPLICATE values

3 Does foreign key column [child column] accepts NULL value


? YES

4 How can I avoid a foreign key column accepting NULL value


? Add NOT NULL constraint
to foreign key column

5 How can I avoid a foreign key accepting Duplicate Values ? Add UNIQUE constraint to
foreign key column
NOT NULL
UNIQUE
Can we place ALL CONSTRAINTS on a Single Table ? PRIMARY KEY
CHECK
FOREIGN KEY

CREATE TABLE employee( eno number(3) PRIMARY KEY,


ename varchar2(30) NOT NULL,
mobile number(10) UNIQUE,
salary number(7,2) CHECK (salary > 0 ),
mgr numer(3) REFERENCES employee(eno));

PARENT COLUMN CHILD COLUMN


Structured Query Language [SQL]
1) UNDERSTANDING THE BASICS OF TABLE
2) PARENT TABLE (VS) CHILD TABLE
3) BASIC SELECT STATEMENT
4) OPERATORS IN SQL
5) NULL
6) SINGLE-ROW FUNCTIONS
7) MULTI-ROW FUNCTIONS [GROUP FUNCTIONS]
8) SET OPERATORS
9) PATTERN MATCHING
10) JOINS
11) NESTED SUB QUERIES
12) CORRELATED SUB QUERIES
13) DML STATEMENTS
14) DDL STATEMENTS
15) DCL STATEMENTS
16) TCL STATEMENTS
17) VIEWS
CHILD TABLE PARENT TABLE

Child Column
Parent Column

CREATE TABLE department(deptid number PRIMARY KEY,


dname varchar2(30) NOT NULL);

CREATE TABLE emp (eno number PRIMARY KEY,


ename varchar2(30) NOT NULL,
dno number references DEPT(dno)
);

Step:1  PARENT TABLE to be Created


Step: 2  CHILD TABLE to be Created with reference to FOREIGN KEY.
CHILD TABLE PARENT TABLE

CREATE TABLE emp


(eno number PRIMARY KEY,
ename varchar2(30) NOT NULL,
dno number references DEPT(dno)
);

PARENT TABLE

Is INSERT into PARENT TABLE always Successful ? YES

Is UPDATE on PARENT TABLE always Successful ? NO

Is DELETE from PARENT TABLE always Successful ? NO Is CHILD depending on PARENT ?

CHILD TABLE Is PARENT depending on CHILD ?


Is INSERT into CHILD TABLE always Successful ? NO

Is UPDATE on CHILD TABLE always Successful ? NO

Is DELETE from CHILD TABLE always Successful ? YES


ON DELETE NO ACTION ON DELETE CASCADE ON DELETE SET NULL ON DELETE SET DEFAULT

CREATE TABLE emp CREATE TABLE emp CREATE TABLE emp CREATE TABLE emp
( ( ( (
eno number PRIMARY KEY, eno number PRIMARY KEY, eno number PRIMARY KEY, eno number PRIMARY KEY,
ename char(30) NOT NULL ename char(30) NOT NULL ename char(30) NOT NULL ename char(30) NOT NULL
dno number dno number dno number dno number DEFAULT 777
REFERENCES dept(dno) REFERENCES dept(dno) REFERENCES dept(dno) REFERENCES dept(dno)
) ON DELETE CASCADE ) ON DELETE SET NULL ) ON DELETE SET DEFAULT)

Child Parent Child Parent Child Parent Child Parent

SQL> DELETE FROM DEPT SQL> DELETE FROM DEPT SQL> DELETE FROM DEPT SQL> DELETE FROM DEPT
WHERE dno=101; WHERE dno=101; WHERE dno=101; WHERE dno=101;
Error:- 1 row deleted 1 row deleted 1 row deleted
integrity constraint violated
Child record found

Child Parent Child Parent Child Parent

Deletion on PARENT is Deletion on PARENT is Deletion on PARENT is Deletion on PARENT is


NOT ALWAYS Successful. ALWAYS Successful. ALWAYS Successful. ALWAYS Successful.
ON UPDATE NO ACTION ON UPDATE CASCADE ON UPDATE SET NULL ON UPDATE SET DEFAULT

CREATE TABLE emp CREATE TABLE emp CREATE TABLE emp CREATE TABLE emp
( ( ( (
eno number PRIMARY KEY, eno number PRIMARY KEY, eno number PRIMARY KEY, eno number PRIMARY KEY,
ename char(30) NOT NULL ename char(30) NOT NULL ename char(30) NOT NULL ename char(30) NOT NULL
dno number dno number dno number dno number DEFAULT 777
REFERENCES dept(dno) REFERENCES dept(dno) REFERENCES dept(dno) REFERENCES dept(dno)
) ON UPDATE CASCADE ) ON UPDATE SET NULL ) ON UPDATE SET DEFAULT)

Child Parent Child Parent Child Parent Child Parent

SQL> UPDATE DEPT SQL> UPDATE DEPT SQL> UPDATE DEPT SQL> UPDATE DEPT
SET dno = 420 SET dno = 420 SET dno = 420 SET dno = 420
WHERE dno = 101; WHERE dno = 101; WHERE dno = 101; WHERE dno = 101;
1 row updated 1 row updated 1 row updated
Error:-
integrity constraint violated
Child record found

Child Parent Child Parent Child Parent

UPDATE on PARENT is UPDATE on PARENT is UPDATE on PARENT is UPDATE on PARENT is


NOT ALWAYS Successful. ALWAYS Successful. ALWAYS Successful. ALWAYS Successful.
CHILD TABLE PARENT TABLE

CREATE TABLE emp (eno number PRIMARY KEY,


ename varchar2(30) NOT NULL,
dno number references DEPT(dno)
ON DELETE CASCADE
ON UPDATE CASCADE);
Note:- Insert/ Update / Delete on PARENT is always Successful.

Which Constrained COLUMN is eligible to be a PARENT COLUMN ? PRIMARY KEY


CHILD TABLE PARENT TABLE
SET OPERATORS
1) UNION
2) INTERSECT
3) MINUS

Child Column
Parent Column

PARENT CHILD CHILD PARENT


COLUMN COLUMN COLUMN COLUMN

MINUS
= MINUS = EMPTY
SET

Result of (CHILD COLUMN – PARENT COLUMN ) Always returns EMPTY SET


GATE Previous Questions
Consider the 2 tables in a relational database with columns and rows as follows:-
GATE 2004 IT : 1 Mark

 Roll_no is the primary key of the Student table


 Dept_id is the primary key of the Department
 Student.Dept_id is a foreign key from Department.Dept_id
What will happen if we execute the following 2 SQL statements ?

1. Update Student set Dept_id = Null where Roll_no = 1;


2. Update Department set Dept_id = Null where Dept_id = 1;

a) Both ( I) and (II) will fail


b) ( I ) will fail but ( II) will succeed
c) ( I ) will succeed but (II) will fail
d) Both (I) and (II) will succeed. 2
Parent Table Child Table
a) Both ( I) and (II) will fail
b) ( I ) will fail but ( II) will succeed Ans = C
c) ( I ) will succeed but (II) will fail
d) Both (I) and (II) will succeed.
Primary key Primary key Foreign Key

I Update Student set Dept_id = Null where Roll_no = 1; Success


Since foreign key column accepts NULL value

II Update Department set Dept_id = Null where Dept_id = 1; Failed


Since Primary key column wont accept NULL value
GATE Previous Questions
GATE 1997 : 1 Mark

Let R(a,b,c) and S(d,e,f) be 2 relations in which ‘d’ is the foreign key of S that refers to the
primary key of R.

Consider the following 4 operations on R and S


A. Insert into R
B. Insert into S
C. Delete from R
D. Delete from S

Which of the following is true about referential integrity constraint above ?

a. None of these can cause its violation


b. All of these can cause its violation
c. Both A and D can cause its violation
d. Both B and C can cause its violation

3
Parent Table Child Table a) None of these can cause its violation
b) All of these can cause its violation
c) Both A and D can cause its violation Ans = D
Parent Column Not Known d) Both B and C can cause its violation
Which of the following is true about referential integrity constraint?

A Insert into R Always Success Since INSERT into PARENT is always Successful.

B Insert into S At times Violates Since INSERT into CHILD is NOT always Successful

C Delete from R At times Violates Since DELETE from PARENT is NOT always Successful.

D Delete from S Always Success Since DELETE from CHILD is always Successful.
GATE Previous Questions
GATE 2005: 2 Marks

The following table has 2 attributes A and C, where A is the primary key and C is the
foreign key referencing A with on-delete cascade.

The set of all tuples that must be additionally deleted to preserve referential integrity when the
tuple (2, 4) is deleted is:-
a. (3 ,4) and (6, 4)
b. (5, 2) and (7, 2)
c. (5, 2), (7, 2) and (9, 5)
d. (3, 4), (4, 3) and (6, 4)
4
The following table has 2 attributes A and C, where A is the primary key and C is the
foreign key referencing A with on-delete cascade.

a. (3 ,4) and (6, 4)


The set of all tuples that must be additionally
b. (5, 2) and (7, 2) Ans = C
deleted to preserve referential integrity when the
c. (5, 2), (7, 2) and (9, 5)
tuple (2, 4) is deleted is:-
d. (3, 4), (4, 3) and (6, 4)

Parent Child
Column Column
Row Deleted = ( 2, 4)

Parent Deleted = 2 5 7 9

Child Rows Deleted = (5, 2) (9, 5) No Child No Child


Rows Rows
(7, 2)

Additional Rows Deleted = (5, 2) (7, 2) (9, 5)

On Delete Cascade
Structured Query Language [SQL]
1) UNDERSTANDING THE BASICS OF TABLE
2) PARENT TABLE (VS) CHILD TABLE
3) BASIC SELECT STATEMENT
4) OPERATORS IN SQL
5) NULL
6) SINGLE-ROW FUNCTIONS
7) MULTI-ROW FUNCTIONS [GROUP FUNCTIONS]
8) SET OPERATORS
9) PATTERN MATCHING
10) JOINS
11) NESTED SUB QUERIES
12) CORRELATED SUB QUERIES
13) DML STATEMENTS
14) DDL STATEMENTS
15) DCL STATEMENTS
16) TCL STATEMENTS
17) VIEWS
BASIC SELECT STATEMENT

SELECT * (or) ename, salary (or) DISTINCT ename, salary


FROM emp
WHERE eno > 3 AND salary < 15000
ORDER BY ename, salary DESC;

 ORDER BY Clause must be the last statement in the SELECT Statement.


 Default Order = Ascending [ASC]
 If we want the result in Descending Order, we must specify DESC.
Structured Query Language [SQL]
1) UNDERSTANDING THE BASICS OF TABLE
2) PARENT TABLE (VS) CHILD TABLE
3) BASIC SELECT STATEMENT
4) OPERATORS IN SQL
5) NULL
6) SINGLE-ROW FUNCTIONS
7) MULTI-ROW FUNCTIONS [GROUP FUNCTIONS]
8) SET OPERATORS
9) PATTERN MATCHING
10) JOINS
11) NESTED SUB QUERIES
12) CORRELATED SUB QUERIES
13) DML STATEMENTS
14) DDL STATEMENTS
15) DCL STATEMENTS
16) TCL STATEMENTS
17) VIEWS
OPERATORS IN SQL
OPERATORS IN SQL

Answer the following Queries

1) Fetch employees whose salary is between 1000 and 2000.


2) Fetch employees working in departments 101,102, and 103.
3) Fetch employees working in departments other than (101,102,103)
OPERATORS IN SQL

Q:1 :-Fetch employees whose salary is between 1000 and 2000.

SELECT
*
FROM EMP

WHERE salary BETWEEN 1000 AND 2000;

Salary >= 1000 AND salary <= 2000;


OPERATORS IN SQL

Q:2 :-Fetch employees working in departments 101,102, and 103.

SELECT
*
FROM EMP

WHERE dno IN (101, 102, 103);

dno = 101 OR dno = 102 OR dno = 103;


OPERATORS IN SQL

Q:2 :-Fetch employees working in departments other than 101,102, and 103.

SELECT
*
FROM EMP

WHERE dno NOT IN (101, 102, 103);

dno != 101 AND dno != 102 AND dno != 103;

NOT (dno = 101 OR dno = 102 OR dno = 103) = dno != 101 AND dno != 102 AND dno != 103
GATE Previous Question
Which of the following queries are equivalent to each other

SELECT *
I FROM PRODUCT
WHERE P_PRICE BETWEEN 50.00 AND 100.00

SELECT * a) III, IV
II FROM PRODUCT b) I, III, IV
WHERE P_PRICE <=50.00 and P_PRICE >=100.00
c) II, IV

SELECT * d) I, III
III FROM PRODUCT
WHERE P_PRICE >= 50.00 AND P_PRICE <=100.00

SELECT *
IV FROM PRODUCT
WHERE P_PRICE <= 100.00 and P_PRICE >=50.00
Practice Bit
Structured Query Language [SQL]
1) UNDERSTANDING THE BASICS OF TABLE
2) PARENT TABLE (VS) CHILD TABLE
3) BASIC SELECT STATEMENT
4) OPERATORS IN SQL
5) NULL
6) SINGLE-ROW FUNCTIONS
7) MULTI-ROW FUNCTIONS [GROUP FUNCTIONS]
8) SET OPERATORS
9) PATTERN MATCHING
10) JOINS
11) NESTED SUB QUERIES
12) CORRELATED SUB QUERIES
13) DML STATEMENTS
14) DDL STATEMENTS
15) DCL STATEMENTS
16) TCL STATEMENTS
17) VIEWS
NULL
1) NULL is Uninitialized, Unknown , and Inapplicable Value
2) A null is neither zero nor blank space.
3) Any Arithmetic operation with NULL is always NULL. [10 + NULL = NULL]
4) No two NULL values are identical. [All NULL values are different from each other]
5) Mathematics (Vs) SQL

Mathematics SQL

WHERE salary > 1000 WHERE salary > 1000


False False
True True
True True
0 False NULL Unknown

False Rows False & Unknown


Final Output = Final Output =
will be eliminated Rows eliminated

Total Possibilities for Condition = {True, False} Total Possibilities = {True, False, Unknown}
NULL

NULL

NULL

Answer the following Queries

1) Fetch employees who doesn’t have commission.


2) Fetch employees who have commission.
3) Compute total-salary of employees.
4) Fetch employees whose commission != 500.
5) Fetch DISTINCT commission from employees.
OPERATORS IN SQL

Q:1 :-Fetch employees who doesn’t have commission.

SELECT
*
FROM EMP

WHERE commission IS NULL;

Q:2 :-Fetch employees who have commission.

SELECT
*
FROM EMP

WHERE commission IS NOT NULL;


OPERATORS IN SQL

NULL

NULL

Q:3:- Compute total-salary of employees.

SELECT eno, ename, (salary + comm) total-salary


FROM emp;
OPERATORS IN SQL
Q:4 :-Fetch employees whose commission != 500.

SELECT *
NULL Unknown
FROM emp False
WHERE commission != 500; True
NULL Unknown

Q:5 :- Fetch DISTINCT commission from employees.

SELECT DISTINCT commission


FROM emp;

Note :-Though All NULL’s are different from each other, yet only one NULL will be displayed for
all NULL Values in the column with DISTINCT option.

Q:6 :- Fetch DISTINCT salary, commission from employees.

SELECT DISTINCT salary, commission


FROM emp;
GATE Previous Questions

Consider the following database schema of relation Employee( Emp#, Name, Age)

SELECT *
FROM Employee
WHERE Age <= 28 OR Age >28;

a) Tuples of Employee relation with non-NULL age


b) Tuples of Employee relation with Age > 28
c) Tuples of Employee relation with Age <=28
d) Copy of Employee relation

5
Consider the following database schema of relation Employee( Emp#, Name, Age)

SELECT *
Ans = A
FROM Employee
WHERE Age <= 28 OR Age >28;

Age Column can take NULL Values  Constraints to be Informed by Business Rule

Age < = 28 OR Age > 28 Final Result


False OR True True

Unknown OR Unknown Unknown

True True

SQL  Row –By –Row Processing


Structured Query Language [SQL]
1) UNDERSTANDING THE BASICS OF TABLE
2) PARENT TABLE (VS) CHILD TABLE
3) BASIC SELECT STATEMENT
4) OPERATORS IN SQL
5) NULL
6) SINGLE-ROW FUNCTIONS
7) MULTI-ROW FUNCTIONS [GROUP FUNCTIONS]
8) SET OPERATORS
9) PATTERN MATCHING
10) JOINS
11) NESTED SUB QUERIES
12) CORRELATED SUB QUERIES
13) DML STATEMENTS
14) DDL STATEMENTS
15) DCL STATEMENTS
16) TCL STATEMENTS
17) VIEWS
SINGLE-ROW FUNCTIONS

1 Single row function accepts each row and returns one result per row.

2 Character Functions  SUBSTR, INSTR

3 Number Functions  ROUND, TRUNC


SINGLE-ROW FUNCTIONS
SUBSTR
Purpose = Returns the part of the string.
Complete Signature = Substr(string, starting_position, no_of_characters)
Total Parameters =3
Mandatory Parameters = 2 [string, starting_position]
Optional Parameter = 1 [no_of_characters]
Default Value for Optional Parameter = no_of_characters till the end of string.

SELECT substr('prakasha'), error


substr('prakasha',4), kasha
substr('prakasha',4,2), ka
FROM dual;
SINGLE-ROW FUNCTIONS
INSTR
Purpose = Returns the numeric position of the string
Complete Signature = instr(string, search_string, starting_position, no_of_occurance)
Total Parameters =4
Mandatory Parameters = 2 [string, search_string]
Optional Parameter = 2 [starting_position, no_of_occurance]
Default Value for Optional Parameter = [starting_position =1, no_of_occurance=1]

SELECT Instr('prakasha','a'), 3
Instr('prakasha','a',4), 5
Instr('prakasha','a',4,2), 8
FROM dual;
SINGLE-ROW FUNCTIONS
ROUND
Purpose = To round the given decimal number
Complete Signature = ROUND(number, no_of_decimal_portions_to_be_rounded)
Total Parameters =2
Mandatory Parameters = 1 [number]
Optional Parameter = 1 [no_of_decimal_portions_to_be_rounded]
Default Value for Optional Parameter = no_of_decimal_portions_to_be_rounded=0

SELECT Round(53.456,2), 53.46


Round(53.456,1), 53.5
Round(53.456), 53
FROM dual;
SINGLE-ROW FUNCTIONS
TRUNC
Purpose = To truncate the given decimal number
Complete Signature = TRUNC(number, no_of_decimal_portions_to_be_rounded)
Total Parameters =2
Mandatory Parameters = 1 [number]
Optional Parameter = 1 [no_of_decimal_portions_to_be_rounded]
Default Value for Optional Parameter = no_of_decimal_portions_to_be_rounded=0

SELECT),
Trunc(53.456,2), 53.45
Trunc(53.456,1), 53.4
Trunc(53.456) 53
FROM dual;
GATE Previous Questions

The SQL statement


SELECT SUBSTR(‘123456789’, INSTR(‘abcabcabc’,’b’), 4) FROM DUAL;
Prints

a. 456789

b. 1234

c. 2345

d. 6789

6
SQL statement SELECT SUBSTR(‘123456789’, INSTR(‘abcabcabc’,’b’), 4) a) 456789
b) 1234
FROM DUAL;  Prints
c) 2345
Ans = C d) 6789

SUBSTR( String, Starting_Position, No_Of_Characters)

SUBSTR(‘123456789’, INSTR(‘abcabcabc’,’b’), 4)

SUBSTR(‘123456789’, 2 , 4) 2345

INSTR( String, Search_String, Starting_Position, No_Of_Occurance)


Default Value of Starting_Position = 1
Default Value of No_Of_Occurance = 1
INSTR(‘abcabcabc’, ’b’) 2
Structured Query Language [SQL]
1) UNDERSTANDING THE BASICS OF TABLE
2) PARENT TABLE (VS) CHILD TABLE
3) BASIC SELECT STATEMENT
4) OPERATORS IN SQL
5) NULL
6) SINGLE-ROW FUNCTIONS
7) MULTI-ROW FUNCTIONS [GROUP FUNCTIONS]
8) SET OPERATORS
9) PATTERN MATCHING
10) JOINS
11) NESTED SUB QUERIES
12) CORRELATED SUB QUERIES
13) DML STATEMENTS
14) DDL STATEMENTS
15) DCL STATEMENTS
16) TCL STATEMENTS
17) VIEWS
SQL> CREATE TABLE emp( eno NUMBER PRIMARY KEY, ename VARCHAR2(30) NOT NULL);
Table Created.

SQL> DESC emp;


Name Null? Type
----------------------------------------- -------- --- Every Table will have
ENO NOT NULL NUMBER
ENAME NOT NULL VARCHAR2(30) 1) User Created Columns

SQL>INSERT INTO emp VALUES(1, ‘A’); 2) Pseudo Columns


1 row inserted.

SQL>INSERT INTO emp VALUES(2, ‘B’);


1 row inserted.

SQL>INSERT INTO emp VALUES(3, ‘C’);


1 row inserted. User Columns  Created & Maintained by USER
SQL> SELECT ROWID, eno, ename FROM emp;
SQL> SELECT * FROM emp;
ENO ENAME
ROWID ENO ENAME
---------- -----------------------
--------------------------------------------------------------------------
1 A
AAAE54AABAAALDBAAA 1 A
2 B
AAAE54AABAAALDBAAB 2 B
3 C
AAAE54AABAAALDBAAC 3 C

Pseudo Columns  Created & Maintained by DBMS


Group Functions  Returns only one result per group 1) COUNT
All Group Functions ignores rows having NULL values except COUNT(*) 2) SUM
3) AVG
NULL COUNT(*)  considers NULL [it counts no of rows in a table] 4) MIN
COUNT(column_name) won’t consider NULL 5) MAX
NULL

SELECT COUNT(salary) FROM employee; 2

SELECT COUNT(*) FROM employee; 4

COUNT(*)  Counts the no of ROWID’s in a Table


MULTI-ROW FUNCTIONS [GROUP FUNCTIONS]
Complete Syntax Of GROUP FUNCTION

SELECT column, group_function(column)


FROM table
WHERE condition  To eliminate unwanted rows.
GROUP BY group_by_column
HAVING condition_on_group_function To eliminate unwanted groups.
ORDER BY column.
MULTI-ROW FUNCTIONS [GROUP FUNCTIONS]
ORDER of Execution
An SQL Query with GROUP FUNCTION executes in the following Order:-
1) WHERE condition will be applied on the table to filter the unmatched rows.[condition]
2) GROUP BY will be applied and divides the resultant rows into Groups.
3) GROUP FUNCTION will be applied on each group to return one result per group.
4) HAVING Clause will be applied to eliminate the unwanted Groups. [GROUP FUNCTION]
5) ORDER By Clause will be used to display the rows in the required order.

SELECT gender, min(gate_rank)


FROM students
WHERE result = ‘qualified’  Only GATE Qualified Students are selected
GROUP BY gender
HAVING min(gate_rank) < 200  Select only gender whose min(gate_rank) < 200
ORDER BY gender;
MULTI-ROW FUNCTIONS [GROUP FUNCTIONS]

Answer the following Queries

1) Compute the total no of employees and average salary of the company.


2) Compute the no of employees and average salary Gender Wise.
3) Compute the no of employees and average salary for each department.
4) Fetch the deptno's whose average salary is greater than 2500.
5) Fetch the deptno's in which the average salary of male employees > 2500
1) GROUP BY Clause is Optional.
2) Total GROUPS By Default = 1 [All Rows in Table =One Group]
3) GROUP BY Clause will be used when we want to divide
Single group into Multiple Groups.

Q:1 :-Compute the total no of employees and average salary of the company.

SELECT count(*), avg(salary)

FROM emp

1 WHERE

2 GROUP BY
1) WHERE  To eliminate Rows
3 HAVING 2) GROUP BY  To divide table into Multiple Groups
3) HAVING  To eliminate Groups
SELECT count(*), avg(salary)
FROM emp
GROUP BY gender;

SELECT Salary, count(*), avg(salary)


FROM emp Not matching Invalid Query
GROUP BY gender;

Q:1 :-Compute the total no of employees and average salary of the company.

SELECT count(*), avg(salary)


FROM emp;

Q:2 :-Compute the no of employees and average salary Gender Wise.

SELECT gender, count(*), avg(salary)

FROM emp

1 WHERE

2 GROUP BY gender 1) WHERE  To eliminate Rows


2) GROUP BY  To divide table into Multiple Groups
3 HAVING 3) HAVING  To eliminate Groups
Q:3 :-Compute the no of employees and average salary for each department.

SELECT deptno, count(*), avg(salary)

FROM emp

1 WHERE

2 GROUP BY deptno

3 HAVING
1) WHERE  To eliminate Rows
2) GROUP BY  To divide table into Multiple Groups
3) HAVING  To eliminate Groups
Q:3 :-Compute the no of employees and avg salary for each department.
SELECT deptno, count(*), avg(salary)
FROM emp
GROUP BY deptno;

Q:4 :-Fetch the deptno's whose average salary is greater than 2500.

SELECT deptno avg(salary)

FROM emp

1 WHERE

2 GROUP BY deptno 1) WHERE  To eliminate Rows


2) GROUP BY  To divide table into Multiple Groups
3 HAVING avg(salary) > 2500 3) HAVING  To eliminate Groups
Q:4 :-Fetch the deptno's whose avg salary is greater than 2500.

SELECT deptno, avg(salary)


FROM emp
GROUP BY deptno
HAVING avg(salary) > 2500;

Q:5 :-Fetch the deptno's in which the average salary of male employees > 2500

SELECT deptno avg(salary)

FROM emp

1 WHERE gender = ‘M’

2 GROUP BY deptno

3 HAVING Avg(salary) > 2500

1) WHERE  To eliminate Rows


2) GROUP BY  To divide table into Multiple Groups
3) HAVING  To eliminate Groups
SELECT deptno, gender, count(*)
FROM emp
GROUP BY deptno, gender;

KEY POINTS
1 Column_name in SELECT Clause is Optional. [Only Group Functions are allowed]

If we want to include any Column in the SELECT Clause, then it must the be the
2 same column list mentioned in the GROUP BY Clause.

3 GROUP BY Clause is Optional. [Complete Table will be treated as a single group]

4 We can group the rows using Multiple Columns [GROUP BY gender, deptno]

5 WHERE Clause  To eliminate Rows, HAVING Clause  To eliminate Groups

SELECT avg(salary) Valid, By default every SQL query with Group


6 FROM emp Function returns 1-Group.
HAVING avg(salary) > 4000; HAVING decides whether to eliminate it (or) not.

7 Except Count(*) , All other group functions ignores NULL values.


GATE Previous Questions
A table T1 in a relational database has the following rows and columns:-
[GATE 2004 IT : 2 Marks]

The following sequence of SQL statements was successfully executed on table T1.

1. Update T1 set marks = marks + 5;


2. Select avg(marks) from T1;

What is the output of the select statement ?

a.8.75
b.20
c.25
d.Null
7
A table T1 in a relational database has the following rows and columns:-
The following sequence of SQL statements was successfully executed T1.

1. Update T1 set marks = marks + 5;


2. Select avg(marks) from T1; a.8.75
b.20
c.25 Ans = C
What is the output of the select statement ? d.Null

1 Update T1 set marks = marks + 5; = =

2 Select avg(marks) from T1; = (15 + 25 + 35)/3 = 75/3 = 25

All GROUP Functions ignores rows having NULL Values


GATE Previous Questions
GATE 2012: 1 Mark

Which of the following statements are TRUE about an SQL query?


P : An SQL query can contain a HAVING clause even if it does not have a GROUP BY clause
Q : An SQL query can contain a HAVING clause only if it has a GROUP BY clause
R : All attributes used in the GROUP BY clause must appear in the SELECT clause
S : Not all attributes used in the GROUP BY clause need to appear in the SELECT clause

a) P and R
SELECT count(*), avg(salary)
b) P and S FROM emp
GROUP BY gender;
c) Q and R
d) Q and S SELECT Salary, count(*), avg(salary)
FROM emp Not matching Invalid Query
GROUP BY gender;

8
Structured Query Language [SQL]
1) UNDERSTANDING THE BASICS OF TABLE
2) PARENT TABLE (VS) CHILD TABLE
3) BASIC SELECT STATEMENT
4) OPERATORS IN SQL
5) NULL
6) SINGLE-ROW FUNCTIONS
7) MULTI-ROW FUNCTIONS [GROUP FUNCTIONS]
8) SET OPERATORS
9) PATTERN MATCHING
10) JOINS
11) NESTED SUB QUERIES
12) CORRELATED SUB QUERIES
13) DML STATEMENTS
14) DDL STATEMENTS
15) DCL STATEMENTS
16) TCL STATEMENTS
17) VIEWS
SET OPERATORS
Every SELECT statement will be treated as SET.
Two SELECT statements are said to be UNION Compatible :-
1. Number of Columns in both SELECT statements must be same
2. Corresponding Columns must belong to same data type [Family]
SELECT eno, ename FROM employee Not UNION Compatible, Since no of
UNION columns =3 in one SELECT and 4 in
SELECT eno FROM emp_history; other.

SELECT eno, ename FROM employee Not UNION Compatible, salary &
UNION address doesn’t belong to same
SELECT ename, eno FROM emp_history; data type [Data Type FAMILY]

SET OPERATORS IN SQL 1) Eliminates Duplicate Rows


2) Displays rows in Sorted Order
UNION, INTERSECT , MINUS
UNION ALL , INTERSECT ALL, MINUS ALL No Duplicate Elimination & No Sorting
UNION
INTERSECT
MINUS (or) EXCEPT

MINUS is NOT COMMUTATIVE


UNION ALL
INTERSECT ALL
MINUS ALL (or) EXCEPT ALL
Structured Query Language [SQL]
1) UNDERSTANDING THE BASICS OF TABLE
2) PARENT TABLE (VS) CHILD TABLE
3) BASIC SELECT STATEMENT
4) OPERATORS IN SQL
5) NULL
6) SINGLE-ROW FUNCTIONS
7) MULTI-ROW FUNCTIONS [GROUP FUNCTIONS]
8) SET OPERATORS
9) PATTERN MATCHING
10) JOINS
11) NESTED SUB QUERIES
12) CORRELATED SUB QUERIES
13) DML STATEMENTS
14) DDL STATEMENTS
15) DCL STATEMENTS
16) TCL STATEMENTS
17) VIEWS
PATTERN MATCHING

%  Zero (or) More Characters

_  Exactly One Character

Use ESCAPE character to search for “%“and “_” in the given string.

Answer the following Queries


1) Fetch emp info whose name starts with "abc“.
2) Fetch emp info whose name starts with "abc" with total characters=4.
3) Fetch emp info whose name is "abc_“.
4) Fetch emp info whose name is "abc%“.
Q:1 :-Fetch emp info whose name starts with "abc“.

SELECT *
DuringFROM emp Escape character will be ignored. Its purpose is to nullify the
comparison,
specialWHERE ename
importance of _LIKE
(or) 'abc%';
%.

Q:2 :-Fetch emp info whose name starts with "abc" with total characters=4.

SELECT *
FROM emp
WHERE ename LIKE 'abc_';

Q:3 :- Fetch emp info whose name is "abc_".

SELECT *
FROM emp
WHERE ename LIKE 'abc\_' ESCAPE '\';
Q:4 :- Fetch emp info whose name is "abc%".

SELECT *
FROM emp
WHERE ename LIKE 'abc\%' ESCAPE '\';
GATE Previous Questions

Like ‘Amit\%shah%’ ESCAPE ‘\’ matches

a) Gives error
b) All strings beginning with “Amit\%shah”
c) All strings beginning with “Amit%shah”
d) All strings beginning with “Amit shah”

9
Structured Query Language [SQL]
1) UNDERSTANDING THE BASICS OF TABLE
2) PARENT TABLE (VS) CHILD TABLE
3) BASIC SELECT STATEMENT
4) OPERATORS IN SQL
5) NULL
6) SINGLE-ROW FUNCTIONS
7) MULTI-ROW FUNCTIONS [GROUP FUNCTIONS]
8) SET OPERATORS
9) PATTERN MATCHING
10) JOINS
11) NESTED SUB QUERIES
12) CORRELATED SUB QUERIES
13) DML STATEMENTS
14) DDL STATEMENTS
15) DCL STATEMENTS
16) TCL STATEMENTS
17) VIEWS
JOINS
We use JOINS to fetch data from multiple tables.

1) CARTESIAN PRODUCT
2) EQUI JOIN
3) NON EQUI JOIN
4) SELF JOIN
5) LEFT OUTER JOIN
6) RIGHT OUTER JOIN
7) FULL OUTER JOIN
8) NATURAL JOIN
CARTESIAN PRODUCT All rows of first table joined with all rows in the second table
No of Columns = 5 No of Columns = 2
No of Rows =3 No of Rows =3

No of Columns = 5 + 2 = 7
No of rows = 3 * 3 = 9
JOINS

Answer the following Queries


1) Fetch employee information along with department information.
2) Fetch employee information along with their grades.
3) Fetch employee information along with their managers information.
4) Fetch all employees along with their department information.
5) Fetch all departments along with employee information.
6) Fetch all employees along with all departments information.
7) Perform Natural Join of Employee and Department.
EQUI JOIN :- Joining 2 (or) more tables using an equality operator [=].

Rows
1
2
3
4
5
6
7
8
9

To Join n-tables, we need a minimum of (n-1) join conditions.


Q:1 :-Fetch employee information along with department information.

SELECT e.eno, e.ename, e.dno, d.dname


FROM emp e, dept d
WHERE e.dno = d.dno;
NON EQUI JOIN:- Joining 2 (or) more tables using operator other than equality [<,>,>=,<=,!=]

Rows
1
2
3
4
5
6
7
8
9

Q:2 :-Fetch employee information along with their grades.


SELECT e.eno, e.ename, e.salary, j.grade
FROM emp e, job_grades J
WHERE e.salary BETWEEN j.low_sal AND j.high_sal;
WHERE e.salary >= j.low_sal AND e.salary <= j.high_sal;
SELF JOIN :- Joining a table to itself

EMPLOYEE “E” MANAGER “M”


Rows
1
2
3
4
5
6
7
8
9

Q:3 :-Fetch employee information along with their managers information.

SELECT e.eno, e.ename, m.mgr, m.ename mgr_name


FROM emp e, emp m
WHERE e.mgr = m.eno;
LEFT OUTER JOIN:- LEFT OUTER JOIN = Rows of EQUI JOIN + Free Rows of Left Table [Free Employees]

The LEFT OUTER JOIN operation keeps every row in the left table; if no matching
row is found in the right table, then the attributes of right table filled with null.

Equi Join

Equi Join

Q:4 :-Fetch all employees along with their department information.

SELECT e.eno, e.ename, d.dno, d.dname


FROM emp e LEFT OUTER JOIN dept d
ON e.dno = d.dno;
RIGHT OUTER JOIN:- RIGHT OUTER JOIN = Rows of EQUI JOIN + Free Rows of Right Table [Free Departments]

The RIGHT OUTER JOIN operation keeps every row in the right table; if no matching
row is found in the left table, then the attributes of left table filled with null.

Equi Join

Equi Join

Q:5 :-Fetch all departments along with employee information.

SELECT e.eno, e.ename, d.dno, d.dname


FROM emp e RIGHT OUTER JOIN dept d
ON e.dno = d.dno;
FULL OUTER JOIN:-
FULL OUTER JOIN keeps all tuples in both the left and the right relations when no
matching tuples are found, filled with null values as needed.
FULL OUTER JOIN = Rows of EQUI JOIN + Free Rows of Left Table [Free Employees] + Free Rows of Right Table [Free Departments]

Equi Join

Equi Join

Q:6 :-Fetch all employees along with all departments information.

SELECT e.eno, e.ename, d.dno, d.dname


FROM emp e FULL OUTER JOIN dept d
ON e.dno = d.dno;
NATURAL JOIN:- Performs equi join on similar column names in both tables.

Common Columns in R and S = {B, C}

WHERE Condition  R.B = S.B AND R.C = S.C

R.B = S.B AND R.C = S.C

SELECT * EQUI JOIN


FROM R NATURAL JOIN S; SELECT *
FROM R ,S
WHERE R.B = S.B
AND R.C = S.C;

Common Columns repeat only Once

Common Columns repeats twice


KEY POINTS
To fetch data from Multiple Tables  Always Visualize the CARTESIAN PRODUCT

NATURAL JOIN (vs) EQUI JOIN


In NATURAL JOIN, Where Clause is Optional & Common columns appear only once

No of Rows in emp = 12
SELECT * FROM emp, dept; 12 * 0 = 0
No of Rows in dept = 0 [Empty]

No of Rows in emp = 1000 [Child Table] SELECT * Min rows = 0


No of Rows in dept = 2000 [Parent Table] FROM emp e, dept d
WHERE e.dno=d.dno; Max rows = 1000

Min Case Max Case

NULL 101
NULL 102
NULL 103
All employees are Free Employees All employees are Working Employees
SELECT * SELECT * 3 rows returned
FROM emp e, dept d FROM emp e, dept d
WHERE e.dno=d.dno; No Rows [0 rows] WHERE e.dno=d.dno;
KEY POINTS
No of Rows in emp = 1000 [Child Table] SELECT * Min rows = 1000
Foreign Key  NOT NULL FROM emp e, dept d
No of Rows in dept = 2000 [Parent Table] WHERE e.dno=d.dno; Max rows = 1000

Min Case & Max Case

101
102
103

SELECT * 3 rows returned


FROM emp e, dept d
WHERE e.dno=d.dno;

All employees are Working Employees  Min & Max = All Employees [All Working Employees]
Min & Max  Always from CHILD TABLE ONLY

No of Rows in emp = m [Child Table] Joining EMP & DEPT


Min rows = 0

No of Rows in dept = n [Parent Table] Max rows = m×n


GATE Previous Questions
A relational database contains two tables GATE 2004 IT : 1Mark

Student (roll_no, name ,dept_id)


Department(dept_id,dept_name)

The following insert statements were executed successfully to populated the empty tables:
Insert into department values(1, ‘Mathematics’);
Insert into department values(2, ‘Physics’);
Insert into student values (1, ‘Navin’,1);
Insert into student values (2, ‘Mukesh’, 2);
Insert into student values (3, ‘Gita’,1);

How many rows and columns will be retrieved by the following SQL statement?

Select * from student, department;

a. 0 row and 4 columns


b. 3 rows and 4 columns
c. 3 rows and 5 columns
d. 6 rows and 5 columns
10
Insert into department values(1, ‘Mathematics’);
Insert into department values(2, ‘Physics’); a) 0 row and 4 columns
b) 3 rows and 4 columns
Insert into student values (1, ‘Navin’,1); c) 3 rows and 5 columns
Insert into student values (2, ‘Mukesh’, 2); d) 6 rows and 5 columns
Insert into student values (3, ‘Gita’,1);

Select * from student, department; Ans = D

No of Columns = 3 No of Columns = 2
No of Rows = 3 No of Rows = 2

Select * from student, department; CARTESIAN PRODUCT No of Columns = 3 + 2 = 5


No of Rows = 3 × 2 = 6
Question Modified
A relational database contains two tables
Child Column Parent Column
student (roll_no, name ,dept_id)
Department(dept_id,dept_name)

The following insert statements were executed successfully to populated the empty
tables: Student(dept_id) is foreign key refering to Department(dept_id)
Insert into student values (1, ‘Navin’,D1); Failed, Foreign key constraint Violated
Insert into student values (2, ‘Mukesh’,D2); Failed, Foreign key constraint Violated
Insert into student values (3, ‘Gita’,1); Failed, Foreign key constraint Violated
Insert into department values(D1, ‘Mathematics’); Success
Insert into department values(D2, ‘Physics’); Success

M = SELECT COUNT(*) FROM STUDENT; 0


M+N=0+2=2
N = SELECT COUNT(*) FROM DEPARTMENT; 2

a) 3
b) 6
What is the value of (M + N) ?
c) 5
d) 2
GATE Previous Questions
GATE 1999: 1 Mark

Consider the join of a relation R with relation S. If R has m-tuples and S has n-
tuples then the maximum and minimum sizes of join respectively are

a) (m + n) and 0 Ans = B
b) mn and 0
c) (m + n) and |m – n|
d) mn and (m + n)

Min rows 0
No of Rows in emp = m [Child Table] Joining EMP & DEPT
No of Rows in dept = n [Parent Table] Max rows m×n

11
GATE Previous Questions
GATE 2011: 2 Marks

Database table by name Loan_Records is given below. What is the output of the
following SQL query?

SELECT Count(*)
FROM ( a) 3
(SELECT Borrower, Bank_Manager
FROM Loan_Records) AS S b) 9
NATURAL JOIN
(SELECT Bank_Manager,Loan_Amount c) 5
FROM Loan_Records) AS T
d) 6
);

12
SELECT Count(*)
FROM (
(SELECT Borrower, Bank_Manager
FROM Loan_Records) AS S
NATURAL JOIN
(SELECT Bank_Manager,Loan_Amount
FROM Loan_Records) AS T
);

a) 3
b) 9 Ans = C S.Bank_Manager = T.Bank_Manager
c) 5
d) 6

Solving Using CARTESIAN PRODUCT


5 Rows Selected
SELECT Count(*) Ans = C
FROM (
(SELECT Borrower, Bank_Manager
FROM Loan_Records) AS S a) 3
NATURAL JOIN b) 9
(SELECT Bank_Manager,Loan_Amount c) 5
FROM Loan_Records) AS T d) 6
Solving by Simulating CARTESIAN PRODUCT );

S.Bank_Manager = T.Bank_Manager

S Natural Join T

Total Rows = 5 Rows Selected


GATE Previous Questions
GATE 2004 : 1 Mark

Consider the following relation schema pertaining to a student’s database:

Student (rollno, name, address)


Enroll (rollno, courseno, coursename)

Where the primary keys are shown underlined. The number of tuples in the
student and Enroll tables are 120 and 8 respectively. What are the maximum
and minimum number of tuples that can be present in (Student*Enroll), where
‘*’ denotes natural join?

a) 8,8
b) 120, 8
c) 960,8
d) 960, 120

13
Consider the following relation schema pertaining to a student’s database:
120 Rows 8 Rows

Primary Key = RollNo Primary Key = RollNo + CourseNo

Foreign key constraint exists, since it belongs to Students Database

RollNo  Foreign Key + NOT NULL

No of Rows in emp = 1000 [Child Table] SELECT * Max rows = 1000


Foreign Key  NOT NULL FROM emp e, dept d
No of Rows in dept = 2000 [Parent Table] WHERE e.dno=d.dno; Min rows = 1000

No of Rows in ENROLL= 8[Child Table]


Foreign Key  NOT NULL
SELECT * Max rows = 8
FROM STUDENT
No of Rows in STUDENT= 120 [Parent Table] NATURAL JOIN ENROLL; Min rows = 8

Consider the following relation schema pertaining to a student’s database:


Ans = A
Student (rollno, name, address)
Enroll (rollno, courseno, coursename) a) 8,8
Where the primary keys are shown underlined. The number of tuples in the b) 120, 8
student and Enroll tables are 120 and 8 respectively. What are the maximum and c) 960,8
minimum number of tuples that can be present in (Student*Enroll), where ‘*’
d) 960, 120
denotes natural join?
GATE Previous Questions
Consider the following relations: GATE 2015: Set:1  2 Marks

Consider the following SQL query:-

SELECT S. Student_Name, sum (P.Marks)


FROM Student S, Performance P
WHERE S. Roll_No =P.Roll_No
GROUP BY S.Student_Name;

The number of rows that will be returned by the SQL query is _________.
14
S.RollNo = P.RollNo

No of Rows returned SQL query are ___.


SELECT S. Student_Name, sum (P.Marks)
FROM Student S, Performance P
WHERE S. RollNo =P.RollNo 1
GROUP BY S.Student_Name; 2

Ans = 2

GROUP BY S.StudentName

Only 2 Groups
GATE Previous Questions
GATE 2000 : 2 Marks

Given relations r(w,x) and s(y,z), the result of


Select distinct w,x
From r,s;
is guaranteed to be same as r, provided

a) r has no duplicates and s is non-empty


b) r and s have no duplicates
c) s has no duplicates and r is non-empty
d) r and s have the same number of tuples

15
Given relations r(w,x) and s(y,z), the result of
SELECT distinct w,x a) r has no duplicates and s is non-empty
FROM r,s; = r provided b) r and s have no duplicates Ans = A
c) s has no duplicates and r is non-empty
X = Y, what would be conditions? d) r and s have the same number of tuples

SELECT distinct w,x


If “S” is empty
FROM r,s; ? r
Case: I

Obviously “S” must be non-empty


!=
If “r” has duplicates SELECT distinct w,x
Case: 2 FROM r,s; ? r

!=
If “r” has no duplicates SELECT distinct w,x

Case: 3
FROM r,s; ?r
Obviously “R” should not have Duplicates =
Consider a database with 3 relation instances shown below. GATE IT 2006 : 2 Marks
The primary keys for the Drivers and Cards relation are did and cid respectively.

What is the output of the following query?

SELECT D.dname
FROM Drivers D
WHERE D.did IN ( SELECT R.did a) Karthikeyan, Boris
FROM Cars C, Reserves R b) Sachin, Salman
WHERE R.cid = C.cid AND C.colour = ’red’
c) Karthikeyan, Boris, Sachin
INTERSECT d) Schumacher, Senna
SELECT R.did
FROM Cars C, Reservers R
WHERE R.cid = C.cid AND C.colour = ‘green’); 16
SELECT D.dname DRIVERS RESERVES
FROM Drivers D 22, 22, 31, 31, 64 did dname did cid
WHERE D.did IN 22 Karthikeyan CARS 22 101
( SELECT R.did 29 Salman cid cname colour 22 102
FROM Cars C, Reserves R 31 Boris 101 Renault blue 22 103
WHERE R.cid = C.cid AND C.colour = ’red’ 32 Amoldt 102 Renault red 22 104
58 Schumacher 103 Ferrari green 31 102
64 Sachin 104 Jaguar red 31 103
INTERSECT 71 Senna 31 104
SELECT R.did 74 Sachin 64 101
85 Rahul 64 102
FROM Cars C, Reservers R
95 Ralph 74 103
WHERE R.cid = C.cid AND C.colour = ‘green’ );

SELECT R.did R.cid = C.cid

FROM Cars C, Reserves R

WHERE R.cid = C.cid AND C.colour = ’red’

2 1
SELECT D.dname DRIVERS RESERVES
FROM Drivers D 22, 22, 31, 31, 64 did dname did cid
WHERE D.did IN 22 Karthikeyan CARS 22 101
( SELECT R.did 29 Salman cid cname colour 22 102
FROM Cars C, Reserves R 31 Boris 101 Renault blue 22 103
WHERE R.cid = C.cid AND C.colour = ’red’ 32 Amoldt 102 Renault red 22 104
58 Schumacher 103 Ferrari green 31 102
64 Sachin 104 Jaguar red 31 103
INTERSECT 22, 31, 74 71 Senna 31 104
SELECT R.did 74 Sachin 64 101
85 Rahul 64 102
FROM Cars C, Reservers R
95 Ralph 74 103
WHERE R.cid = C.cid AND C.colour = ‘green’ );

SELECT R.did R.cid = C.cid

FROM Cars C, Reservers R

WHERE R.cid = C.cid AND C.colour = ‘green’

2 1
SELECT D.dname DRIVERS RESERVES
FROM Drivers D 22, 22, 31, 31, 64 did dname did cid
WHERE D.did IN 22 Karthikeyan CARS 22 101
( SELECT R.did 29 Salman cid cname colour 22 102
FROM Cars C, Reserves R 31 Boris 101 Renault blue 22 103
WHERE R.cid = C.cid AND C.colour = ’red’ 32 Amoldt 102 Renault red 22 104
58 Schumacher 103 Ferrari green 31 102
64 Sachin 104 Jaguar red 31 103
INTERSECT 22, 31, 74 71 Senna 31 104
SELECT R.did 74 Sachin 64 101
85 Rahul 64 102
FROM Cars C, Reservers R
95 Ralph 74 103
WHERE R.cid = C.cid AND C.colour = ‘green’ );

Ans = A
{22, 22, 31, 31, 64} Intersect {22, 31, 74} = {22, 31}

SELECT D.dname DRIVERS


did dname
FROM Drivers D 22 Karthikeyan
WHERE D.did IN (22, 31) ; 29 Salman
31 Boris
32 Amoldt
58 Schumacher
64 Sachin
71 Senna
74 Sachin
85 Rahul
95 Ralph
GATE Previous Questions
GATE 2015: Set:2  2 Marks
Consider two relations R1 & R2 with the tuples
R1(A,B) =(1, 5), (3,7)
R2 (A,C) = (1,7), (4,9)
Assume that R(A,B,C) is the full natural outer join of R1 and R2 . Consider the following tuples
of the form (A,B,C):
a = (1,5,null)
b = (1,null,7)
c = (3,null,9)
d = (4,7,null)
e = (1,5,7)
f = (3,7,null)
g = (4,null,9)
Which one of the following statements is correct?

a) R contains a,b,e,f,g but not c,d.


b) R contains all of a,b,c,d,e,g
c) R contains e,f,g but not a,b
d) R contains e but not f,g.

17
Consider two relations R1 & R2 with the tuples R1(A,B) =(1, 5), (3,7) and R2 (A,C) = (1,7), (4,9)

Assume that R(A,B,C) is the full natural outer join of R1 and R2 . a = (1,5,null) Ans = C
b = (1,null,7)
Which one of the following statements is correct in R(A,B,C)? c = (3,null,9)
a) R contains a,b,e,f,g but not c,d. d = (4,7,null)
b) R contains all of a,b,c,d,e,g e = (1,5,7)
c) R contains e,f,g but not a,b f = (3,7,null)
d) R contains e but not f,g. g = (4,null,9)

R1.A = R2.A
Rows of Equi Join

Full Natural Outer Join


= Free Rows of LEFT Table

Free Rows of RIGHT Table

Full Natural Outer Join = Full Outer Join + Natural Join


R1.A = R2.A
Full Outer Join with Condition as R1.A = R2.A
= and
Common Columns to be repeated Only Once
FULL OUTER JOIN = Rows of EQUI JOIN + Free Rows of Left Table [Free Employees] + Free Rows of Right Table [Free Departments]
Structured Query Language [SQL]
1) UNDERSTANDING THE BASICS OF TABLE
2) PARENT TABLE (VS) CHILD TABLE
3) BASIC SELECT STATEMENT
4) OPERATORS IN SQL
5) NULL
6) SINGLE-ROW FUNCTIONS
7) MULTI-ROW FUNCTIONS [GROUP FUNCTIONS]
8) SET OPERATORS
9) PATTERN MATCHING
10) JOINS
11) NESTED SUB QUERIES
12) CORRELATED SUB QUERIES
13) DML STATEMENTS
14) DDL STATEMENTS
15) DCL STATEMENTS
16) TCL STATEMENTS
17) VIEWS
NESTED SUB QUERIES
Select-Statement embedded in another Select-Statement
Outer Query Executes Second
SELECT column_list
FROM table outer Inner Query Executes first
WHERE operator ( SELECT column_list
FROM table inner
WHERE condition );

Operator  {=, < , >, !=, >, <} Returns only 1-Row Single Row Sub Queries

Operator  {IN, ANY, ALL} Returns multiple Rows Multi Row Sub Queries

WHERE Salary IN (100, 200, 300) = WHERE Salary = 100 OR Salary = 200 OR Salary = 300

WHERE Salary >ANY (100, 200, 300 = WHERE Salary >100 OR Salary > 200 OR Salary >300

WHERE Salary >ALL(100, 200, 300) = WHERE Salary >100 AND Salary > 200 AND Salary >300
KEY POINTS
1) Job of Inner Query
2) Inner Query  Returning 1-row (or) n-rows
3) Operator  {IN, ANY, ALL} (or) {=, >, <}

Answer the following Queries


1) Fetch employees whose salary is greater than “a” salary.
2) Fetch employees who are drawing salary more than any one in dept=102.
3) Fetch employees who are drawing salary more than all employees in dept=102.
4) Fetch employees who are drawing same salary as employees in dept=102.
5) Fetch department that has at least one employee using Sub Query.
6) Fetch department that do not have employees using Sub Query.
KEY POINTS
1) Job of Inner Query
2) Inner Query  Returns 1-row (or) n-rows
3) Operator  {IN, ANY, ALL} (or) {=, >, <}

Q:1 :-Fetch employees whose salary is greater than “a” salary.

SELECT eno, ename, salary 3000


FROMSELECT
emp eno, ename, salary
WHEREFROM
salaryemp
> (SELECT salary
WHERE salary FROM
> 3000;emp
WHERE ename= 'a');
SELECT eno, ename, salary, dno
FROM emp 2000
WHERE dno !=102
AND salary > (SELECT min(salary)
FROM emp
WHERE dno = 102);

SELECT eno, ename, salary, dno


FROM emp
KEY POINTS
WHERE dno !=102 1) Job of Inner Query
AND salary > 2000 OR salary > 4000; 2) Inner Query  Returns 1-row (or) n-rows
3) Operator  {IN, ANY, ALL} (or) {=, >, <}

Q:2 :-Fetch employees who are drawing salary more than any one in dept=102.

SELECT eno, ename, salary, dno


FROM emp {2000, 4000}
WHERE dno !=102
AND salary > ANY (SELECT salary
FROM emp
WHERE dno=102);
SELECT eno, ename, salary, dno
FROM emp 4000
WHERE dno !=102
AND salary > (SELECT max(salary)
FROM emp
WHERE dno = 102);

SELECT eno, ename, salary, dno


FROM emp
KEY POINTS
WHERE dno !=102 1) Job of Inner Query
AND salary > 2000 AND salary > 4000; 2) Inner Query  Returns 1-row (or) n-rows
3) Operator  {IN, ANY, ALL} (or) {=, >, <}

Q:3 :-Fetch employees who are drawing salary more than all employees in dept=102.

SELECT eno, ename, salary, dno


FROM emp {2000, 4000}
WHERE dno !=102
AND salary > ALL (SELECT salary
FROM emp
WHERE dno=102);
KEY POINTS
1) Job of Inner Query
2) Inner Query  Returns 1-row (or) n-rows
3) Operator  {IN, ANY, ALL} (or) {=, >, <}

SELECT eno, ename, salary, dno


FROM emp
WHERE dno !=102
AND salary = 2000 OR salary = 4000;

Q:4 :-Fetch employees who are drawing same salary as employees in dept=102.

SELECT eno, ename, salary, dno


FROM emp {2000, 4000}
WHERE dno !=102
AND salary IN (SELECT salary
FROM emp
WHERE dno=102);
KEY POINTS
1) Job of Inner Query
2) Inner Query  Returns 1-row (or) n-rows
3) Operator  {IN, ANY, ALL} (or) {=, >, <}

Q:5 :-Fetch department that has at least one employee using Sub Query.

SELECT * {101, 102, 103, NULL}


FROM dept
WHERE dno IN (SELECT distinct dno
FROM emp);

SELECT eno, ename, salary, dno


FROM emp
WHERE dno = 101 OR dno = 102 OR dno = 103 OR dno = NULL;
KEY POINTS
1) Job of Inner Query
2) Inner Query  Returns 1-row (or) n-rows
3) Operator  {IN, ANY, ALL} (or) {=, >, <}

Q:6 :-Fetch department that do not have employees using Sub Query.

SELECT * {101, 102, 103, NULL}


FROM dept
WHERE dno NOT IN (SELECT distinct dno
FROM emp);
SELECT *
SELECT eno, ename, salary,{101,
dno102, 103}
FROM dept
FROM emp
WHERE dno NOT IN (SELECT distinct dno
WHERE dno != 101 AND dno != 102 AND dno != 103 AND dno != NULL;
FROM emp
WHERE dno IS NOT NULL);
If sub query returns NO ROWS with IN, ANY, ALL operators.

SELECT * No Rows Returned


FROM emp
WHERE salary IN (SELECT salary No Rows
FROM emp
WHERE eno = 4); Operator = {IN, ANY}
All rows returned by Outer Query are False
SELECT * No Rows Returned
FROM emp
No Rows
WHERE salary > ANY (SELECT salary
FROM emp Operator = {ALL, NOT IN}
WHERE eno = 4 ); All rows returned by Outer Query are TRUE
SELECT * No Rows Returned
FROM emp
WHERE salary > ALL ( SELECT salary
FROM emp
WHERE eno = 4);
SELECT * No Rows Returned
FROM emp
WHERE salary NOT IN (SELECT salary
FROM emp
WHERE eno = 4);
NESTED SUB QUERIES
KEY POINTS

Inner Query executes First, exactly Once


Outer Query executes Second, exactly Once
Order of Execution :- Outer Query returns the required result.
Inner Query is Independent
Outer Query is Dependent on Inner Query.

Single Row Sub Queries  Returns Only 1-row


Operators = { =, >, < , >=, <=, !=}
2 Types of Sub Queries :-
Multi Row Sub Queries  Returns Multiple Rows
Operators = { IN , ANY , ALL }

Sub Query returned Operator = ANY/IN  Result = NO Rows Returned


“NO ROWS” Operator = ALL/ NOT IN Result = ALL Rows returned by Outer Query

Make Sure that Sub Query shouldn’t return


When NOT IN used for Sub Query
NULL, If it returns NULL, then result= NO ROWS.
GATE Previous Questions
Table Employee has 10 records. It has a non-null SALARY column which is also UNIQUE.

SELECT count(*)
FROM employee
WHERE salary > ANY (SELECT salary
FROM employee);

a.0
b.5
c.9
d.10

18
Table Employee has 10 records. It has a non-null SALARY column which is also UNIQUE.
SELECT count(*) a) 0
FROM employee b) 5 Ans = C
WHERE salary > ANY (SELECT salary c) 9
FROM employee); d) 10

Salary > ANY (100, 200,…,1000) is equivalent to Salary > 100 OR Salary > 200 ….OR Salary > 1000

SQL Row –by- Row Processing

SELECT count(*)
FROM employee > ANY (100, 200,…,1000) NO
WHERE salary > ANY ( SELECT salary
> ANY (100, 200,…,1000) YES
FROM employee );
> ANY (100, 200,…,1000) YES
> ANY (100, 200,…,1000) YES
(100, 200,…,1000)
> ANY (100, 200,…,1000) YES
Final Output =
> ANY (100, 200,…,1000) YES
> ANY (100, 200,…,1000) YES
> ANY (100, 200,…,1000) YES
> ANY (100, 200,…,1000) YES
9 rows selected
> ANY (100, 200,…,1000) YES
SELECT count(*)
FROM employee Count (*) = 9
WHERE salary > ANY (SELECT salary
{ 200, 300,…1000}
FROM employee);
SELECT count(*)
FROM employee Count (*) = 10
WHERE salary >= ANY (SELECT salary
FROM employee); All rows selected
SELECT count(*)
FROM employee Count (*) = 0
WHERE salary > ALL (SELECT salary
FROM employee); No Rows Returned
SELECT count(*)
FROM employee Count (*) = 1
WHERE salary > = ALL (SELECT salary Only Highest Salary
FROM employee); Salary = 1000
SELECT count(*)
FROM employee Count (*) = 10
WHERE salary IN (SELECT salary
FROM employee); All rows selected

SELECT count(*)
FROM employee
Count (*) = 0
WHERE salary NOT IN (SELECT salary
FROM employee); No Rows Returned
GATE Previous Questions
GATE 2015: Set:3  1 Mark

Consider the following relation Cinema (theater, address, capacity)

Which of the following options will be needed at the end of the SQL query?

SELECT P1. address


FROM Cinema P1
Such that it always finds the addresses of theaters with maximum capacity?

a) WHERE P1. Capacity> = All (select P2. Capacity from Cinema P2)
b) WHERE P1. Capacity> = Any (select P2. Capacity from Cinema P2)
c) WHERE P1. Capacity > All (select max(P2. Capacity) from Cinema P2)
d) WHERE P1. Capacity > Any (select max (P2. Capacity) from Cinema P2)

19
Consider the following relation Cinema (theater, address, capacity)

Query  To find the addresses of theaters with Maximum Capacity?


Ans = A

SELECT P1. address Option: A


100, 200 , 300, 300
FROM Cinema P1 Required Output
WHERE P1. Capacity > = All ( select P2. Capacity from Cinema P2 )

SELECT P1. address Option: B


100, 200 , 300, 300 All rows Returned
FROM Cinema P1
WHERE P1. Capacity > = ANY ( select P2. Capacity from Cinema P2 )

SELECT P1. address Option: C


300
FROM Cinema P1 No Rows Returned
WHERE P1. Capacity > All ( select max(P2. Capacity) from Cinema P2 )

Option: D
SELECT P1. address
300
FROM Cinema P1 No Rows Returned
WHERE P1. Capacity > ANY ( select max(P2. Capacity) from Cinema P2 )
GATE Previous Questions
GATE 2012: 2 Marks
Consider the following relations A, B and C:-

How many tuples does the result of the following SQL query contain?
a) 4
SELECT A.Id
FROM A b) 3
WHERE A.age > ALL ( SELECT B.Age
FROM B c) 0
WHERE B.Name = ‘Arun’);
d) 1

20
Ans = B

a) 4
b) 3
c) 0
How many tuples does the result of the following SQL query contain? d) 1

SELECT A.Id No Rows Returned


FROM A
WHERE A.age > ALL ( SELECT B.Age
FROM B
WHERE B.Name = ‘Arun’ );

KEY POINTS
Inner Query  No Rows Returned
Operator = ALL
Result = Rows Returned by Outer Query
3 rows returned
GATE Previous Questions
Employee information in a company is stored in relation Employee(name, sex, salary, deptName)
SELECT deptName GATE 2004: 2 Marks
FROM Employee
WHERE Sex = ‘M’
GROUP BY deptName
HAVING avg(salary) > (SELECT avg(salary)
FROM Employee);

It returns the names of the department in which

a) The average salary is more than the average salary in the company
b) The average salary of male employees is more than the average salary of all male
employees in the company
c) The average salary of male employees is more than the average salary of employees in
the same department.
d) The average salary of male employees is more than the average salary in the company.

21
Employee information in a company is stored in relation Employee(name, sex, salary, deptName)

SELECT deptName Outer Query


FROM Employee Computing Avg Salary of Only Male Employees Department Wise

WHERE Sex = ‘M’ 1 More than Inner Query


GROUP BY deptName 2 Computing Avg Salary of company

HAVING avg(salary) 3 > ( SELECT avg(salary)


Ans = D
FROM Employee );
Query returns

a) It returns the names of the department in which average salary Wrong


is more than the average salary in the company Correct

It returns the names of the department in which average salary of male employees Correct
b)
is more than the average salary of all male employees in the company Wrong

It returns the names of the department in which average salary of male employees Correct
c)
Is more than the average salary of employees in the same department. Wrong

It returns the names of the department in which average salary of male employees Correct
d) Is more than the average salary in the company. Correct
GATE Previous Questions
GATE 2014 SET:2  2 Marks

SQL allows duplicate tuples in relations, and correspondingly defines the multiplicity of
tuples in the result of joins. Which one of the following queries always gives the same
answer as the nested query shown below:

Select * from R where a in (select S.a from S)

a) Select R.* from R, S where R.a=S.a


b) Select distinct R.* from R, S where R.a=S.a
c) Select R.* from R, (Select distinct a from S) as S1 where R.a=S1.a
d) Select R.* from R, S where R.a=S.a and is unique R

22
SQL allows duplicate tuples in relations, and correspondingly defines the multiplicity of tuples
in the result of joins.
Which one of the following queries always gives the same answer as the given query below:
{ 1, 1} { 1, 1}
Ans = C
select * from R where a IN ( select S.a from S )

a) Select R.* from R, S where R.a=S.a Not Matching

b) Select distinct R.* from R, S where R.a=S.a Not Matching

Matching
c)
Select R.* from R, (Select distinct a from S) as S1 where R.a=S1.a
Total No of Tables = 2 = {R, S}
Total No of Columns in table “R” = Not Given
d) No Select
Total of ColumnsR.* from
in table “S” R, S where
= Not Given R.a=S.a and is unique R Syntax is Wrong
By Observing the given queries, we have to consider column “a” in R & S tables.
Structured Query Language [SQL]
1) UNDERSTANDING THE BASICS OF TABLE
2) PARENT TABLE (VS) CHILD TABLE
3) BASIC SELECT STATEMENT
4) OPERATORS IN SQL
5) NULL
6) SINGLE-ROW FUNCTIONS
7) MULTI-ROW FUNCTIONS [GROUP FUNCTIONS]
8) SET OPERATORS
9) PATTERN MATCHING
10) JOINS
11) NESTED SUB QUERIES
12) CORRELATED SUB QUERIES
13) DML STATEMENTS
14) DDL STATEMENTS
15) DCL STATEMENTS
16) TCL STATEMENTS
17) VIEWS
Answer the Simple Query

Fetch employees whose salary is greater than average salary of the company.

SELECT * 3000
FROM emp
WHERE salary > (SELECT avg(salary)
FROM emp);
Answer another simple Query
Average Salary of all Departments

Fetch employees whose salary is greater than average salary of his department.

How to get the Output ? What is the JOB of Inner Query ?


CORRELATED SUB QUERIES

INNER Query is dependent on the OUTER Query.


INNER Query needs an input from the OUTER Query.
So OUTER Query executes First, then INNER Query.
Fetch employees whose salary is greater than average salary of his department.
Final Output

Inner Query Executes exactly once for every outer row = 7-times

Outer Query Executes First  returned 7-rows

SELECT outer.eno, outer.ename, outer.salary, outer.dno


FROM emp outer
WHERE outer.salary > (SELECT avg(inner.salary)
FROM emp inner
WHERE inner.dno = outer.dno);

3333
3000
2000
0 NO
NO
YES
YES SELECT avg(inner.salary) from emp inner WHERE inner.dno=?
102
NULL
101
103
101
102
Q:1 :-Fetch employees whose salary is greater than
average salary of his department.

Outer Query Executes First Inner Query Executes Second


 returned 7-rows Executes exactly 7-times

SELECT outer.eno, outer.ename, outer.salary, outer.dno


FROM emp outer
WHERE outer.salary > (SELECT avg(inner.salary)
FROM emp inner
WHERE inner.dno = outer.dno);
SELECT avg(inner.salary) FROM emp inner
3333 NO Where inner.dno = 101;
3333 YES Where inner.dno = 101;
3333 NO Where inner.dno = 101;
3000 NO Where inner.dno = 102;
3000 YES Where inner.dno = 102;
2000 NO Where inner.dno = 103;
NULL NO Where inner.dno = NULL;
CORRELATED SUB QUERY
Fetch Male Employees having
Dependents

SELECT *
FROM employee outer
WHERE outer.gender=‘M’
AND 0 != (SELECT count(*)
FROM dependent inner
WHERE inner.empid = outer.empid);

Outer Query Executed First  returned 3-rows

1 Yes
1 Yes
0 NO
CORRELATED SUB QUERIES

Answer the following Queries


1) Fetch employees whose salary is greater than average salary of his department.
2) Fetch employees whose salary is greater than his manager’s salary.
3) Fetch department having at least one employee using Correlated Sub Query.
4) Fetch department that do not have employees using Correlated Sub Query.
5) Fetch department that has exactly one employee using Correlated Sub Query.
6) Fetch department that has 2 (or) more employees using Correlated Sub Query.
Q:1 :-Fetch employees whose salary is greater than average salary of his department.

SELECT outer.eno, outer.ename, outer.salary, outer.dno


FROM emp outer
WHERE outer.salary > (SELECT avg(inner.salary)
FROM emp inner
WHERE inner.dno = outer.dno);
Q:2 :-Fetch employees whose salary is greater than his manager’s salary.

SELECT outer.eno, outer.ename, outer.salary, outer.mgr


FROM emp outer
WHERE outer.salary > (SELECT inner.salary
FROM emp inner
WHERE inner.eno = outer.mgr);
Q:3 :-Fetch department having at least one employee using Correlated Sub Query.

SELECT outer.dno, outer.dname


FROM dept outer
WHERE 0 != (SELECT count(inner.dno)
FROM emp inner
WHERE inner.dno = outer.dno);

SELECT outer.dno, outer.dname


FROM dept outer
WHERE EXISTS (SELECT 'prakash'
FROM emp inner
WHERE inner.dno = outer.dno);
Q:4 :-Fetch department that do not have employees using Correlated Sub Query.

SELECT outer.dno, outer.dname


FROM dept outer
WHERE 0 = (SELECT count(inner.dno)
FROM emp inner
WHERE inner.dno = outer.dno);

SELECT outer.dno, outer.dname


FROM dept outer
WHERE NOT EXISTS (SELECT 'prakash'
FROM emp inner
WHERE inner.dno = outer.dno);
Q:5 :-Fetch department that has exactly one employee using Correlated Sub Query.

SELECT outer.dno, outer.dname


FROM dept outer
WHERE 1 = (SELECT count(inner.dno)
FROM emp inner
WHERE inner.dno = outer.dno);

SELECT outer.dno, outer.dname


FROM dept outer
WHERE UNIQUE (SELECT 'prakash'
FROM emp inner
WHERE inner.dno = outer.dno);
Q:6 :-Fetch department that has 2 (or) more employees using Correlated Sub Query.

SELECT outer.dno, outer.dname


FROM dept outer
WHERE 2 <= (SELECT count(inner.dno)
FROM emp inner
WHERE inner.dno = outer.dno);

SELECT outer.dno, outer.dname


FROM dept outer
WHERE NOT UNIQUE (SELECT 'prakash'
FROM emp inner
WHERE inner.dno = outer.dno);
CORRELATED SUB QUERIES
CORRELATED SUB QUERIES
KEY POINTS
Type of SUB Query Executes FIRST Query Executes SECOND Query giving
QUERY the OUTPUT

NESTED Sub Query

CORRELATED

Use EXISTS , NOT EXISTS, UNIQUE, NOT UNIQUE functions with Correlated Sub Query.
GATE Previous Questions
A relational schema for a train reservation database is given below. GATE 2010 : 2 Marks
Passenger (pid, pname, age)
Reservation (pid, class, tid)

What pids are returned by the following SQL query for the above instance of the tables?

SELECT pid a) 1,0


FROM Reservation
WHERE class = ‘AC’ b) 1,2
AND EXISTS (SELECT *
FROM Passenger c) 1,3
WHERE age > 65
AND Passenger. pid = Reservation.pid) d) 1,5
23
OUTER QUERY Table INNER QUERY Table What pids are returned by the following SQL query:-
a) 1,0
b) 1,2
Ans = C
c) 1,3
d) 1,5

SELECT pid Outer Query executes first and returns 4 rows


FROM Reservation Inner Query executes second and exactly once for each outer row
WHERE class = ‘AC’
AND EXISTS ( SELECT * Final Output
FROM Passenger
WHERE age > 65
AND Passenger. pid = Reservation.pid )

INNER QUERY executes once per each OUTER ROW RETURNS OPERATOR OUTER ROW

Eliminated
SELECT * FROM Passenger WHERE age > 65 AND pid = 0 No Rows EXISTS

SELECT * FROM Passenger WHERE age > 65 AND pid = 1 1 row EXISTS Selected

SELECT * FROM Passenger WHERE age > 65 AND pid = 5 No Rows EXISTS Eliminated

SELECT * FROM Passenger WHERE age > 65 AND pid = 3 1 row EXISTS Selected
GATE Previous Questions
GATE 2005: 2 Marks

The relation book (title, price) contains the title and prices of different books. Assuming that
no two books have the same price, what does the following SQL query list ?

Select title
From book as B
Where (Select count(*)
From book as T
Where T.price > B.price) < 5

a. Titles of the 4 most expensive books


b. Title of the 5th most inexpensive book
c. Title of the 5th most expensive book
d. Titles of the 5 most expensive books

24
The relation book (title, price) contains the title and prices of different books.
Assuming that no two books have same price, what does the following SQL query list ? Ans = D

a) Titles of the 4 most expensive books


b) Tile of the 5th most inexpensive book
Outer Query c) Title of the 5th most expensive book
Table Inner Query
d) Titles of the 5 most expensive books Table
Sample Data  Insert 6 rows into Table BOOK

Outer Query executes first and returns all rows Final Output
Select title
From book as B Inner Query executes second and exactly once for each outer row
Where ( Select count(*)
From book as T 5 most expensive books selected
Where T.price > B.price ) < 5

INNER QUERY executes once per each OUTER ROW COUNT(*) < 5 OUTER ROW

Select count(*) From book as T Where T.price > 100 5 < 5 Eliminated

Select count(*) From book as T Where T.price > 200 4 < 5 Selected

Select count(*) From book as T Where T.price > 300 3 < 5 Selected

Select count(*) From book as T Where T.price > 400 2 < 5 Selected

Select count(*) From book as T Where T.price > 500 1 < 5 Selected

Select count(*) From book as T Where T.price > 600 0 < 5 Selected
The relation book (title, price) contains the title and prices of different books.
Assuming that no two books have same price, what does the following SQL query list ? Ans = D

a) Titles of the 4 most expensive books


b) Tile of the 5th most inexpensive book
Outer Query c) Title of the 5th most expensive book Inner Query
Table d) Titles of the 5 most expensive books Table
Sample Data  Insert 5 rows into Table BOOK

Outer Query executes first and returns all rows Final Output
Select title
From book as B Inner Query executes second and exactly once for each outer row
Where ( Select count(*)
From book as T All books selected
Where T.price > B.price ) < 5

INNER QUERY executes once per each OUTER ROW COUNT(*) < 5 OUTER ROW

Select count(*) From book as T Where T.price > 100 4 < 5 Selected

Select count(*) From book as T Where T.price > 200 3 < 5 Selected

Select count(*) From book as T Where T.price > 300 2 < 5 Selected

Select count(*) From book as T Where T.price > 400 1 < 5 Selected

Select count(*) From book as T Where T.price > 500 0 < 5 Selected
GATE Previous Questions
Consider the following relational schema: GATE 2014 SET:3  2 Marks
employee(empId, empName, empDept)
customer(custId, custName, salesRepId, rating)
salesRepId is a foreign key referring to empId of the employee relation. Assume that each
employee makes a sale to at least one customer. What does the following query return?

SELECT empName
FROM employee E
WHERE NOT EXISTS (SELECT custId
FROM customer C
WHERE C.salesRepId = E.empId
AND C.rating <> ‘GOOD’);

a) Names of all the employees with at least one of their customers having a ‘GOOD’ rating.
b) Names of all the employees with at most one of their customers having a ‘GOOD’ rating.
c) Names of all the employees with none of their customers having a ‘GOOD’ rating.
d) Names of all the employees with all their customers having a ‘GOOD’ rating.

25
a) Names of all the employees with at least one of their customers having a ‘GOOD’ rating.
b) Names of all the employees with at most one of their customers having a ‘GOOD’ rating.
c) Names of all the employees with none of their customers having a ‘GOOD’ rating.
d) Names of all the employees with all their customers having a ‘GOOD’ rating.

How Beginner’s solve the Query?


-- By Populating Sample Data into Tables.

We have to populate DATA in the following way


1) One Employee with Both Good Customers. [empID = 1]
2) One Employee with One Good and One Bad Customer. [empID = 2]
3) One Employee with Both Bad Customers. [empID = 3]
1, 2
2, 3
3
1
Outer Query Table Inner Query Table
Ans = D

SELECT empName Outer Query executes first and returns all rows Final Output
FROM employee E
WHERE NOT EXISTS ( SELECT custId
FROM customer C
WHERE C.salesRepId = E.empId
AND C.rating <> ‘GOOD’ );
Inner Query executes second and exactly once for each outer row

INNER QUERY executes once per each OUTER ROW RETURNS OPERATOR OUTER ROW

SELECT custId FROM customer C WHERE C.salesRepId =


AND C.rating <> ‘GOOD’ );
1 No Rows NOT EXISTS Selected

SELECT custId FROM customer C WHERE C.salesRepId =


AND C.rating <> ‘GOOD’ );
2 1 row NOT EXISTS Eliminated

SELECT custId FROM customer C WHERE C.salesRepId =


AND C.rating <> ‘GOOD’ );
3 2 rows NOT EXISTS Eliminated
a) Names of all the employees with at least one of their customers having a ‘GOOD’ rating.
b) Names of all the employees with at most one of their customers having a ‘GOOD’ rating.
c) Names of all the employees with none of their customers having a ‘GOOD’ rating.
d) Names of all the employees with all their customers having a ‘GOOD’ rating.

How Expert will solve the Query?


-- Without Populating Sample Data into Tables.
NOT EXISTS  OUTER ROW will be Selected Only If INNER QUERY returns NO ROWS.
NOT EXISTS  empID will be selected only if he does not have any Bad Customer  All Good Customers

SELECT empName
FROM employee E Ans = D
WHERE NOT EXISTS ( SELECT custId
FROM customer C
WHERE C.salesRepId = E.empId
AND C.rating <> ‘GOOD’ );

Inner Query executes second and exactly once for each outer row.
Inner Query accepts empId and returns list of custId’s of Only Bad Customers.
Finally, Inner Query  Returns list of Bad Customers of the Given Employee.

Outer Query executes first and selects all employees


Structured Query Language [SQL]
1) UNDERSTANDING THE BASICS OF TABLE
2) PARENT TABLE (VS) CHILD TABLE
3) BASIC SELECT STATEMENT
4) OPERATORS IN SQL
5) NULL
6) SINGLE-ROW FUNCTIONS
7) MULTI-ROW FUNCTIONS [GROUP FUNCTIONS]
8) SET OPERATORS
9) PATTERN MATCHING
10) JOINS
11) NESTED SUB QUERIES
12) CORRELATED SUB QUERIES
13) DML STATEMENTS
14) DDL STATEMENTS
15) DCL STATEMENTS
16) TCL STATEMENTS
17) VIEWS
DML STATEMENTS
INSERT :- To insert a single row into a table.

To insert data into few columns :- [Must specify the column names explicitly]
INSERT INTO emp (eno,ename) VALUES (11,’a’);

To insert data into all columns :- [Need not mention the column names]
INSERT INTO emp VALUES (11,’a’,1000,3,101);

DELETE :- To delete 1 (or) multiple rows from a table.

DELETE from emp;  All rows in emp will be deleted.


DELETE from emp WHERE eno=3;  Only 1 row will be deleted.

UPDATE :- To update 1 (or) multiple rows and 1 (or) multiple columns in a table.

UPDATE emp SET salary= salary + 1000, mgr = 2;  2 Columns updated for all rows
UPDATE emp SET salary = salary + 1000 WHERE eno=3;  only 1-column, 1-row updated.
Structured Query Language [SQL]
1) UNDERSTANDING THE BASICS OF TABLE
2) PARENT TABLE (VS) CHILD TABLE
3) BASIC SELECT STATEMENT
4) OPERATORS IN SQL
5) NULL
6) SINGLE-ROW FUNCTIONS
7) MULTI-ROW FUNCTIONS [GROUP FUNCTIONS]
8) SET OPERATORS
9) PATTERN MATCHING
10) JOINS
11) NESTED SUB QUERIES
12) CORRELATED SUB QUERIES
13) DML STATEMENTS
14) DDL STATEMENTS
15) DCL STATEMENTS
16) TCL STATEMENTS
17) VIEWS
DDL STATEMENTS
CREATE :- To create a new table.

CREATE TABLE emp ( eno number PRIMARY KEY, ename varchar2(30);

ALTER :- To add a new column, drop an existing column, and modifying the data
type, size, and constraint of the existing column.

ALTER TABLE emp ADD deptno number(3);


ALTER TABLE emp DROP COLUMN deptno;
ALTER TABLE emp MODIFY ename varchar2(50);

TRUNCATE :- To remove the data [rows] from the table leaving the structure.
TRUNCATE TABLE emp;  All rows will be removed, It cannot be rolled back.

RENAME :- To rename the object. DROP:- To remove the object permanently.


RENAME emp to employee; DROP TABLE emp;
Definition

Data

DELETE TRUNCATE DROP

DELETE FROM emp


WHERE eno = 2; TRUNCATE TABLE emp; DROP TABLE emp;

Only one row No EMP table


deleted

DELETE FROM emp; All rows deleted

DML Statement DDL Statement


Can be Rolled Back Cannot be Rolled Back

DEFINITION YES DEFINITION YES DEFINITION NO

DATA YES/NO DATA NO DATA NO


GATE Previous Questions

Which of the following statements are true?

I) The INSERT INTO command allows the insertion of only one row at a time
II) The DELETE command allows the deletion of only one row at a time
III) The UPDATE command allows the Updation of only one row at a time
IV) The UPDATE command allows the Updation of only one attribute for a given table at a time

a. Only I, II and IV
b. Only I and II
c. Only III
d. Only I

Practice Bit
Structured Query Language [SQL]
1) UNDERSTANDING THE BASICS OF TABLE
2) PARENT TABLE (VS) CHILD TABLE
3) BASIC SELECT STATEMENT
4) OPERATORS IN SQL
5) NULL
6) SINGLE-ROW FUNCTIONS
7) MULTI-ROW FUNCTIONS [GROUP FUNCTIONS]
8) SET OPERATORS
9) PATTERN MATCHING
10) JOINS
11) NESTED SUB QUERIES
12) CORRELATED SUB QUERIES
13) DML STATEMENTS
14) DDL STATEMENTS
15) DCL STATEMENTS
16) TCL STATEMENTS
17) VIEWS
2 Types of Students

GOOD STUDENT BAD STUDENT

SQL> show user; SQL> show user;


prakash suresh
SQL> SELECT * FROM emp; SQL> SELECT * FROM emp;
No Object exists

SQL> SELECT * FROM emp;

10,000 rows are displayed

SQL> GRANT select ON emp TO suresh;


grant succeeded. 10,000 rows are displayed

SQL> REVOKE select FROM emp TO suresh;


revoke succeeded. SQL> SELECT * FROM emp;
No Object exists
2 Types of Database Users

DBA Normal Users


SQL> CREATE USER suresh identified by 420; SQL> show user;
user created prakash
SQL> GRANT create table, create view to suresh;
grant succeeded SQL> SELECT * FROM emp;
10,000 rows are displayed
SQL> GRANT select ON emp TO suresh;
grant succeeded.

2 Types of Privileges

SYSTEM Privileges OBJECT Privileges

DBA  Normal User Normal User  Normal User

 CREATE TABLE  SELECT


 CREATE VIEW  INSERT
 CREATE SYNONYM  DELETE
 CREATE PROCEDURE  UPDATE
2 ways of Granting Privileges

Direct Way Indirect Way [using ROLE]


SQL> GRANT create table to prakash; SQL> CREATE ROLE student;
grant succeeded.
role created successfully
SQL> GRANT create table to navatha;
grant succeeded SQL> GRANT create table to student;
grant succeeded.
SQL> GRANT create table to pranavi;
grant succeeded SQL> GRANT student to prakash;
grant succeeded.
SQL> REVOKE create table from prakash;
revoke succeeded. SQL> GRANT student to navatha;
grant succeeded
SQL> REVOKE create table from navatha;
revoke succeeded. SQL> GRANT student to pranavi;
grant succeeded
SQL> REVOKE create table from pranavi;
revoke succeeded. SQL> REVOKE create table from student;
revoke succeeded.
Structured Query Language [SQL]
1) UNDERSTANDING THE BASICS OF TABLE
2) PARENT TABLE (VS) CHILD TABLE
3) BASIC SELECT STATEMENT
4) OPERATORS IN SQL
5) NULL
6) SINGLE-ROW FUNCTIONS
7) MULTI-ROW FUNCTIONS [GROUP FUNCTIONS]
8) SET OPERATORS
9) PATTERN MATCHING
10) JOINS
11) NESTED SUB QUERIES
12) CORRELATED SUB QUERIES
13) DML STATEMENTS
14) DDL STATEMENTS
15) DCL STATEMENTS
16) TCL STATEMENTS
17) VIEWS
Operations on Database  Select, Insert, Delete, and Update
Transaction  Set of DML operations that performs a Business Unit of Work

BANK
 With drawl
 Deposit
 Funds Transfer
 Account Opening
 Account Closure

RAILWAY RESERVATION COUNTER


 Ticket Reservation
 Ticket Cancellation
 Ticket Upgrade
 Ticket Downgrade

COLLEGE
 Student Admission
 Student Relieving
 Student Migration
 Student Termination
CREATE PROCEDURE prc_ticket_reservation RESERVATION SCREEN
(train_no number,
doj date,
TRAIN NO : 12711
class varchar, DOJ :1-june-14
source varchar, CLASS :II-AC
dest varchar, SOURCE :Banglore
passenger varchar, DEST :Vijayawada
gender varchar, PNAME :Prakash
age number, GENDER :Male
fare number) AS AGE : 35
BEGIN FARE : 1800
INSERT INTO PASSENGER(pno, pname, gender, age)
VALUES (seq.nextval,'prakash','male', 35); BOOK
INSERT INTO BOOKING(pno, train_no, doj, class, src, dest)
VALUES (1111, 12711,'01-June-14', 'II-AC', 'Blore', 'Vja");
No of DML operations in Transaction
UPDATE REVENUE SET balance = balance + 1800;
2- Inserts
UPDATE AVAILABILITY SET no_of_seats = no_of_seats-1 2- Updates
WHERE train_no=12711 AND doj='01-June-14' AND Class='II-AC';
COMMIT; (OR) ROLLBACK;
END: COMMIT  The changes made by the transaction will be saved permanently in database.
ROLLBACK  The changes made by the transaction will be erased [discarded].
Structured Query Language [SQL]
1) UNDERSTANDING THE BASICS OF TABLE
2) PARENT TABLE (VS) CHILD TABLE
3) BASIC SELECT STATEMENT
4) OPERATORS IN SQL
5) NULL
6) SINGLE-ROW FUNCTIONS
7) MULTI-ROW FUNCTIONS [GROUP FUNCTIONS]
8) SET OPERATORS
9) PATTERN MATCHING
10) JOINS
11) NESTED SUB QUERIES
12) CORRELATED SUB QUERIES
13) DML STATEMENTS
14) DDL STATEMENTS
15) DCL STATEMENTS
16) TCL STATEMENTS
17) VIEWS
VIEWS
Name given to a SELECT statement CREATION of a VIEW
(or) CREATE VIEW empvu80 AS
Stored SELECT Statement SELECT emp_id, last_name,salary
(or) FROM employees
Virtual Table. WHERE department_id = 80;

USING a VIEW
SELECT *
FROM empvu80 ;

EMPLOYEES

Table  Definition + Data


View  Only Definition [Data will be fetched from the table on which it is created]
DML operations on View  DML operations on the Table only.

INSERT INTO empvu80(eno,ename,salary,)


Values( 25, ‘xyz’, 7000);  1 row inserted into the employee table.
GATE Previous Questions

Which of the following statements are true?

I. In SQL, We can create virtual tables


II. SQL is only Data Manipulation Language
III. WHERE clause applies to output of a GROUP BY command
IV. HAVING clause applies to columns and expressions for individual rows

a) I, III, IV
b) I
c) All of the above
d) I, II, III

26
SQL [Structured Query Language]

Any Queries