Beruflich Dokumente
Kultur Dokumente
Teaching: 4 years
- worked in NRI Institute of Technology as Associate Professor
- 4 years of experience in training students for GATE
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
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
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
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
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
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_____?
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
All 3 columns should not take NULL values and DUPLICATE values
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
Child Column
Parent Column
PARENT TABLE
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)
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
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)
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 Column
Parent Column
MINUS
= MINUS = EMPTY
SET
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.
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.
Parent Child
Column Column
Row Deleted = ( 2, 4)
Parent Deleted = 2 5 7 9
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
*
FROM EMP
SELECT
*
FROM EMP
Q:2 :-Fetch employees working in departments other than 101,102, and 103.
SELECT
*
FROM EMP
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
Total Possibilities for Condition = {True, False} Total Possibilities = {True, False, Unknown}
NULL
NULL
NULL
SELECT
*
FROM EMP
SELECT
*
FROM EMP
NULL
NULL
SELECT *
NULL Unknown
FROM emp False
WHERE commission != 500; True
NULL Unknown
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.
Consider the following database schema of relation Employee( Emp#, Name, Age)
SELECT *
FROM Employee
WHERE Age <= 28 OR Age >28;
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
True True
1 Single row function accepts each row and returns one result per row.
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),
Trunc(53.456,2), 53.45
Trunc(53.456,1), 53.4
Trunc(53.456) 53
FROM dual;
GATE Previous Questions
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(‘123456789’, INSTR(‘abcabcabc’,’b’), 4)
SUBSTR(‘123456789’, 2 , 4) 2345
Q:1 :-Compute the total no of employees and average salary of the company.
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;
Q:1 :-Compute the total no of employees and average salary of the company.
FROM emp
1 WHERE
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.
FROM emp
1 WHERE
Q:5 :-Fetch the deptno's in which the average salary of male employees > 2500
FROM emp
2 GROUP BY deptno
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.
4 We can group the rows using Multiple Columns [GROUP BY gender, deptno]
The following sequence of SQL statements was successfully executed on table T1.
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.
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]
Use ESCAPE character to search for “%“and “_” in the given string.
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_';
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
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
Rows
1
2
3
4
5
6
7
8
9
Rows
1
2
3
4
5
6
7
8
9
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
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
Equi Join
Equi Join
No of Rows in emp = 12
SELECT * FROM emp, dept; 12 * 0 = 0
No of Rows in dept = 0 [Empty]
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
101
102
103
All employees are Working Employees Min & Max = All Employees [All Working Employees]
Min & Max Always from CHILD TABLE ONLY
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?
No of Columns = 3 No of Columns = 2
No of Rows = 3 No of Rows = 2
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
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
S.Bank_Manager = T.Bank_Manager
S Natural Join T
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
The number of rows that will be returned by the SQL query is _________.
14
S.RollNo = P.RollNo
Ans = 2
GROUP BY S.StudentName
Only 2 Groups
GATE Previous Questions
GATE 2000 : 2 Marks
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
!=
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.
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’ );
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’ );
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}
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
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) {=, >, <}
Q:2 :-Fetch employees who are drawing salary more than any one in dept=102.
Q:3 :-Fetch employees who are drawing salary more than all employees in dept=102.
Q:4 :-Fetch employees who are drawing same salary as employees in dept=102.
Q:5 :-Fetch department that has at least one employee using Sub Query.
Q:6 :-Fetch department that do not have employees using Sub Query.
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
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
Which of the following options will be needed at the end of the SQL query?
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)
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
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);
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)
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:
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 )
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.
Inner Query Executes exactly once for every outer row = 7-times
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.
SELECT *
FROM employee outer
WHERE outer.gender=‘M’
AND 0 != (SELECT count(*)
FROM dependent inner
WHERE inner.empid = outer.empid);
1 Yes
1 Yes
0 NO
CORRELATED SUB QUERIES
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?
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
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
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
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.
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 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.
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);
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.
ALTER :- To add a new column, drop an existing column, and modifying the data
type, size, and constraint of the existing column.
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.
Data
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
2 Types of Privileges
BANK
With drawl
Deposit
Funds Transfer
Account Opening
Account Closure
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
a) I, III, IV
b) I
c) All of the above
d) I, II, III
26
SQL [Structured Query Language]
Any Queries