You are on page 1of 28

Chapter 2

Structured Query Language

LEARNING OBJECTIVES

 Relational algebra  Correlated nested queries


 Select operator  Relational calculus
 Project operator  Tuple relational calculus
 Set operators  Tuple relational calculus
 Union compatible relations  DML
 Union operation  Super key
 Aggregate operators  SQL commands

RelaTional algeBRa Relational operations


1. A set of operators (unary or binary) that take relation instances
as arguments and return new relations. Unary operators Binary operators
2. Gives a procedural method of specifying a retrieval query 1. Select 1. Union
2. Project 2. Intersection
3. Forms the core component of a relational query engine 3. Difference
4. SQL queries are internally translated into RA expressions 4. Join
5. Provides a framework for query optimization 5. Divide
6. Cartesian product

SQL query Select Operator (s)


Select operator is an unary operator. It can be used to select those
tuples of a relation that satisfy a given condition.
Relational algebra expression
Notation: sθ (r)
s : Select operator(read as sigma)
Query expression plan
θ : Selection condition
r : Relation name
Executable code Result is a relation with the same scheme as r consisting of the
tuples in r that satisfy condition θ
Figure 1 Role of relational algebra in DBMS: Syntax: scondition (relation)
Example:
Relational Operations Table 2.1 Person

A collection of simple ‘low-level’ operations used to manipulate Id Name Address Hobby


relations. 112 John 12, SP Road Stamp collection

1. It provides a procedural way to query a database. 113 John 12, SP Road Coin collection
2. Input is one (or) more relations. 114 Mary 16, SP Road Painting
3. Output is one relation. 115 Brat 18, GP Road Stamp collection
4.22 | Unit 4  •  Databases

σ Hobby = ‘stamp. Collection’(person) In the output table, John name has appeared once, project
The above given statement displays all tuples (or) records operation eliminated duplicates.
with hobby ‘stamp collection’. 2. pName, address (person)
Output: Output:
Id Name Address Hobby Name Address

112 John 12, SP Road Stamp collection John 12, SP Road


115 Brat 18, GP Road Stamp collection Mary 16, SP Road
Bart 18,GP Road
Selection condition can use following operators:
<, ≤, >, ≥, =, ≠ Expressions:
1. <attribute> operator <attribute>
pid,name (s hobby = ‘stamp collection’ OR Hobby= ‘coin collection’ (person))
2. <attribute> operator <constant>
Output:
Example:  Salary ≥ 1000 Id Name
3. <Condition> AND/OR <condition>
112 John
Example:  (Experience > 3) AND (Age < 58) 115 Bart
4. NOT <condition>
The above given relational algebra expression gives Ids,
Selection operation examples: names of a person whose hobby is either stamp collection
1. σ Id > 112 OR Hobby = ‘paint’ (person) (or) coin collection.
It displays the tuples whose ID > 112 or Hobby is paint
2. σ Id > 112 AND Id < 115 (person) Set Operators
It displays tuples whose ID is greater than 112 and less Union (∪), Intersection (∩), set difference (–) are called
than 115 set operators. Result of combining two relations with a set
3. σ NOT (hobby = ‘paint’) (person) operator is a relation ⇒ all its elements must be tuples hav-
ing same structure. Hence scope of set operations is limited
It displays tuples whose hobby is not paint
to union compatible relations.
4. σ Hobby ≠ ‘paint’ (person)
It displays tuples whose hobby is not paint, displays all
tuples other than hobby paint. Union Compatible Relations
Selection operator: Produces table containing subset Two relations are union compatible if
of rows of argument table which satisfies condition. 1. Both have same number of columns
2. Names of attributes are same
3. Corresponding fields have same type
Project Operator (p) 4. Attributes with the same name in both relations have
The project operator is unary operator. It can be used to same domain.
keep only the required attributes of a relation instance and 5. Union compatible relations can be combined using
throw away others. Union, Intersection, and set difference.
Notation:  pA2, A2, … Ak(r) Where A1, A2, … AK is a list L of Example:
desired attributes in the scheme of r. Consider the given tables.
Result =  {  ( V1, V2, … VK)/Vi ∈ DOM (Ai), 1< i < k and Person (SSN, Name, Address, Hobby)
there is some tuple t in r, such that t.A1 = v1, t.A2 Professor (Id, Name, office, phone)
= v2, … t.AK = VK} person and professor tables are not union compatible.
  p Attribute List (Relation)
Take table 2.1 as reference. Union
1. pName (person) The result of union will be a set consisting of all tuples
appearing in either or both of the given relations. Relations
Output:
cannot contain a mixture of different kinds of tuples, they
Name
must be ‘tuple – homogeneous’. The union in the relational
John
algebra is not the completely general mathematical union;
Mary
rather, it is a special kind of union, in which we require the
Bart
two input relations to be of the same type.
Chapter 2  •  Structured Query Language  |  4.23

The general definition of relational union operator: Difference


Given are two relations ‘a’ and ‘b’ of the same type. The Like union and intersection, the relational difference opera-
union of those two relations, a union b, is a relation of the tor also requires its operands to be of the same type. Given
same type, with body consisting of all tuples ‘t’ such that ‘t’ are two relations ‘a’ and ‘b’ of the same type, Then, the dif-
appears in a or b or both. ference between those two relations, ‘a’ MINUS ‘b’ (in that
*  Union operation eliminates duplicates. order), is a relation of the same type, with body consisting
of all types t such that t appears in a and not b.
Here is a different but equivalent definition:
Given are two relations ‘a’ and ‘b’ of the same type. The 1. MINUS has a directionality to it, just as subtraction
union of those two relations, a union b, is a relation of the does in ordinary arithmetic (e.g., ‘6 – 3’ and ‘3 – 6’ are
same type, with body consisting of all tuples t such that t is not the same thing)
equal to (i.e., is a duplicate of) some tuple in a or b or both. 2. Redundant duplicate rows are always eliminated from
the result of UNION, INTERSECTION, EXCEPT
Union Operation (U) operations.
3. SQL also provides the qualified variants UNION ALL,
When union operation is applied on two tables it gives all INTERSECT ALL and EXCEPT ALL, where dupli-
the tuples in both without Repetition. cates are retained
Example: Set difference operation returns the tuples in the first
table which are not matching with the tuples of other table.
Table 2  Result of union operation

Roll. no. Name Semester Percentage Table 4  Result of R – S


22 Arun 7 45% Roll
Name Semester Percentage
R 31 Bindu 6 55% R–S= no.
58 Sita 5 35% 22 Arun 7 45%

Roll no. Name Semester Percentage Table 5  Result of S – R


S 28 Suresh 4 65% S–R= Roll no. Name Semester Percentage
31 Bindu 6 55% 28 Suresh 4 65%
44 Pinky 4 75% 44 Pinky 4 75%
58 Sita 5 35%
*  R – S ≠ S –R (both are different)
Roll no. Name Semester Percentage
22 Arun 7 45% Example:
R∪S
31 Bindu 6 55% A
58 Sita 5 35% Supplier number Supplier name Status City
44 Pinky 4 75% SN1 MAHESH 40 HYDERABAD
28 Sita 5 35% SN3 SURESH 40 HYDERABAD

Intersection B

Like union, Intersection operator requires its operands to Supplier number Supplier number Status City
be of the same type. Given are two relations a and b of the SN3 SURESH 40 HYDERABAD
same type, then, the intersection of those two relations, ‘a’ SN4 RAMESH 30 CHENNAI
INTERSECT ‘b’, is a relation of the same type, with body
consisting of all tuples t such that t appears in both ‘a’ and UNION (A ∪ B)
‘b’.
Supplier number Supplier name Status City
Intersection operation returns tuples which are common
SN1 MAHESH 40 HYDERABAD
to both tables
SN3 SURESH 40 HYDERABAD
Table 3  Result of intersection operation SN4 RAMESH 30 CHENNAI

R∩S= Roll no. Name Semester Percentage


INTERSECTION (A ∩ B)
31 Bindu 6 55%
58 Sita 5 35% Supplier number Supplier name Status City
SN3 SURESH 40 HYDERABAD
4.24 | Unit 4  •  Databases

DIFFERENCE (A – B) Aggregate Operators


Supplier name Supplier name Status City SQL Supports the usual aggregate operators COUNT,
SN1 MAHESH 40 HYDERABAD SUM, AVG, MAX, MIN, EVERY and ANY, but there are a
few SQL-specific points.
DIFFERENCE (B – A)
1. The argument can optionally be preceded by the key-
Supplier name Supplier name Status City word DISTINCT, for example SUM (DISTINCT
SN4 RAMESH 30 CHENNAI column -name) to indicate that duplicates are to be
eliminated before the aggregation is done. For MAX,
MIN, EVERY and ANY, however, DISTINCT has no
Cartesian Product effect and should not be specified.
The Cartesian product of two sets is the set of all ordered 2. The operator COUNT (*), for this DISTINCT is not
pairs such that in each pair, the first element comes from allowed, and is provided to count all rows in a table
the first set and the second element comes from second without any duplicate elimination.
set.
3. Any NULLS in the argument column are eliminated
The result consists of all the attributes from both of the
before the aggregation is done, regardless of whether
two input headings. We define the Cartesian product of two
DISTINCT is specified, except in the case of COUNT
relations ‘a’ and ‘b’, as
(*), where nulls behave as if they were values.
‘a’ times ‘b’, where a and b have no common attrib-
ute names (If we need to construct the Cartesian product 4. After NULLS if any have been eliminated, if what is
of two relations that do have any such common attribute left is an empty set, COUNT returns zero. The other
names, therefore, we must use the RENAME operator first operators return NULL.
to rename attributes appropriately). AVG, MIN, MAX, SUM, COUNT
The Cartesian product operation is also known as CROSS
These functions operate on the multiset of values of col-
PRODUCT. This is also a binary set operation, but the rela-
umn of a relation and returns a value.
tions on which it is applied need not to be union compatible.
This operation is used to combine tuples from two relations 1. Find the average account balance at the Perryridge
in a combinational fashion. branch.
Example: Solution:  SELECT AVG (balance) FROM account
A B WHERE branch.name = ‘perryridge’
R X1 X2
X3 X4
2. Find the number of tuples in customer relation.

Solution:  SELECT count (*) FROM customer


C D
3. Find the number of depositors for each branch.
S Y1 Y2
Y3 Y4 Solution:  SELECT branch.name, COUNT (distinct
customer-name) FROM depositor, account WHERE
depositor. account-no = account account-no GROUPBY
A B C D
branch-name.
R×S= X1 X2 Y1 Y2
X1 X2 Y3 Y4
X3 X4 Y1 Y2 Nested Queries
X3 X4 Y3 Y4 Some queries require that existing values in the database be
fetched and then used in a comparison condition.
Such queries can be conveniently formulated by using
Example:  Transcript (StuId, coursecode, semester, grade)
nested queries, which are complete SELECT – FROM
Teaching (ProfId, coursecode, semester)
–WHERE blocks within the WHERE clause of another
pstuId,coursecode (Transcript) × pprofId,coursecode (Teaching) query. The other query is called the outer query.
The above expression returns
Table 6  Result of cross product In-Comparison Operator
Stu Id Course code Prof Id Course code The comparison operator IN, which compares a value ‘v’
... ... ... ... with a set of values ‘V’ and evaluates to TRUE if ‘v’ is one
of the elements in V.
Chapter 2  •  Structured Query Language  |  4.25

Example:  Consider the given database scheme and the 1. In co-related nested queries, the inner query depends
statement: on the outer query for its value.
2. Sub-query is executed repeatedly, once for each row
EMPLOYEE that is selected by the outer query.
FNAME INITIAL LNAME ENO DOB ADDRESS SALARY DNO 3. A correlated subquery is a sub query that contains a
reference to a table that also appears in the outer query.

DEPARTMENT
Example:  Consider the following correlated nested query:
SELECT *
D NAME DNO MANAGER-NO FROM table1
WHERE col1 ≥ ALL
DEPARTMENT–LOCATIONS
(SELECT col1 FROM table2 WHERE table2. col2 =
table1. col2)
DNO D-LOCATION
1. The subquery contains reference to a column of table1,
even though the sub-queries FROM clause does not
PROJECT mention a table table1
2. SQL has to check outside the sub-query and find Table
PNAME PNO P-LOCATION DNO
1 in the outer query
3. Suppose that Table 1 contains a row where col1 = 3 and
col2 = 4 and Table 2 contains a row where col1 = 5 and
WORKS–ON
col2 = 4
ENO PNO HOURS 4. The expression

WHERE col1 ≥ All (SELECT col1


Example:  Select distinct PNO from project where PNO FROM table2
IN (select PNO from project, department, employee where
P. DNO = D. DNO AND MANAGER. NO = ENO AND
3 ≥ 5 (false)
LNAME = ‘RAMYA’)
The first query selects. The project numbers that have a
‘Ramya’ involved as manager, while the second selects the (WHERE condition TRUE) Table1.
project numbers of projects that have a ‘Ramya’ involved col2 = table2. col2 4 = 4
as worker.
If a nested returns a single value, in such cases, it is per- So the expression as a whole is FALSE.
missible to use = instead of IN for the comparison operator. 5. It is evaluated from outside to inside
In general, the nested query will return a table, Which is
a set of multiset of tuples.
* SQL allows the use of tuples of values in comparisons by
Relational Calculus
placing them within parentheses. Relational calculus can define the information to be retrieved

Example:  SELECT DISTINCT ENO FROM WORKS - 1. In this, there is no specific series of operations.
ON WHERE (PNO, HOURS) IN (SELECT PNO, HOURS 2. Relational algebra defines the sequence of operations.
FROM WORKS - ON WHERE ENO = 929). 3. Relational calculus is closer to how users would for-
mulate queries, in terms of information requirements,
This query will select the employee numbers of all rather than in terms of operations.
employees who work on the same (PROJECT, HOURS)
combination on some project a particular employee whose Relational Calculus
ENO = ‘929’ works on. In this example, the IN operator
compares the subtuple of values in parentheses (PNO,
HOURS) for each tuple in works on with the set of union- Tuple Relational Domain Relational
compatible tuples produced by the nested query. calculus (variables Calculus (variables
range over tuples) range over domain
Correlated nested queries: Nested queries can be evaluated attributes)
by executing the sub query (or) Inner query once and sub-
stituting the resulting value (or) values into the WHERE 4. Relational calculus is based on predicate logic, gives
clause of the outer query. the usual quantifiers to construct complex queries.
4.26 | Unit 4  •  Databases

Tuple Relational Calculus Example: ∃ × ((X ∈ Boats) ∧ X.color) = ‘Red’)


There exists a tuple X in the boats relation whose color
Example:  Employee
is red.
E Id F Name L Name S alary (or)
201 John James 3000
∃ × ∈ Boats (X.color = ‘Red’)
202 Brat Frank 2000 Examples:
203 Mary Jennifer 3000 1. Find all sailors with rating above 8.
204 Adam Borg 2000
Sid Sname Rating Age
205 Smith Joyce 1000
28 Yuppy 9 35
Query 1: Display the employees whose salary is above 2000. Sailors: 35 Rubber 8 55
{E | ∃ E ∈ Employee(E.salary > 2000)} 44 grove 5 35
58 rusty 10 35
Output:
E Id F Name L Name Salary Solution: {s|s ∈ sailors ∧ s. rating > 8}
201 John James 3000 Output
203 Mary Jennifer 3000
Sid Sname Rating Age
Query 2: Display the employee Ids whose salary is above R= 28 yuppy 9 35
1000 and below 3000. 58 rusty 10 35
{P | ∃ E ∈ Employee ((E.salary > 1000 ∧ E.salary <
3000) ∧ P.EId = E.EId)} 2. Find names and ages of sailors with rating > 8.
P is a table, in which EIds are stored, from tuples which
satisfies the given condition. Solution: {R
| ∃ S ∈ sailors (s.rating > 8 ∧ R.sname =
s.name ∧ R.age = s.age)
Output:
Tuple Relational Calculus

sname age
A non-procedural language, where each query is of the
yuppy 35
form {t| p(t)}. It is a set of all tuples t such that predicate p
rusty 35
is true for t, t is a tuple variable, t [A] denotes the value of
tuple ‘t’ on attribute A.
{T| p (T)} Join Operation in Tuple Relational Calculus
T is a tuple and P (T) denotes a formula in which tuple vari- Examples:
able T appears. 3. Find sailors rated > 7 who have reserved boat = 103.

1. ∀ × (P(X)) Solution:  {S | S ∈ sailors ∧ s.rating > 7 ∧ ∃ R (R ∈ reserves


∀ is called the universal or ‘for all’ quantifier because ∧ R.sid = s.sid ∧ R.bid = 103)}
every tuple in ‘the universe of ’ tuples must make F 4. Find sailors rated > 7 who have reserved a red boat.
true to make the quantified formula true.
Only true if p(X) is true for every X in the universe. Solution:  {S | S ∈ sailors ∧ s.rating > 7 ∧ ∃ R (R ∈ reserves ∧
R.sid = s.sid ∧ ∃ B( Boats ∧ B.bid = R.bid ∧ B.color = ‘Red’))}
Example:  ∀ × (x.color = ‘Red’)
means everything that exists is red.
Division Operation in Tuple
Example: ∀ × ((x ∈ Boats) ⇒ (X. color = ‘Red’)) Relational Calculus
‘⇒’ is a logical implication. a ⇒ b means that if a is Examples
true, b must be true 1. Find sailors who have reserved all boats.
(or)
∃ × ∈ Boats (X.color = ‘Red’) Solution:  {S | S ∈ sailors ∧ ∀ B ∈ boats (∃ R ∈ reserves
For every ‘x’ in the boats relation, the color must be (s.sid = R.sid ∧ B.bid = R.bid))}
red.
Domain Relational Calculus
2. ∃ × (P(X))
1. Tuple relational and domain relational are semantically
∃ is called the existential or ‘there exists’ quantifier
similar.
because any tuple that exists in ‘the universe of’ tuples
2. In TRC, tuples share an equal status as variables, and
may take F true, to make the quantified formula true.
field referencing can be used to select tuple parts.
Chapter 2  •  Structured Query Language  |  4.27

3. In DRC formed variables are explicit. Features


4. DRC query has the following form. 1. Strong data protection
{<x1, x2, … xn > /P(<x1, x2, … , xn>} 2. Robust transactional support
Result included all tuples <x1, x2, … xn > 3. High performance
That make the formula p(<x1, x2, … xn>) true. 4. High availability
5. Formula given in DRC is recursively defined. First start 5. Security and flexibility to run anything
with simple atomic formula and expand the formulas 6. Easy to manage
by using the logical connectives. 7. User friendly
6. A variable that is not bound is free.
7. The variable X1, X2, …, Xn that appear in the left side of General Structure
‘/’ must be the only free variable in the formula p(…). SELECT ... FROM ... WHERE
Example:  Consider the employee table given in the above SQL is divided into two languages
Example. 1. DML (data manipulation language)
The use of quantifiers ∃ x and ∀ x in a formula is said to SELECT: Extracts data from a database table.
bind x UPDATE: Updates data in a database table.
Query 1: Display the Employees whose salary is above DELETE: Deletes data from a database table.
2000? INSERT INTO: Inserts new data into database table.
{<I, F, L, S> / <I, F, L, S> ∈ Employee ∧ S > 2000} 2. DDL (data definition language)
Query 2: Display the EIds of Employees, whose salary is CREATE TABLE - creates a new database table.
above 1000 and below 3000? ALTER TABLE - Alters a database table.
{<I> / ∃F, L, S(<I, F, L, S > ∈ Employee ∧ (S > 1000 ∧ S < 3000))} DROP TABLE - deletes a database table.
CREATE INDEX - Creates an index (search key).
SQL (Structured Query Language) DROP INDEX - Deletes an index.
RENAME – Changes the name of the table.
When a user wants to get some information from a database
file, he/she can issue a query. A query is a user-request to Types of keys:
retrieve data (or) information with a certain condition. SQL 1. Candidate key
is a query language that allows user to specify the condi- 2. Primary key
tions (instead of algorithms) 3. Super key
4. Foreign key
Concept of SQL 5. Composite primary key
The user specifies a certain condition. The program will go In relational database, ‘keys’ play a major role. Keys are
through all the records in the database file and select those used to establish and identify relation between relations (or)
records that satisfy the condition. The result of the query tables.
will be stored in the form of a table. Keys are used to ensure that each record within a table
can be uniquely identified by combining one or more fields
Features of SQL (or) column headers within a table.
1. SQL is a language of database. It includes database Candidate key: A candidate key is a column or set of col-
creation, deletion, fetching rows and modifying rows. umns in a table that contains unique values, with these we
2. SQL is a structured query language for storing, manip- can uniquely identify any database record without referring
ulating and retrieving data stored in relational database. to any other columns data.
3. It allows users to describe the data. Each table may have one or more candidate keys, among
4. It allows users to create and drop database and tables. the available candidate keys, one key is preserved for pri-
5. It allows users to create view, functions in a database. mary key.
6. Allows users to set permissions on tables and views. A candidate key is a subset of a super key.
7. The standard SQL commands to interact with rela- Example:  Student
tional database are CREATE, SELECT, UPDATE, First
INSERT, DROP and DELETE. StudentId Last name Course Id
name
8. The commands can be classified as follows: CS00345 Jim Black C2
•• Data query language: SELECT – It retrieves par- CS00254 Carry Norris C1
ticular rows which satisfies the given condition. CS00349 Peter Murray C1
•• Data definition language: CREATE, ALTER, DROP. CS00196 John Mc Cloud C3
•• Data manipulation language: INSERT, UPDATE, CS00489 Brat Holland C4
DELETE CS00553 Mary Smith C5
4.28 | Unit 4  •  Databases

In the above table, we have studentId that uniquely identifies Foreign key: A foreign key is a column or group of columns
the students in a student table. This would be a candidate in a relational database table that provides connectivity
key. between data in two tables.
In the same table, we have student’s first name and last 1. The majority of tables in a relational database system
name, which are also candidate keys. adhere to the concept of foreign key.
1. If we combine first name and last name then also it 2. In complex databases, data must be added across mul-
becomes a candidate key. tiple tables, thus the link or connectivity has to be
2. Candidate key must (have) maintained among the tables.
•• Unique values 3. The concept of Referential Integrity constraint is
•• No null values derived from Foreign key.
•• Minimum number of fields to ensure uniqueness. Example:  Emp
•• Uniquely identify each record in the table.
EId EName Dept – No
3. The candidate keys which are not selected for primary
key are known as secondary keys or alternative keys.
Dept
Primary key: A primary key is a candidate key that is most Dept-No DName
suitable (or) appropriate to become main key of the table.
1. It is a special relational database table column ((or)
In the above specified tables, Dept-No is common to both
combination of columns)
the tables, In Dept table it is called as primary key and in
2. Primary key main features are
Emp table it is called as foreign key.
•• It must contain a unique value for each row of data.
These two tables are connected with the help of
•• It cannot contain null values.
‘Dept-No’ field
Example:  We can choose primary key as studentId which 1. For any column acting as a foreign key, a correspond-
is mentioned in the table given in above example. ing value should exist in the link (or) connecting table.
Composite primary key: A key that consists of two or more 2. While inserting data and removing data from the for-
attributes that uniquely identify an entity is called compos- eign key column, a small incorrect insertion or dele-
ite key or composite primary key. tion destroys the relationship between the two tables.

Example:  Customer
SQL Commands
Cust-Id Order-Id Sale-details
SELECT statement
C1 O–2 Sold
The most commonly used SQL command is SELECT state-
C1 O–3 Sold
ment. The SQL SELECT statement is used to query or retrieve
C2 O–2 Sold data from a table in the database. A query may retrieve infor-
C2 O–3 Sold mation from specified columns or from all of the columns in
the table. To create a simple SQL SELECT statement, you
Composite primary key is {cust-Id, order-Id} must specify the column(s) names and the table name.
Super key: A super key is a combination of attributes that Syntax: SELECT column-name (s) from table name
can be uniquely used to identify a database record. A table
can have any number of super keys. Example:  Persons
Lastname Firstname Address City
1. Candidate key is a special subset of super keys.
Hansen Ola SpRoad,-20 Hyd
Example:  Customer
Svendson Tove GPRoad,-18 Secbad
Customer name Customer Id SSN Address DOB Petterson Kari RpRoad,-19 Delhi

1. SELECT lastname FROM persons


Assume that we can guarantee uniqueness only for SSN
field, then the following are some of the super keys possible. Output:
Lastname
1. {Name, SSN, DOB}
Hansen
2. {ID, Name, SSN}
Svendson
In a set of attributes, there must be at least one key (could
Petterson
be primary key or candidate key)
Chapter 2  •  Structured Query Language  |  4.29

2. SELECT lastname, firstname FROM persons


BETWEEN - Between an inclusive range.
Output: LIKE - Search for a pattern
Lastname Firstname Example:  Persons
Hansen Ola
Lastname Firstname Address City Year
Svendson Tove
Hansen Ola SPRoad, 16 Hyd 1956
Petterson Kari
Svendson Tiva GPRoad, 18 Sec 1977
Smith Ole RPRoad, 19 Hyd 1986
DISTINCT statement
Petterson Kari SPRoad, 17 Sec 1985
Returns distinct values. It eliminates duplicate values.
Syntax: Select DISTINCT column_name (s) from table-name 1. SELECT * FROM persons
Example:  Orders Output: It displays the entire table
Company Order.No 2. SELECT * FROM persons WHERE city = ‘Hyd’
IBM 3412

Output:
DELL 5614
WIPRO 4412 Lastname Firstname Address City Year

DELL 4413 Hansen Ola SPRoad, 16 Hyd 1956


Smith Ole RPRoad, 19 Hyd 1986
1. SELECT company FROM orders

Output: LIKE condition


Company The LIKE operator is used to list all rows in a table whose
IBM column values match a specified pattern. It is useful when
DELL you want to search rows to match a specific pattern, or when
WIPRO you do not know the entire value. For this purpose, we use a
DELL wildcard character ‘%’.
2. SELECT DISTINCT company FROM orders The LIKE condition is used to specify a search for a pat-
tern in a column.
Company A ‘%’ sign can be used to define wildcards (missing let-
IBM ters in the pattern) both before and after the pattern.
DELL Syntax: SELECT column FROM table WHERE column
WIPRO LIKE pattern
1. SELECT * FROM persons WHERE Firstname LIKE
WHERE statement ‘O%’
The WHERE clause is used when you want to retrieve spe-
cific information from a table excluding other irrelevant Solution:  SQL statement will return persons with first
data. By using WHERE clause, we can restrict the data that names that start with a letter ‘O’
is retrieved. The condition provided in the WHERE clause Output:
filters the rows retrieved from the table and gives only those Lastname Firstname Address City Year
rows which were expected. WHERE clause can be used
Hansen Ola SPRoad, 16 Hyd 1956
along with SELECT, DELETE, UPDATE statements.
The WHERE clause is used to specify a selection condi- Smith Ole RPRoad, 19 Hyd 1986
tion. All conditions are specified in this clause.
2. SELECT * FROM persons WHERE Firstname LIKE
Syntax: SELECT column FROM table WHERE column ‘%a’
operator value. Solution:  SQL statement will return persons whose first
Operates used in where clause: name ends with letter ‘a’.
= Output:
< > (not equal) (or) ! =
Last name First name Address City Year
>
< Hansen Ola SPRoad, 16 Hyd 1956
>= Svendson Tiva GPRoad, 18
Sec.
1977
<= bad
4.30 | Unit 4  •  Databases

3. SELECT * FROM persons WHERE firstname LIKE UPDATE


‘%la%’ The update statement is used to modify the data in a table.
Solution:  SQL statement returns persons whose firstname Syntax: UPDATE table_name
contains ‘la’. The word sequence ‘la’ may come at any place SET Column_name = new_value
in the word. WHERE column_name = some_value.
Output: 1. Add a first name (Nine) to the person whose last name
Last name First Name Address City Year is ‘Rasmussen’?
Hansen Ola SPRoad, 16 Hyd 1956 Solution:  UPDATE person SET Firstname = ‘Nine’
WHERE Lastname = ‘Rasmussen’
String operations 2. Change the address and add the name of the city as
1. ‘%idge%’matches ‘Rockridge’, ‘Ridgeway’, ‘Perryridge’. Hyd of a person with last name Rasmussen?
2. ‘_____’ matches a string of three characters.
Solution:  UPDATE person
3. ‘_____%’ matches a string of at least rhree characters.
SET Address = ‘street 12’,
city = ‘Hyd’
INSERT INTO statement WHERE Lastname = ‘Rasmussen’
This statement is used to insert new rows into a table. While
inserting a row, if you are adding values for all the columns
of the table you need not specify the column(s) name in the DELETE statement
SQL query. But you need to make sure the order of the val- The DELETE statement is used to delete rows from a table.
ues is in the same order as the columns in the table. When The WHERE clause in the SQL delete command is optional,
adding a row, only the characters or data values should be and it identifies the rows in the column that gets deleted. If
enclosed with single quotes and ensure the data type of the you do not include the WHERE clause, all the rows in the
value and the column matches. One can specify the columns table will be deleted.
for which you want to insert data Syntax: DELETE FROM table_name
Syntax: INSERT INTO table-name (column1, column2 . . .) WHERE column_name = some_value
VALUES (value 1, value2 . . .) 1. Delete all rows?
1. INSERT INTO persons VALUES (‘Hetland’, ‘Camilla’, Solution:  DELETE * FROM table_name
‘HPRoad 20’, ‘Hyd’)
Output:
Cartesian product
Last name First Name Address City
The Cartesian product of two sets is the set of all ordered
Hansen Ola S.P Road 16 Hyd pairs of elements such that the first element in each pair
Svesdon Tiva GP Road 18 Secbad belongs to the first set and the second element in each pair
Smith Ole RP Road 19 Hyd belongs to the second set. It is denoted by cross(X).
Petterson Kari SP Road 17 Secbad
For example, given two sets:
Hetlan Camilla HPRoad, 20 Hyd
S1 = {1, 2, 3} and S2 = {4, 5, 6}
2. Insert data into specified columns The Cartesian product S1 × S2 is the set
INSERT INTO persons (Lastname, Address) VALUES {(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5),
(‘Rasmussen’, ‘street 67’) (3, 6)}
Output:
Example:
Last name First Name Address City
Female Male
Hansen Ola SP Road 16 Hyd
Name Job Name Job
Svesdon .Tiva GP Road 18 Secbad
Komal Clerk Rohit Clerk
Smith Ole RP Road 19 Hyd
Ankita Sales Raju Sales
Petterson Kari SP Road 17 Secbad
Hetlan Camilla HP Road 20 Hyd Assume that the tables refer to male and female staff,
Rasmussen Street 67 respectively. Now, in order to obtain all possible inter-staff
marriages, the cartesian product can be taken.
Chapter 2  •  Structured Query Language  |  4.31

Male-Female We may specify ‘desc’ for descending order (or) ‘asc’ for
ascending order. - ‘asc’ is default.
Female name Female job Male name Male job
Komal Clerk Rohit Clerk Example:  ORDERBY customer-name desc.
Komal Clerk Raju Sales
Join (⋈)
Ankita Sales Rohit Clerk SQL Join is used to get data from two (or) more tables,
Ankita Sales Raju Sales which appear as single table after joining.

Examples: 1. Join is used for combining columns from two or more


tables by using values common to both tables.
1. Find the Cartesian product of borrower and loan?
2. Self Join: A table can also join to itself is known as self
Solution:  SELECT * FROM borrower, loan join. Types of JOIN
2. Find the name, loan-no, and loan amount of all cus- 1. INNER JOIN
tomers having a loan at the Perryridge branch? 2. OUTER JOIN
(i)  LEFT OUTER JOIN
Solution:  SELECT customer_name, borrower. loan_ (ii)  RIGHT OUTER JOIN
number, amount FROM borrower, loan WHERE borrower. (iii)  FULL OUTER JOIN
loan-no = Loan.loan_no AND branch_name = ‘perryridge’
1.  INNER JOIN (or) EQUI JOIN
3. Find all loan numbers for loans made at the perryridge
branch with loan amount greater than 1200? It is a simple JOIN in which result is based on matching
tuple, depending on the equality condition specified in the
Solution:  SELECT loan-no FROM loan WHERE branch. query.
name = ‘perryridge’ AND amount > 1200
Syntax: SELECT Column-names FROM table name1
Comparison operator INNER JOIN table name 2 WHERE table name 1. Column
name = table name 2.column – name.
Relation algebra includes six comparison operators (=, < >,
<, >, < =, > =). These are proposition forming operators on Example:  Class
terms. For example, x < > 0 asserts that x is not equal to 0. SID Name
It also includes three logical operators (AND, OR, NOT).
11 Ana
These are proposition forming operators on propositions.
12 Bala
Example:  x > 0 and x < 8 13 Sudha
Comparison results can be combined using the logical con- 14 adam
nections AND, OR NOT
Info
1. Find the loan-no of those loans with amounts between
90,000 and 1,00,000? SID City
11 Bangalore
Solution:  SELECT loan-no FORM loan WHERE amount
12 Delhi
BETWEEN 90,000 AND 1,00,000. SQL allows renewing
relations and attributes using ‘AS’ clause 13 Hyderabad

2. Find the name, loan-no and loan amount of all custom- SELECT *
ers, rename the column name loan-no as loan.id? FROM Class INNER JOIN Info
Solution:  SELECT customer.name, borrower.loan no AS WHERE Class.SID = Info.SID
loan.id, amount FROM borrower, loan, WHERE borrower. Result:
loan-no = loan.loan-no
SID Name SID City

Ordering of Tuples 11 Ana 11 Banglore


12 Bala 12 Delhi
It lists the tuples in alphabetical order.
13 Sudha 13 Hyderabad
Example:  List in alphabetic order, the names of all customers
having a loan in Perryridge branch? NATURAL JOIN:
Solution:  SELECT customer-name FROM borrower NATURAL JOIN is a type of INNER JOIN which is based
WHERE branch.name = ‘perryridge’ ORDERBY customer- on column having same name and same data type present in
name two tables on which join is performed.
4.32 | Unit 4  •  Databases

Syntax: SELECT  * Query:


FROM table-name1 NATURAL JOIN table-name 2 SELECT *
FROM Class1 RIGHT OUTER JOIN Info1
Example:  Consider the tables class and Info, and the
ON(class1.SID = Info1.SID)
following Query
SELECT * Result:
FROM   class NATURAL JOIN Info SID Name City
16 Arun Chennai
Result:
18 NULL Noida
SID Name City
11 Ana Bangalore FULL OUTER JOIN: The full outer Join returns the tuples
12 Bala Delhi with the matched data of two tables, remaining rows of both
13 Sudha Hyderabad
left table and Right table are also included.

Both tables being joined have SID column (same name and Example:  Consider the tables class 1 and Info1
same data type), the tuples for which value of SID matches Query:
in both the tables, appear in the result. SELECT *
FROM class1 FULL OUER JOIN Info1
Dangling tuple: When NATURAL JOIN is performed on ON(class1.SID = Info1.SID)
two tables, there would be some missing tuples in the result
Result:
of NATURAL JOIN
SID Name City
Those missing tuples are called Dangling tuples. In the
16 Arun Chennai
above example, the number of dangling tuples is 1 that is
17 Kamal NULL
14 Adam 18 NULL Noida
OUTER JOIN: Outer Join is based on both matched and ALTER command: ALTER command is used for altering the
unmatched data. table structure
LEFT OUTER JOIN: Left outer Join returns the tuples 1. It is used to add a new column to existing table.
available in the left side table with the matched data of 2 2. To rename existing column.
tables and null for the right tables column. 3. ALTER is used to drop a column.
Example:  Consider the table’s class and Info 4. It is used to change data type of any column or modify
SELECT * its size.
FROM class LEFT OUTER JOIN Info Add new column: By using alter command, we can add a
ON(class.SID = Info. SID) new column to the table.
Result:
Syntax: ALTER table table-name ADD(column-name data
SID Name City type).
11 Ana Banglore
Example:  Consider a student table.
12 Bala Delhi
SID S Name Grade
13 Sudha Hyderabad
14 adam NULL

RIGHT OUTER JOIN: RIGHT OUTER JOIN returns the Add a new column called address
tuples available in the Right side table with the matched ALTER table student ADD (address char);
data of 2 tables and NULL for the left table’s column.
Example:  Class 1 Example:  Add multiple columns, parent-name, course-
Name, date-of-birth to student table.
SID Name
16 Arun ALTER table student ADD (parent-name
17 Kamal varchar(60), course-Name varchar(20),
date-of-birth date);
Info 1
SID City Example:  Change the data type of column address to varchar?
16 Chennai
17 Noida ALTER table student modify(address varchar(30))
Chapter 2  •  Structured Query Language  |  4.33

Example:  Rename a column address to Location Syntax: Drop table table-name


Rename: This command is used to rename a table.
ALTER table student rename address to Location
Syntax: Rename table old-table-name to new-table-name.
TRUNCATE command: Truncate command removes all Example:  Rename table Employee to New-Employee.
tuples from a table, this command will not destroy the tables
DROP a column: Alter command can be combined with
structure.
DROP command to remove columns from a table.
Syntax: Truncate table table-name
Syntax: alter table table-name DROP(column-name)
DROP Command: DROP query removes a table completely
from database. This command will destroy the table structure. Example:  Alter table student DROP (grade)

Exercises
Practice Problems 1 (C) SELECT *
Directions for questions 1 to 20:  Select the correct alterna- FROM Persons
tive from the given choices. WHERE last-name=’svendson’
AND (first-name=’tove’ AND first-name=’ola’)
1. Consider the given table called Persons (D) SELECT *
FROM Persons
P-Id Lastname Firstname Address City
WHERE last-name=’svendson’
1 Hansen ola Timoteivn -10 Sandnes OR (first-name=’tove’ AND first-name=’ola’)
2 Svendson Tove Brazil-50 Sandnes 3. Write an SQL statement to add a new row, but only in
3 Petterson Kari Storgt-20 Stavanger specified columns, for the persons table add data into
4 Joseph ole Brazil-20 Sandnes columns ‘P-Id’, ‘Last name’ and the ‘First name’ with
values (5, Teja, Jakob)?
Write a query to select the persons with first name (A) INSERT INTO Persons VALUES(5,‘teja’,‘jakob’)
‘Tove’ and last name ‘Svendson’? (B) INSERT INTO Persons VALUES(5,teja,jakob)
(A) SELECT * (C)  INSERT INTO Persons (P-Id, last-name, first-
FROM Persons name) VALUES(5,’teja’,’jakob’)
WHERE first-name=’tove’ (D)  INSERT INTO Persons(P-Id, last-name, first-
AND last-name=’svendson’ name) VALUES(5,teja,jakob)
(B) SELECT * 4. Write an SQL statement:
FROM Persons (i) To select the persons living in a city that starts
WHERE first-name=’tove’ with ‘S’ from the ‘Persons’ table?
OR last-name=’svendson’ (A) SELECT *
(C) SELECT first-name FROM Persons
FROM Persons WHERE city LIKE ‘s__’.
WHERE first-name=’tove’ (B) SELECT *
AND last-name=’svendson’ FROM Persons
(D) SELECT last-name WHERE city LIKE ‘s%’.
FROM Persons (C) SELECT *
WHERE first-name=’tove’ FROM Persons
AND last-name=’svendson’ WHERE city LIKE ‘%s’.
(D) SELECT *
2. Write a query to select only the persons with last name
FROM Persons
‘Svendson’ and the first name equal to ‘Tove’ or ‘ola’?
WHERE city LIKE ‘_s%’.
(A) SELECT * (ii) To select the persons living in a city that contains
FROM Persons the pattern ‘tav’ from ‘Persons’ table?
WHERE last-name=’svendson’ (A) SELECT *
AND first-name=’tove’ FROM Persons
(B) SELECT * WHERE city LIKE ‘_tav_’.
FROM Persons (B) SELECT *
WHERE last-name=’svendson’ FROM Persons
AND (first-name=’tove’ OR first-name=’ola’) WHERE city LIKE ‘_tav%’.
4.34 | Unit 4  •  Databases

(C) SELECT * (i) Find out the students who have scored more than
FROM Persons 80 marks, and display them in descending order
WHERE city LIKE ‘%tav_’. according to their marks?
(D) SELECT * (A) SELECT student-name,marks
FROM Persons FROM Result
WHERE city LIKE ‘%tav%’. WHERE marks > 80
(iii) To select the persons whose last name starts with ORDERBY marks DESC
‘b’ or ‘s’ or ‘p’ ? (B) SELECT *
(A) SELECT * FROM Result
FROM Persons WHERE marks > 80
WHERE last-name LIKE ‘b-s-p’ ORDERBY marks DESC
(B) SELECT * (C) SELECT student-name,marks
FROM Persons FROM Result
WHERE last-name LIKE ‘b%s%p’ WHERE marks > 80
(C) SELECT * ORDERBY marks
FROM Persons (D) (A) and (B)
WHERE last-name LIKE ‘b%s%p%’ (ii) 
From the above table, find out the top-most three
(D) SELECT * students.
FROM Persons (A) SELECT student-name
WHERE last-name LIKE ‘[bsp]%’ FROM Result
5. Consider the given table called ‘Persons’ ORDERBY marks DESC > 3
(B) SELECT student-name
P-Id Last-name First-name Address City FROM Result
1 Hansen ola Timoteivn-10 Sandnes ORDERBY marks DESC = 3
2 Svendson Tove Brazil-50 Sandnes (C) SELECT student-name
3 Petterson Kari Storgt-20 Stavanger FROM Result
ORDERBY marks DESC limit 3
and the ‘Orders’ table (D) None of these
O-Id Order No P-Id 8. From the table ‘Results’, Identify the suitable SQL
11 77895 3 expression?
12 44678 3 (i) Find out the student Who stood 2nd?
13 22456 1 (A) SELECT student-name
14 24562 1
FROM Result
ORDERBY marks DESC limit 2
15 34764 5
(B) SELECT student-name
perform NATURAL JOIN operation on both the tables FROM Result
and what is are the O_Id’s displayed in the result? ORDERBY marks DESC limit 1,1
(A) 11, 12, 13 (B) 11, 13, 14 (C) SELECT student-name
(C) 11, 12, 13, 14 (D) 12, 13, 14 FROM Result
6. Write an SQL to perform FULL JOIN operation on
ORDERBY marks DESC limit 1,2
both ‘Person’ and ‘Orders’ tables and What is the num- (D) SELECT student-name
ber of tuples in the Result? FROM Result
(A) 4 (B) 5 ORDERBY marks DESC limit 2,1
(C) 6 (D) 7 (ii) Find out how many students scored > = 80.
(A) SELECT COUNT(*)
7. Consider the given table ‘Result’.
FROM Result
Student Name Marks WHERE marks > = 80
A 55 (B) SELECT COUNT
B 90 FROM Result
C 40 WHERE marks > = 80
(C) SELECT SUM(*)
D 80
FROM Result
E 85
WHERE marks > = 80
F 95 (D) SELECT SUM
G 82 FROM Result
WHERE marks > = 80
Chapter 2  •  Structured Query Language  |  4.35

9. Consider the given tables: (ii) 


Find the loan-numbers from loan table where
branch-name is Dhaka?
Customer
(A) SELECT loan-number
Customer name Customer street Customer city FROM loan
Sonam Mirpurroad Dhaka WHERE branch-name=’dhaka’
Sonam Aga KhaRoad Bogra (B) SELECT loan-number
Anusha XYZRoad Kanchi
FROM branch-name=’dhaka’
(C) SELECT loan-number
Nandy MirpurRoad Dhaka
FROM Loan × Borrower
Account (D) Both (A) and (C)
11. (i) 
Find all customers who have only accounts but no
Account number Customer name Balance
loans.
A-101 Anusha 1000 (A) SELECT customer-name
A-102 Anusha 1500 FROM depositor LEFT OUTER JOIN Bor-
A-103 Sonam 2000 rower ON
A-104 Nandy 2500 Depositor.customer-name=Borrower.cus-
tomer-name
From the customer table, find out the names of all the WHERE loan-number IS NULL
customers who live in either Dhaka or Bogra? (B) SELECT customer-name
(A) SELECT customer-name FROM depositor LEFT OUTER JOIN Bor-
FROM customer rower ON
WHERE customer-city=’dhaka’ OR Depositor.customer-name = Borrower.cus-
customer-city=’bogra’ tomer-name
(B) SELECT customer-name WHERE loan-number=NULL
FROM customer (C) SELECT customer-name
WHERE customer-city=dhaka OR  FROM depositor RIGHT OUTER JOIN
customer-city=’bogra’ Borrower ON
(C) SELECT customer-name Depositor.customer-name=Borrower.cus-
FROM customer tomer-name
WHERE customer-city=’dhaka’ AND WHERE loan-number IS NULL
customer-city=’bogra’ (D) SELECT customer-name
(D) SELECT customer-name  FROM depositor RIGHT OUTER JOIN
FROM customer Borrower ON
WHERE customer-city=’dhaka’ EXIST Depositor.customer-name=Borrower.cus-
customer-city=’bogra’ tomer-name
10. Consider the given tables WHERE loan-number=NULL
Loan (ii) Find the names of all customers who have either
Loan Number Branch Name Amount an account or loan but not both.
L-101 Dhaka 1000
Borrower
L-103 Khulna 2000
Customer name Loan no.
Borrower: Sonam L-101
Customer name Loan number Sonam L-102
Sonam L-101 Anusha L-103
Nandy L-103
Anusha L-103 Depositor
Customer name Account no.
(i) What are the number of tuples present in the result
Anusha A-102
of cross product of the above two tables?
(A) 4 (B) 5 Sonam A-103
(C) 6 (D) 7 Nandy A-104
4.36 | Unit 4  •  Databases

(A) SELECT customer name (C) SELECT SUM(salary)


FROM depositor FULL OUTER JOIN FROM Employee
Borrower ON GROUP BY Branch-name
Depositor.customer-name=Borrower.customer- (D) SELECT branch-name, SUM(salary)
name FROM Employee
 WHERE loan-number IS NULL OR Account- (iii) Find branch city, branch name Wise total salary,
number=NULL average salary and also number of employees.
(B) SELECT customer-name (A) SELECT branch-city, branch-name,
FROM depositor FULL OUTER JOIN SUM (salary), AVG(salary),
Borrower ON COUNT (Employee-name)
Depositor.customer-name = Borrower.customer- FROM Employee
name GROUP BY branch-city, branch-name
 WHERE loan-number IS NULL OR Account- (B) SELECT branch-city, branch-name,
number IS NULL SUM (salary), AVG (salary),
(C) SELECT customer-name COUNT (Employee-name)
FROM depositor FULL OUTER JOIN FROM Employee
Borrower ON GROUP BY branch-city
Depositor.customer-name = Borrower.customer- (C) SELECT branch-city, branch-name,
name SUM (salary), AVG (salary), COUNT (Em-
WHERE loan-number = NULL OR Account-num- ployee-name)
ber = NULL FROM Employee
(D) SELECT customer-name GROUP BY branch-name
FROM depositor FULL OUTER JOIN Borrower (D) SELECT branch-name, SUM (salary),
ON AVG (salary), COUNT (Employee-name)
Depositor.customer-name = Borrower.customer- FROM Employee
name GROUP BY branch-city, branch-name
WHERE loan-number=NULL OR Account-num- Common data for questions 13 to 15: Consider the SHIP­
ber IS NULL MENTS relation and write the SQL statements for the below
12. Consider the following ‘employee’ table
Employee name Branch name Branch city Salary SUPPLIERS
A DU Dhaka 1000 Supplier number Supplier name Status City

B DU Dhaka 2000 SN1 Suma 30 Hyderabad


SN2 Hari 20 Chennai
C BUET Dhaka 3000
SN3 Anu 10 Hyderabad
D KUET Khulna 4000
SN4 Mahesh 20 Bombay
E KU Khulna 5000 SN5 Kamal 30 Delhi
F RU Rajshahi 6000
PARTS
(i) Find the distinct number of branches appearing in Part number Part name Color Weight City
the employee relation. PN1 X Red 13.0 Chennai
(A) SELECT COUNT(branch-name) PN2 Y Green 13.5 Bombay
FROM Employee PN3 X Yellow 13.2 Hyderabad
(B) SELECT COUNT(DISTINCT branch-name) PN4 Y Green 14.1 Calcutta
FROM Employee PN5 Z Red 14.3 Hyderabad
(C) SELECT DISTINCT COUNT(branch-name) PN6 Z Blue 14.2 Bombay
FROM Employee
(D) SELECT COUNT(*) PROJECT
FROM Employee Project number Project name City
(ii) 
Find the total salary of all employees at each PJ1 Display Chennai
branch of the bank. PJ2 OCR Bombay
(A) SELECT branch-name, SUM(salary) PJ3 RAID Chennai
FROM Employee PJ4 SORTER Hyderabad
GROUP BY Branch-city PJ5 EDS Chennai
(B) SELECT branch-name, SUM(salary) PJ6 Tape Bombay
FROM Employee PJ7 Console Hyderabad
GROUP BY Branch-name
Chapter 2  •  Structured Query Language  |  4.37

SHIPMENTS (B) SELECT shipments.part-number


Supplier number Part number Project number Quantity FROM Shipments
GROUP BY shipments.part-number
SN1 PN1 PJ1 300
HAVING COUNT(shipments.supplier-num-
SN1 PN1 PJ4 400
ber)>=2
SN2 PN3 PJ1 350 (C) SELECT shipments.part-number
SN2 PN3 PJ2 450 FROM Shipments
SN2 PN3 PJ3 640 GROUP BY shipments.part-number>2
SN2 PN3 PJ4 320 (D)  SELECT shipments.part-number, COUNT
(shipments.supplier-number)>2
SN2 PN3 PJ5 330
FROM Shipments
SN2 PN3 PJ6 520
GROUP BY shipments.part-number
SN2 PN3 PJ7 480
(iii) Get supplier names for suppliers who supply part
SN2 PN5 PJ2 460 PN3?
SN3 PN3 PJ1 440 (A) SELECT DISTINCT suppliers.supplier-name
SN3 PN4 PJ2 410 FROM Supplier
SN4 PN6 PJ3 310 WHERE suppliers.supplier-number IN (SE-
SN4 PN6 PJ7 320
LECT Shipments.supplier-number
FROM Shipments
SN5 PN2 PJ2 340
WHERE Shipments.part-number=’PN3’)
SN5 PN2 PJ4 350
(B) SELECT DISTINCT suppliers.supplier-name
SN5 PN5 PJ5 360 FROM Supplier
SN5 PN5 PJ7 370  WHERE suppliers.supplier-number NOT
SN5 PN6 PJ2 380 IN(SELECT Shipments.supplier-number
SN5 PN1 PJ4 420 FROM Shipments
SN5 PN3 PJ4 440
WHERE Shipments.part-number=’PN3’)
(C) SELECT DISTINCT suppliers.supplier-name
SN5 PN4 PJ4 450
FROM Supplier
SN5 PN5 PJ4 400 WHERE suppliers.supplier-number EXCEPT
SN5 PN6 PJ4 410 (SELECT Shipments.supplier-number
13. (i) 
For each part supplied, get the part number and the FROM Shipments
total shipment quantity? WHERE Shipments.part-number=’PN3’)
(A) SELECT shipments.part-number, SUM (ship- (D) SELECT DISTINCT suppliers, supplier-name
ments.quantity) FROM Supplier
FROM Shipments WHERE suppliers.supplier-number
GROUP BY shipments.part-number UNION
(B) SELECT SUM(shipments.quantity) SELECT Shipments.supplier-number
FROM Shipments FROM Shipments
GROUP BY shipments.part-number WHERE Shipments.part-number=’PN3’
(C) SELECT shipments.part-number, SUM (ship- 14. (i) 
Get supplier names for suppliers who supply at
ments.quantity) least one blue part.
FROM Shipments (A) SELECT DISTINCT suppliers.supplier-name
GROUP BY shipments.quantity FROM Suppliers
(D) SELECT shipments.part-number, SUM (ship- WHERE suppliers.supplier-number
ments. part-number) IN (SELECT Shipments.supplier-number
FROM Shipments FROM Shipments
GROUP BY shipments.part-number WHERE Shipments.part-number
(ii) Get part numbers for parts supplied by more than IN (SELECT Parts.part-number
two suppliers? FROM Parts
(A) SELECT shipments.part-number WHERE Parts.color=’Blue’))
FROM Shipments (B) SELECT DISTINCT suppliers.supplier-name
GROUP BY shipments.part-number FROM Suppliers
HAVING COUNT(shipments.supplier-num- WHERE suppliers.supplier-number
ber) > 2 IN (SELECT Shipments.supplier-number
FROM Shipments
4.38 | Unit 4  •  Databases

WHERE Shipments.part-number NOT (B) SELECT DISTINCT suppliers.supplier-name


IN( SELECT Parts.part-number FROM Suppliers
FROM Parts WHERE NOT EXIST(SELECT *
WHERE Parts.color=’Blue’)) FROM Shipments
(C) SELECT DISTINCT suppliers.supplier-name WHERE Shipments.supplier-number = sup-
FROM Suppliers pliers.supplier-number
 WHERE suppliers.supplier-number NOT AND
IN(SELECT Shipments.supplier-number Shipments.part-number=’PN2’)
FROM Shipments (C) SELECT DISTINCT suppliers.supplier-name
WHERE Shipments.part-number FROM Suppliers
IN (SELECT Parts.part-number WHERE EXIST(SELECT *
FROM Parts FROM Shipments
WHERE Parts.color=’Blue’)) WHERE Shipments.supplier-number = sup-
(D) SELECT DISTINCT suppliers.supplier-name pliers.supplier-number
FROM Suppliers OR
WHERE suppliers.supplier-number Shipments.part-number=’PN2’)
IN (SELECT Shipments.supplier-name (D) SELECT DISTINCT suppliers.supplier-name
FROM Shipments FROM Suppliers
WHERE Shipments.part-number WHERE EXIST(SELECT *
IN (SELECT Parts.part-number FROM Shipments
FROM Parts WHERE Shipments.supplier-number = sup-
WHERE Parts.color=’Blue’)) pliers.supplier-number
(ii) Get supplier numbers for suppliers with status less UNION
than the current maximum status in the suppliers Shipments.part-number=’PN2’)
table: 15. (i) Get supplier names for suppliers who do not sup-
(A) SELECT Suppliers.supplier-number ply part PN2.
FROM suppliers (A) SELECT DISTINCT suppliers.supplier-name
WHERE Suppliers.status < (SELECT MAX FROM Suppliers
(Suppliers.status) WHERE NOT EXIST(SELECT *
FROM Suppliers) FROM Shipments
(B) SELECT Suppliers.supplier-number WHERE Shipments.supplier-number = sup-
FROM suppliers pliers.supplier-number
WHERE Suppliers.status<=(SELECT MAX AND
(Suppliers.status) Shipments.part-number=’PN2’)
FROM Suppliers) (B) SELECT DISTINCT suppliers.supplier-name
(C) SELECT Suppliers.supplier-number, FROM Suppliers
WHERE EXIST(SELECT *
MAX (Suppliers.status)
FROM Shipments
FROM suppliers
WHERE Shipments.supplier-number = sup-
WHERE Suppliers.status
pliers.supplier-number
(D) SELECT Suppliers.supplier-number AND
FROM suppliers Shipments.part-number=’PN2’)
WHERE Suppliers.status=MAX(Suppliers. (C) SELECT DISTINCT suppliers.supplier-name
status) FROM Suppliers
(iii) Get supplier names for suppliers who supply part WHERE EXCEPT(SELECT *
PN2? FROM Shipments
(A) SELECT DISTINCT suppliers.supplier-name WHERE Shipments.supplier-number = sup-
FROM Suppliers pliers.supplier-number
WHERE EXIST(SELECT * AND
FROM Shipments Shipments.part-number=’PN2’)
WHERE Shipments.supplier-number = sup- (D) SELECT DISTINCT suppliers.supplier-name
pliers.supplier-number FROM Suppliers
AND WHERE NOT EXIST(SELECT *
Shipments.part-number=’PN2’) FROM Shipments
Chapter 2  •  Structured Query Language  |  4.39

WHERE Shipments.supplier-number = sup- (B) SELECT parts.part-number


pliers.supplier-number FROM parts
OR WHERE Parts.weight>18
Shipments.part-number=’PN2’) UNION
(ii) Get supplier names for suppliers who supply all SELECT Shipments.supplier-name
parts. FROM shipments
(A) SELECT DISTINCT suppliers.supplier-name WHERE Shipments.supplier-number=’SN2’
FROM Suppliers (C) SELECT parts.part-number
WHERE NOT EXIST(SELECT * FROM parts
FROM Part WHERE Parts.weight>18
 WHERE NOT EXIST(SELECT * FROM UNION
Shipments SELECT Shipments.part-number,Shipments.
WHERE Shipments.supplier-number = sup- supplier-name
pliers.supplier-number FROM shipments
AND WHERE Shipments.supplier-number=’SN2’
Shipments.part-number=Parts.part-number)) (D) SELECT parts.part-Number, parts.color
(B) SELECT DISTINCT suppliers.supplier-name FROM parts
FROM Suppliers WHERE Parts.weight>18
UNION
WHERE EXIST(SELECT *
SELECT Shipments.part-number
FROM Part
FROM shipments
 WHERE NOT EXIST(SELECT * FROM
WHERE Shipments.supplier-number=’SN2’
Shipments
WHERE Shipments.supplier-number = sup- Common data for questions 16 and 17: Consider the fol-
pliers.supplier-number lowing relation: Teach
AND
Name Address course
Shipments.part-number=Parts.part-number))
(C) SELECT DISTINCT suppliers.supplier-name Zohar 40B,east city MD
Nisha 16/2, hyd BDS
FROM Suppliers
Zohar 40B, East city MS
WHERE NOT EXIST(SELECT *
Ravi New York MBA
FROM Part
WHERE EXIST(SELECT * FROM Shipments 16. The teacher with name Zohar teaching the course MS?
WHERE Shipments.supplier-number = sup- (A) sName = ‘Zohar’ teach = MS.
pliers.supplier-number (B) pName = ‘Zohar’ teach = MS.
AND (C) sname = ‘Zohar’ and course = ‘MS’ (teach).
Shipments.part-number=Parts.part-number)) (D) pName = ‘Zohar’ and course = ‘MS’ (teach).
(D) SELECT DISTINCT suppliers.supplier-name 17. Select the names of courses taught by Zohar?
FROM Suppliers (A) pcourse(sName = ‘Zohar’ (Teach))
WHERE EXIST(SELECT * (B) scourse(pName = ‘Zohar’ (Teach))
FROM Part (C) pcourse(sName = ‘MD’ (Teach))
WHERE EXIST(SELECT * FROM Shipments
(D) None
WHERE Shipments.supplier-number = sup- 18. Consider the join of a relation A with a relation B. If A
pliers.supplier-number has m tuples and B has n tuples. Then the maximum and
AND minimum sizes of the join respectively are.
Shipments.part-number=Parts.part-number)) (A) mn and m + n    (B) m + n and (m –n)
(iii) Get part numbers for parts that either weigh more (C) mn and m       (D) mn and 0
than-16 pounds or are supplied by supplier SN3, or 19. Match the following:
both?
(A) SELECT parts.part-number I Set intersection 1 R | × | S
FROM parts II Natural join 2 r – (r – s)
WHERE Parts.weight>18 III Division 3 ←
UNION
pR – S(r) – pR –S
SELECT Shipments.part-number
IV Assignment 4 (π R−S (r ) × s)
FROM shipments
−π R−S , s(r )
WHERE Shipments.supplier-number=’SN2’
4.40 | Unit 4  •  Databases

(A) I – 2, II – 1, III – 4, IV – 3 (A) r÷s


(B) I – 3, II – 4, III – 2, IV – 1 (B) π R − S (r ) − π R − S ((π R − S (r ) × s ) − π R − S ), s (r )
(C) I – 1, II – 2, III – 3, IV – 4 (C) Temp 1 ← pR – S (r)
(D) I – 2, II – 3, III – 4, IV – 1 Temp 2 ← pR – S(temp1 × s) –pR – S, s(r)
20. Which one is correct for division operations for rela-
result = temp 1 – temp 2
tion r and s (D) All the above

Practice Problems 2 7. Select the persons whose hobby is either painting (or)

Directions for questions 1 to 20:  Select the correct alterna- singing.


tive from the given choices. (A) sHobby = ‘painting’ OR Hobby = ‘singing’ (person)
1. The correct order of SQL expression is (B) sHobby = ‘painting’,’ singing’ (person)
(A) Select, group by, where, having (C) sHobby = ‘painting’ OR ‘singing’ (person)
(B) Select, where, group by, having (D) All are correct
(C) Select, group by, having, where 8. Select the persons whose age is above 21 and below 32:
(D) Select, having, where, group by (A) sage > 21 AND age < 32 (person)
2. Which one is not a query language?
(B) s21 < age < 32 (person)
(A) SQL (B) QBE
(C) sage > 21 OR age < 32 (person)
(C) Data log (D) MySQL
(D) sage < 21 AND age > 32 (person)
3. Like ‘a b \ % c d’ escape ‘\’ matches all the strings
(A) Ending with a b c d Common data for questions 9 and 10: Consider the fol-
(B) Beginning with a b c d lowing relation: Teach
(C) Beginning with a b c d
Name course Rating Age
(D) Beginning with a b % c d
Zohar MD 7 35
4. ‘_ _ _%’ matches any string of
(A) At least three characters Nisha BDS 8 27
(B) At most three characters Zohar MS 7 34
(C) Exactly three characters Ravi MBA 9 33
(D) exactly three characters ending with %
5. Which of the following are set operations?
9. Select the teachers whose rating is above 7 and whose
(i) Union age is less than 32?
(ii) Intersection (A) sRating > 7 AND Age < 32 (Teach)
(iii) Set Difference (B) sRating ≥ 7 AND Age < 32 (Teach)
(iv) Cartesian Product (C) sRating > 7 AND < 32 (Teach)
(A) (i), (ii), (iii) (D) Both (A) and (B)
(B) (i), (iii), (iv)
10.
Select the courses with rating above 7?
(C) (i), (iii), (ii), (iv)
(D) (i), (ii), (iv) (A) pcourse (srating > 7 (Teach))
(B) scourse (p rating > 7(Teach))
6. What is the purpose of project operation?
(C) pname, course (srating > 7 (Teach))
(A) It selects certain columns
(B) It selects certain rows (D) None
(C) It selects certain strings Common data for questions 11 and 12: Consider the follow-
(D) It selects certain integers ing schema of a relational database employee (empno, ename,
eadd) project (pno, pname) Work–on (empno, pno) Part(partno,
Common data for questions 7 and 8: Person partname, qty-on-hand, size) Use (empno, pno, partno, number)
Id Name Age Hobby 11.
Display the names of the employees who are working
11 Anu 21 Stamp Collection on a project named ‘VB’.
22 Kamal 32 Painting
(A) sname(employee ⋈ (spname = ‘VB’ project) ⋈ worked on)
(B) sname (employee ⋈ (ppname = ‘VB’ (project) ⋈ work on)
33 Ravi 24 Dancing
(C) pname (employee ⋈ (spname = ‘VB’ (project) ⋈ work on)
44 Ram 22 Singing
(D) pname (employee ⋈ (ppname = ‘VB’ (project) ⋈ work on)
Chapter 2  •  Structured Query Language  |  4.41

12. Display the names of the people who are not working (A) Names of the students who are working in either
for any project. projects ‘MS’ or ‘MD’
(A) pname (employee ⋈(pname (employee + work on) (B) Names of the students who are working in both the
(B) pname (employee – pname (employee ∩ work on) projects ‘MS’ or ‘MD’
(C) pname (employee – pname (employee ⋈ work on) (C) Names of the students who are not working in any of
the projects ‘MS’ or ‘MD’
(D) sname (employee – sname (employee ⋈ work on)
(D) None of the above
13. Consider the following tables: 16. ‘All rows corresponding to students whose sno’s are
A B C D C D between 10 and 20
b c e f e f
(i) Select * form student where SNo are between 5
AND 10
a b i j g h
(ii) Select * from student where SNO IN(5, 10)
b c g h (A) Only (i) (B) Only (ii)
b c a d (C) Both (A) and (B) (D) None
d i g h 17. UPDATE account SET

d j j k DA = basic * .2,
d i e f GROSS = basic * 1.3, Where basic > 2000;
(A) The above query displays DA and gross for all
R÷S those employees whose basic is ≥ 2000
A B (B) The above query displays DA and Gross for all
b c employees whose basic is less than 2000
(C) The above query displays updated values of DA as
d i
well as gross for all those employees whose basic
Which of the following statements is true? is > 2000
(A) R ÷ S = pA, B(R) – pA, B(pA, B(R) × S + R) (D) All the above
(B) R ÷ S = pA, B(R) – pA, B(pA, BR × S – R) 18. Given two union compatible relations R1(A, B) and R2(C,

D), what is the result of the operation
(C) R ÷ S = pA, B(R) – pA, B((pA, B(R) × S) – R)
R1 A = CAB = DR2?
(D) R ÷ S = pA, B(R) – pA, B(pA, B(R) × R – S) (A) R1 ∪ R2 (B) R1 × R2
(C) R1 – R2 (D) R1 ∩ R2
Common data for questions 14 and 15: Consider the fol-
lowing schema of a relational data base 19. Which of the following queries finds the clients of banker

student (sno, name, address) Agassi and the city they live in?
project (pno, Pname) work-on (sno, pno) (A)  pclient.cname.Ccity(sclient.cname = customer c name (sBanker.
Part (part no, part name, qtyon hand size) name = Aggassi
(client × customer)
Use (sno, pno, part no, number) (B) pClient.c city (sBanker name = ‘Aggasi’(client × customer)
14. List the names of the students who are participating in (C)  pclient.c name.Cucity(sclient.c name = ‘Aggasi’ (sclient.name = Cutomer
every project and have used every part. (client × customer)
(A)  sname(student ⋈(((Workon) ÷ spro(project)) ∩ (ssno, part (D)  p .c name.Cucity(sBankers name = name (sBanker. = agassi (cli-
no
(use) ÷ spart no (part))) ent × customer)
(B)  pname(student ⋈(((Workon) ÷ ppro(project)) ∩ (psno, 20. Consider the following schema pertaining to students data

partno
(use) ÷ spart no (part))) Student (rno, name, add)
(C) pname(student ⋈(((Workon) ÷ ppartno (project)) ∩ (psno, Enroll (rno, Cno, Cname) Where the primary keys are
partno
(use) ÷ spart no (part))) shown Underlined. The no. of tuples in the student and
(D) pname(student ∞ (((Workon) ÷ ppro(project)) ∪ (pssno, Enroll tables are 120 and 8 respectively. What are the
partno
(use) ÷ ppart no (part))) maximum and minimum no. of tuples that can be pre-
sent in (student * Enroll) where ‘*’ denotes natural join.
15. The following query gives pname (employee ⋈(work on ÷
(A) 8, 8 (B) 120, 8
ppro (sPname = ‘MS’ AND ‘MD’(project))) (C) 960, 8 (D) 960, 120
4.42 | Unit 4  •  Databases

Previous Years’ Questions


1. Consider the relation account (customer, balance) (C) There exist databases for which Query3 returns
where customer is a primary key and there are no null strictly fewer rows than Query2
values. We would like to rank customers according (D) There exist databases for which Query4 will en-
to decreasing balance. The customer with the largest counter an integrity violation at runtime
balance gets rank 1, ties are not broke but ranks are
skipped; if exactly two customers have the largest bal- 3. Consider the relation enrolled (student, course), in
ance they each get rank 1 and rank 2 is not assigned. which (student, course) is the primary key, and the
relation paid (student, amount) where student is the
 Query 1: select A.customer, count (B.customer) from primary key. Assume no null values and no foreign
account A, account B where A.balance <= B.balance keys or integrity constraints. Assume that amounts
group by A.customer 6000, 7000, 8000, 9000 and 10000 were each paid by
Query 2: select A.customer, 1 + count (B.balance) 20% of the students. Consider these query plans (plan
from account A, account B where A.balance < 1 on left, plan 2 on right) to ‘list all courses taken by
B.balance group by A.customer Consider these state- students who have paid more than x’
ments about Query1 and Query2. Enrolled Paid Enrolled Paid
1. Query1 will produce the same row set as Query2
for some but not all databases. Probe index Sequential Probe index Sequential scan
2. Both Query1 and Query2 are correct implementa- on student scan, select on student
tion of the specification. amout > x
3. Query1 is a correct implementation of the specifi-
cation but Query2 is not. Indexed nested loop join
Indexed nested loop join
4. Neither Query1 nor Query2 is a correct implemen-
Select on amount > x
tation of the specification.
Project on course
5. Assigning rank with a pure relational query takes
Project on course
less time than scanning in decreasing balance or-
der assigning ranks using ODBC.
Which two of the above statements are correct?[2006] A disk seek takes 4 ms, disk data transfer bandwidth
(A) 2 and 5 (B) 1 and 3 is 300 MB/s and checking a tuple to see if amount is
(C) 1 and 4 (D) 3 and 5 greater than x takes 10 ms. Which of the following
statements is correct? [2006]
2. Consider the relation enrolled (student, course) in (A) Plan 1 and Plan 2 will not output identical row
which (student, course) is the primary key, and the sets for all databases
relation paid (student, amount) where student is the (B) A course may be listed more than once in the
primary key. Assume no null values and no foreign output of Plan 1 for some databases
keys or integrity constraints. Given the following four (C) For x = 5000, Plan 1 executes faster than Plan 2
queries: for all databases
Query1: select student from enrolled where student in (D) For x = 9000, Plan 1 executes slower than Plan 2
(select student from paid) for all databases
Query2: select student from paid where student in (se- 4. Information about a collection of students is given by
lect student from enrolled) the relation studinfo (studId, name, sex). The rela-
tion enroll (studId, courseId) gives which student has
 Query3: select E.student from enrolled E, paid P enrolled for (or taken) what course(s). Assume that
where E.student = P.student every course is taken by at least one male and at least
Query4: select student from paid where exists (select one female student. What does the following rela-
* from enrolled where enrolled.student = paid.stu- tional algebra expression represent?
dent)
Πcourseld((Πstudid(ssex = ‘female’(studInfo))
Which one of the following statement is correct?[2006]
× Πcourseld (enroll)) - enroll) [2007]
(A) All queries return identical row sets for any data-
base (A) Courses in which all the female students are en-
(B) Query2 and Query4 return identical row sets for rolled
all databases but there exist databases for which (B) Courses in which a proper subset of female stu-
Query1 and Query2 return different row sets dents are enrolled.
Chapter 2  •  Structured Query Language  |  4.43

(C) Courses in which only male students are en- 8. Let R and S be relational schemes such that R =
rolled. {a,b,c} and S = {c}. Now consider the following que-
(D) None of the above ries on the database:
I. π R − S (r ) − π R − S (π R − S (r ) × s − π R − S , S (r ))
5. Consider the relation employee (name, sex, super-
visorName) with name as the key. supervisorName II. {t | t ∈ π R − S (r ) ∧ ∀u ∈ s (∃v ∈ r (u = v[ s ] ∧ t
gives the name of the supervisor of the employee = v[ R − S ]))}
under consideration. What does the following Tuple
Relational Calculus query produce? {t | t ∈ π R − S (r ) ∧ ∀v ∈ r (∃u ∈ s (u = v[ s ] ∧ t
III.
e ⋅ name | employee(e) ∧ = v[ R − S ]))}

(∀x)[¬employee( x) ∨ x ⋅ supervisor Name ≠ e ⋅ name ∨ IV. SELECT R.a, R.b


FROM R, S
 x ⋅ sex = "male"]} [2007] WHERE R.c = S.c
(A) Names of employees with a male supervisor. Which of the above queries are equivalent? [2009]
(B) Names of employees with no immediate male (A) I and II (B) I and III
subordinates. (C) II and IV (D) III and IV
(C) Names of employees with no immediate female
subordinates. Common data for questions 9 and 10: Consider the fol-
(D) Names of employees with a female supervisor. lowing relational schema: Suppliers (sid: integer, sname:
string, city: string, street: string) Parts(pid: integer, pname:
6. Consider the table employee (empId, name, depart-
string, color: string) Catalog (sid: integer, pid: integer,
ment, salary) and the two queries Q1, Q2 below.
cost: real)
Assuming that department 5 has more than one
employee, and we want to find the employees who 9. Consider the following relational query on the above
get higher salary than anyone in the department 5, database:
which one of the statements is TRUE for any arbi- SELECT  S.sname
trary employee table? FROM     Suppliers S
Q1: SELECT e.empId WHERE S.sid NOT IN (SELECT C.sid
FROM Catalog C
FROM employee e
WHERE C.pid NOT IN (SELECT P.pid FROM Parts P
WHERE not exists
WHERE P.color <> ‘blue’))
(Select * From employee s where s.department = ‘5’
and s.salary >=e.salary) Assume that relations corresponding to the above
schema are not empty. Which one of the following is
Q2: SELECT e.empId
the correct interpretation of the above query? [2009]
FROM employee e
(A) Find the names of all suppliers who have sup-
WHERE e.salary > Any plied a non-blue part.
(Select distinct salary From employee s Where (B) Find the names of all suppliers who have not sup-
s.department = ‘5’) [2007] plied a non-blue part.
(A) Q1 is the correct query (C) Find the names of all suppliers who have sup-
(B) Q2 is the correct query plied only blue parts.
(C) Both Q1 and Q2 produce the same answer. (D) Find the names of all suppliers who have not sup-
(D) Neither Q1 nor Q2 is the correct query plied only blue parts.
7. Let R and S be two relations with the following schema 10. A relational schema for a train reservation database is
R (P, Q, R1, R2, R3) given below
S (P, Q, S1, S2) Passenger (pid, pname, age)
Where {P, Q} is the key for both schemas. Which of Reservation (pid, cass, tid)
the following queries are equivalent? Table :Passenger
I. ΠP (R ⋈ S) Table :Reservation
II. ΠP (R) ⋈ ΠP (S)
Pid pname Age Pid class tid
III. ΠP (ΠP, Q (R) ∩ ΠP, Q (S))
IV. ΠP (ΠP, Q (R) – (ΠP, Q (R) – (ΠP, Q (S))) [2008] 0 ‘Sachin’ 65 0 ‘AC’ 8200

(A) Only I and II (B) Only I and III 1 ‘Rahul’ 66 1 ‘AC’ 8201
(C) Only I, II and III (D) Only I, III and IV 2 ‘Sourav’ 67 2 ‘SC’ 8201
4.44 | Unit 4  •  Databases

3 ‘Anil’ 69 5 ‘AC’ 8203 Let MX and MY denote the respective maximum values
of X and Y among all records in the table at any point
1 ‘SC’ 8204 in time. Using MX and MY, new records are inserted
3 ‘AC’ 8202 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 pids are returned by the following SQL query for the
What will be the output of the following SQL query
above instance of the tables?
after the steps mentioned above are carried out?
SELECT pid SELECT Y FROM T WHERE X = 7; [2011]
FROM Reservation (A) 127 (B) 255
WHERE class = ‘AC’ AND (C) 129 (D) 257
EXISTS (SELECT * 14. Which of the following statements are true about an
FROM Passenger SQL query?
WHERE age > 65 AND P: An SQL query can contain a HAVING clause
Passenger.pid = Reservation.pid) [2010] even if it does not have a GROUP BY clause
(A) 1, 0 (B) 1, 2 Q: An SQL query can contain a HAVING clause
(C) 1, 3 (D) 1, 5 only if it has a GROUP BY clause
11. Consider a relational table r with sufficient number of R: All attributes used in the GROUP BY clause must
records, having attributes A1, A2, … An and let 1 ≤ p ≤ n. appear in the SELECT clause
Two queries Q1 and Q2 are given below. S: Not all attributes used in the GROUP BY clause
need to appear in the SELECT clause  [2012]
Q1: π A1 … An (σ Ap=c (r )) where c is a constant.
(A) P and R (B) P and S
Q2: π A1 … An (σ c1 ≤ Ap ≤ c2 (r )) where c1 and c2 are constants. (C) Q and R (D) Q and S
The database can be configured to do ordered indexing 15. Suppose R1(A, B) and R2(C, D) are two relation
on AP or hashing on Ap. Which of the following state- schemas. Let r1 and r2 be the corresponding relation
ments is TRUE? [2011] instances. B is a foreign key that refers to C in R2.
(A) Ordered indexing will always outperform hash- If data in r1 and r2 satisfy referential integrity con-
ing for both queries straints, which of the following is always true?[2012]
(B) Hashing will always outperform ordered index- (A) ΠB (r1) – ΠC(r2) = ∅
ing for both queries. (B) ΠC(r2) – ΠB (r1) = ∅
(C) Hashing will outperform ordered indexing on (C) ΠB (r1) = ΠC (r2)
Q1, but not on Q2.
(D) Hashing will outperform ordered indexing on (D) ΠB (r1) – ΠC (r2) ≠ ∅
Q2, but not on Q1.
Common data for questions 16 and 17: Consider the fol-
12. Database table by name Loan_Records is given below.
lowing relations A, B and C:
Borrower Bank manager Loan amount (A)
Ramesh Sunderajan 10000.00 Id Name Age

Suresh Ramgopal 5000.00 12 Arun 60

Mahesh Sunderajan 7000.00 15 Shreya 24


99 Rohit 11
What is the output of the following SQL query?
SELECT count ( * ) (B)
FROM (Select Borrower, Bank_Manager FROM Id Name Age
Loan Records) AS S 15 Shreya 24
NATURAL JOIN 25 Hari 40
(SELECT Bank_Manager, Loan_Amount FROM 98 Rohit 20
Loan_Records) AS T; [2011] 99 Rohit 11
(A) 3 (B) 9 (C)
(C) 5 (D) 6 Id Phone Area
13. Consider a database table T containing two columns 10 2200 02
X and Y each of type integer. After the creation of the 99 2100 01
table, one record (X = 1, Y = 1) is inserted in the table.
Chapter 2  •  Structured Query Language  |  4.45

16. How many tuples does the result of the following 20. Given the following schema:
SQL query contain? Employees (emp–id, first-name, last– name, hire–
SELECT A.Id date, dept–id, salary)
FROM A  Departments (dept–id, dept–name, manager–id,
WHERE A. Age > ALL (SELECT B. Age location–id)
FROM B  you want to display the last names and hire dates of
WHERE B. Name = ‘Arun’) [2012] all latest hires in their respective departments in the
(A) 4 (B) 3 location ID 1700. You issue the following query:
(C) 0 (D) 1 SQL > SELECT last–name, hire–date
17. How many tuples does the result of the following FROM employees
relational algebra expression contain? Assume that WHERE (dept–id, hire–date) IN
the schema of A ∪ B is the same as that of A. (SELECT dept–id, MAX (hire–date)
(A⋃B) ⋈A.Id > 40 V C.Id <15C [2012]  FROM employees JOIN departments USING
(A) 7 (B) 4 (dept–id)
(C) 5 (D) 9 WHERE location–id = 1700
18. Consider the following relational schema. Students GROUP BY dept–id);
(rollno: integer, sname: string) Courses (courseno: What is the outcome? [2014]
integer, cname: string) Registration(rollno:integer,co (A) It executes but does not give the correct result.
urseno: integer, percent: real) (B) It executes and gives the correct result.
  Which of the following queries are equivalent to (C) It generates an error because of pair wise compari-
this query in English? son.
  ‘Find the distinct names of all students who score (D) It generates an error because the GROUP BY
more than 90% in the course numbered 107’ clause cannot be used with table joins in a sub-
(I) SELECT DISTINCT S.sname FROM Students query.
as S, Registration as R WHERE R.rollno=S.rollno 21. Given an instance of the STUDENTS relation as
AND R.courseno=107 AND R.percent>90 shown below:
(II) psname(σcourseno=107^percent>90 Registration⑅Students) Student Student
Student ID Name Student Email Age CPI
(III) {T |∃ S ∈ Students, ∃R∈ Registration (S.rollno=R.
rollno ∧ R.courseno=107 ∧ R.percent>90∧T. 2345 Shankar shaker @ math X 9.4
sname=S.sname)} 1287 Swati swati @ ee 19 9.5

(IV) {<SN> |∃SR∃RP (<SR, SN> ∈ Students ∧ <SR, 107, 7853 Shankar shankar @ cse 19 9.4

RP> ∈ Registration ∧ RP>90)} [2013] 9876 Swati swati @ mech 18 9.3

(A) I, II, III and IV (B) I, II and III only 8765 Ganesh ganesh@ civil 19 8.7

(C) I, II and IV only (D) II, III and IV only For (StudentName, StudentAge) to be a key for this
instance, the value X should NOT be equal to _____.
19. Given the following statements:  [2014]
S1: A foreign key declaration can always be replaced
22. Consider a join (relation algebra) between relations
by an equivalent check assertion in SQL.
(r(R)) and (s(S)) using the nested loop method. There
S2: Given the table R (a, b, c) where a and b together
are three buffers each of size equal to disk block size,
form the primary key, the following is a valid ta-
out of which one buffer is reserved for intermediate
ble definition.
results. Assuming size r(R) < size s(S), the join will
CREATE TABLE S (
have fewer number of disk block accesses if [2014]
a INTEGER
(A) Relation r(R) is in the outer loop
d INTEGER,
(B) Relation s(S) is in the outer loop
e INTEGER,
(C) Join selection factor between r(R) and s(S) is
PRIMARY KEY (d),
more than 0.5
FOREIGN KEY (a) references R)
(D) Join selection factor between r(R) and s(S) is less
Which one of the following statements is CORRECT? than 0.5
 [2014]
23. SQL allows duplicate tuples in relations, and corre-
(A) S1 is TRUE and S2 is FALSE
spondingly defines the multiplicity of tuples in the
(B) Both S1 and S2 are TRUE result of joins. Which one of the following queries
(C) S1 is FALSE and S2 is TRUE always gives the same answer as the nested query
(D) Both S1 and S2 are FALSE shown below:
4.46 | Unit 4  •  Databases

Select * from R where a in (select S. a from S)[2014] (C) Names of all the employees with none of their cus-
(A) Select R.* from R, S where R. a = S. a tomers having a ‘GOOD’ rating.
(B) Select distinct R * from R, S where R . a = S . a (D) Names of all the employees with all their customers
(C) Select R.* from R, (select distinct a from S) as S1 having a ‘GOOD’ rating.
where R.a = S1.a 2 7. SELECT operation in SQL is equivalent to [2015]
(D) Select R.* from R, S where R.a = S.a and is unique (A) The selection operation in relational algebra
R (B) The selection operation in relational algebra,
except that SELECT in SQL retains duplicates.
24. What is the optimized version of the relation algebra
(C) The projection operation in relational algebra.
expression π A1 (π A2 (σ F1 (σ F2 ( r ) ))), where A1, A2 are sets
(D) The projection operation in relational algebra,
of attributes in r with A1 ⊂ A2 and F1, F2 are Boolean except that SELECT in SQL retains duplicates.
expressions based on the attributes in r? [2014]
28. Consider the following relations:
π A1 (σ ( F ∧ F )( r ) )
(A)
1 2
Student
π A1 (σ ( F ∨ F )( r ) )
(B) Roll No Student Name
1 2

π A2 (σ ( F ∧ F )( r ) )
(C) 1 Raj
1 2
2 Rohit
π A2 (σ ( F ∨ F )( r ) )
(D) 3 Raj
1 2

25. Consider the relational schema given below, where Performance


eld of the relation dependent is a foreign key refer-
Roll No Course Marks
ring to empId of the relation employee. Assume that
every employee has at least one associated dependent 1 Math 80
in the dependent relation. 1 English 70
Consider the following relational algebra query: 2 Math 75
employee (empId, empName, empAge) 3 English 80
dependent (depId, eId, depName, depAge)
2 Physics 65
pempId(employee)- pempId (employee ⋈ (empId = eID) ∧ (empAge ≤
3 Math 80
depAge)
dependent)
The above query evaluates to the set of empIds of em- Consider the following SQL query.
ployees whose age is greater than that of  [2014]
SELECT S.Student_Name, sum (P.Marks)
(A) some dependent.
FROM Student S, Performance P
(B) all dependents.
WHERE S.Roll_No = P.Roll_No
(C) some of his/her dependents.
GROUP BY S.Student_Name
(D) all of his/her dependents.
The number of rows that will be returned by the SQL
26. Consider the following relational schema: query is ______ [2015]
employee (empId, empName, empDept)
customer(custId, custName, salesRepid, rating) 29. Consider two relations R1(A, B) with the tuples (1, 5),
salesRepId is a foreign key referring to empId of the (3, 7) and R2(A, C) = (1, 7), (4, 9). Assume that R(A, B,
employee relation. Assume that each employee makes C) is the full natural outer join of R1 and R2. Consider
a sale to at least one customer. What does the follow- the following tuples of the form (A, B, C): a = (1, 5,
ing query return? null), b = (1, null, 7), c = (3, null, 9), d = (4, 7, null), e
SELECT empName = (1, 5, 7), f = (3, 7, null), g = (4, null, 9). Which one
FROM employee E of the following statements is correct? [2015]
WHERE NOT EXISTS (A) R contains a, b, e, f, g but not c, d.
(SELECT custId (B) R contains all of a, b, c, d, e, f, g.
FROM customer C (C) R contains e, f, g but not a, b.
WHERE C.salesRepId = E.empId (D) R contains e but not f, g.
AND C.Rating < > ‘GOOD’); [2014] 3 0. Consider the following relation
(A) Names of all the employees with at least one of
Cinema (theater, address, capacity)
their customers having a ‘GOOD’ rating.
(B) Names of all the employees with at most one of Which of the following options will be needed at the
their customers having a ‘GOOD’ rating. end of the SQL query
Chapter 2  •  Structured Query Language  |  4.47

SELECT P1.address (D) WHERE P1.capacity > Any (select max(P2.


FROM Cinema P1 capacity) from Cinema P2)
such that it always finds the addresses of theaters with 31. Which of the following is NOT a superkey in a rela-
maximum capacity? [2015] tional schema with attributes V, W, X, Y, Z and primary
(A) WHERE P1.capacity > = All (select P2. Capacity key VY? [2016]
from Cinema P2) (A)  V XYZ (B)  V WXZ
(B) WHERE P1.capacity >= Any (select P2. Capacity (C)  V WXY (D)  V WXYZ
from Cinema P2) 32. Consider a database that has the relation schema EMP
(C) WHERE P1.capacity > All (select max(P2. (EmpId, EmpName and DeptName). An instance of
capacity) from Cinema P2) the schema EMP and a SQL query on it are given
below.

EMP
EmpId EmpName DeptName
1 XYA AA SELECTIVE AVG ( EC.Num )
2 XYB AA FROM EC
3 XYC AA
WHERE ( DeptName, Num ) IN
4 XYD AA
(SELECT DeptName, COUNT ( EmpId ) AS
5 XYE AB
6 XYF AB EC ( DeptName, Num )
7 XYG AB FROM EMP
8 XYH AC GROUP BY DeptName)
9 XYI AC
10 XYJ AC
11 XYK AD
12 XYL AD
13 XYM AE

The output of executing the SQL query is ______.


CR
 [2017]
StudentName CourseName
33. Consider a database that has the relation sche-
SA CA
mas EMP(EmpId, EmpName, DeptId), and
DEPT(DeptName, DeptId), Note that the DeptId SA CB
can be permitted to be NULL in the relation EMP. SA CC
Consider the following queries on the database SB CB
expressed in tuple relational calculus. SB CC
(I) {t | ∃u ∈ EMP(t[EmpName] = u[EmpName] ∧ ∀ SC CA
v ∈ DEPT(t[DeptId] ≠ v[DeptId]))} SC CB
(II) {t | ∃u ∈ EMP(t[EmpName] = u[EmpName] ∧ ∃
SC CC
v ∈ DEPT(t[DeptId] ≠ v[DeptId]))}
(III) {t | ∃u ∈ EMP(t[EmpName] = u[EmpName] ∧ ∃ SD CA
v ∈ DEPT(t[DeptId] = v[DeptId]))} SD CB

Which of the above queries are safe? [2017] SD CC


(A) (I) and (II) only SD CD
(B) (I) and (III) only SE CD
(C) (II) and (III) only SE CA
(D) (I), (II) and (III) SE CB
34. Consider a database that has the relation schema CR SF CA
(studentName, CourseName). An instance of the SF CB
schema CR is as given below.
SF CC
4.48 | Unit 4  •  Databases

The following query is made on the database. 36. Consider the following two tables and four queries in
SQL.
T 1 ← pCouraseName (sStudentName =' SA ' (CR))
Book (isbn, bname), Stock (isbn, copies)
T 2 ← CR ÷ T 1 Query 1: SELECT B.isbn, S.copies
The number of rows in T2 is . [2017] FROM Book B INNER JOIN Stock S
35. Consider the following database table named ON B.isbn = S.isbn;
top_scorer. Query 2: SELECT B.isbn, S.copies
FROM Book B LEFT OUTER
top_scorer
JOIN Stock S
player country goals
ON B.isbn = S.isbn;
Klose Germany 16
Query 3: SELECT B.isbn, S.copies
Ronaldo Brazil 15 FROM Book B RIGHT OUTER
G Miiller Germany 14 JOIN Stock S
Fontaine France 13 ON B.isbn = S.isbn;
Pelé Brazil 12 Query 4: SELECT B.isbn, S.copies
Klinsmann Germany 11 FROM Book B FULL OUTER
Kocsis Hungary 11 JOIN Stock S
ON B.isbn = S.isbn;
Batistuta Argentina 10
Cubillas Peru 10 Which one of the queries above is certain to have an
Lato Poland 10
output that is a superset of the outputs of the other
three queries? [2018]
Lineker England 10
(A) Query 1 (B) Query 2
T Muller Germany 10
(C) Query 3 (D) Query 4
Rahn Germany 10
37. Consider the relations r(A, B) and s(B, C), where s ⋅ B
Consider the following SQL query: is a primary key and r ⋅ B is a foreign key referencing
SELECT ta.player FROM top_scorer AS ta s ⋅ B. Consider the query
WHERE ta.goals >ALL (SELECT tb.goals Q: r  (σB<5 (S))
FROM top_scorer AS tb Let LOJ denote the natural left outer-join operation.
WHERE tb.country = ‘Spain’) Assume that r and s contain no null values.
AND ta.goals >ANY (SELECT tc.goals
Which one of the following queries is NOT equiva-
FROM top_scorer AS tc
lent to Q? [2018]
WHERE tc. country = ‘Germany’)
(A) σB<5(r  s) (B) σB<5(r LOJ s)
The number of tuples returned by the above SQL (C) r LOJ (σB<5(s)) (D) σB<5(r) LOJ s
query is _________. [2017]

Answer Keys
Exercises
Practice Problems 1
1. A 2. B 3. C 4. (i) B   (ii) D   (iii) D 5. C 6. C 7. (i) A   (ii) C
8. (i) B   (ii) A 9. A 10. A 11. (i) A   (ii) B 12. (i) B  (ii) B  (iii) 
A
13.  (i) 
A  (ii)  A 14. (i) 
A  (iii)  A  (ii)  A  (iii) A 15. (i) A  (ii)  A 16. C
A  (iii) 
17. A 18. D 19. A 20. D

Practice Problems 2
1. B 2. D 3. D 4. A 5. C 6. A 7. A 8. A 9. A 10. A
11. C 12. C 13. C 14. C 15. C 16. B 17. C 18. D 19. B 20. A

Previous Years’ Questions


1. C 2. A 3. C 4. B 5. C 6. B 7. D 8. A 9. A 10. C
11. C 12. C 13. A 14. C 15. A 16. B 17. A 18. A 19. D 20. B
21. 19 22. A 23. C 24. A 25. D 26. D 27. D 28. 2 29. C 30. A
31. B 32. 2.6 33. D 34. 4 35. 7 36. D 37. C

You might also like